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