messing with the snake game
authorBrendan Hansen <brendan.f.hansen@gmail.com>
Tue, 23 Nov 2021 19:53:49 +0000 (13:53 -0600)
committerBrendan Hansen <brendan.f.hansen@gmail.com>
Tue, 23 Nov 2021 19:53:49 +0000 (13:53 -0600)
tests/snake.onyx

index 9550c5762386835ebab0c9576074fdc7db2c6254..db26970e7f4913adb2da5d710268be8de0ca710c 100644 (file)
@@ -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);
+}