v / examples / hot_reload
Raw file | 84 loc (77 sloc) | 1.62 KB | Latest commit hash e81e0ac70
1// Build this example with
2// v -live bounce.v
3module main
4
5import gx
6import gg
7import time
8
9struct Game {
10mut:
11 gg &gg.Context = unsafe { nil }
12 x int
13 y int
14 dy int
15 dx int
16 height int
17 width int
18 draw_fn voidptr
19}
20
21const (
22 window_width = 400
23 window_height = 300
24 width = 50
25)
26
27fn main() {
28 mut game := &Game{
29 gg: 0
30 dx: 2
31 dy: 2
32 height: window_height
33 width: window_width
34 draw_fn: 0
35 }
36 game.gg = gg.new_context(
37 width: window_width
38 height: window_height
39 font_size: 20
40 user_data: game
41 window_title: 'Hot code reloading demo'
42 create_window: true
43 frame_fn: frame
44 bg_color: gx.white
45 )
46 // window.onkeydown(key_down)
47 println('Starting the game loop...')
48 spawn game.run()
49 game.gg.run()
50}
51
52// Try uncommenting or changing the lines inside the live functions.
53// Guess what will happen:
54[live]
55fn frame(mut game Game) {
56 game.gg.begin()
57 game.gg.draw_text_def(10, 5, 'Modify examples/hot_reload/bounce.v to get instant updates')
58 game.gg.draw_rect_filled(game.x, game.y, width, width, gx.blue)
59 game.gg.draw_rect_filled(window_width - width - game.x + 10, 200 - game.y + width,
60 width, width, gx.rgb(228, 10, 55))
61 game.gg.draw_rect_filled(game.x - 25, 250 - game.y, width, width, gx.rgb(28, 240,
62 55))
63 game.gg.end()
64}
65
66[live]
67fn (mut game Game) update_model() {
68 speed := 2
69 game.x += speed * game.dx
70 game.y += speed * game.dy
71 if game.y >= game.height - width || game.y <= 0 {
72 game.dy = -game.dy
73 }
74 if game.x >= game.width - width || game.x <= 0 {
75 game.dx = -game.dx
76 }
77}
78
79fn (mut game Game) run() {
80 for {
81 game.update_model()
82 time.sleep(16 * time.millisecond) // 60fps
83 }
84}