From f7edc75ef897ed0f1bd12f02f8c72b51cc900dbd Mon Sep 17 00:00:00 2001 From: Brendan Hansen Date: Tue, 23 Nov 2021 13:53:49 -0600 Subject: [PATCH] messing with the snake game --- tests/snake.onyx | 45 ++++++++++++++++++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/tests/snake.onyx b/tests/snake.onyx index 9550c57..db26970 100644 --- a/tests/snake.onyx +++ b/tests/snake.onyx @@ -5,8 +5,16 @@ use package core Vec2 :: struct (T: type_expr) { x, y: T; - convert :: (use this: ^Vec2($T), $R: type_expr) -> Vec2(R) { - return .{ cast(R) x, cast(R) y }; + convert :: (this: ^Vec2($T), $R: type_expr) -> Vec2(R) { + return .{ cast(R) this.x, cast(R) this.y }; + } + + rotate_left :: (this: ^Vec2($T)) -> Vec2(T) { + return .{ this.y, -this.x }; + } + + rotate_right :: (this: ^Vec2($T)) -> Vec2(T) { + return .{ -this.y, this.x }; } } #operator + (v1, v2: Vec2($T)) => Vec2(T).{ v1.x + v2.x, v1.y + v2.y }; @@ -27,8 +35,10 @@ snake_make :: (head: Vec2i) -> Snake { s: Snake; s.head = head; s.direction = .{ 1, 0 }; + array.init(^s.body); - for i: 4 do s.body << head; + for i: 10 do s.body << head; + return s; } @@ -58,9 +68,11 @@ snake_draw :: (use this: ^Snake, cell_size: f32) { the_snake: Snake; +the_food: Vec2i; load :: () { the_snake = snake_make(.{ 0, 0 }); + the_food = .{ 10, 10 }; } update :: (dt: f32) { @@ -68,13 +80,23 @@ update :: (dt: f32) { hb.window.setShouldClose(true); } - if hb.input.keyIsDown(.Left) do the_snake.direction = .{ -1, 0 }; - if hb.input.keyIsDown(.Right) do the_snake.direction = .{ 1, 0 }; - if hb.input.keyIsDown(.Up) do the_snake.direction = .{ 0, -1 }; - if hb.input.keyIsDown(.Down) do the_snake.direction = .{ 0, 1 }; + #persist last_left_down := false; + #persist last_right_down := false; + + left_down := hb.input.keyIsDown(.Left); + right_down := hb.input.keyIsDown(.Right); + + if !left_down && last_left_down { the_snake.direction = the_snake.direction->rotate_left(); snake_timer = 0; } + if !right_down && last_right_down { the_snake.direction = the_snake.direction->rotate_right(); snake_timer = 0; } + + last_left_down = left_down; + last_right_down = right_down; #persist snake_timer := 1.0f; snake_timer -= dt; + + if hb.input.keyIsDown(.Up) do snake_timer -= 3 * dt; + if snake_timer <= 0 { snake_timer = 0.2; snake_move(^the_snake); @@ -85,5 +107,10 @@ draw :: () { hb.graphics.setClearColor(0.1, 0.1, 0.1); hb.graphics.clear(); - snake_draw(^the_snake, 32); -} \ No newline at end of file + cell_size :: 32.0f; + + snake_draw(^the_snake, cell_size); + + hb.graphics.setColor(0.8, 0.9, 0.1); + hb.graphics.circle(.Fill, cell_size * ~~the_food.x + cell_size / 2, cell_size * ~~the_food.y + cell_size / 2, cell_size / 2); +} -- 2.25.1