diff --git a/src/game.zig b/src/game.zig index 37513fe..3c1fde3 100644 --- a/src/game.zig +++ b/src/game.zig @@ -33,11 +33,14 @@ const Game = struct { body: std.ArrayList(Vec2), state: State, - pub fn create(allocator: std.mem.Allocator) !Game { + pub fn createWithSize(allocator: std.mem.Allocator, bodySize: u8) !Game { var body = try std.ArrayList(Vec2).initCapacity(allocator, 1000); - try body.append(Vec2{ 10, 10 }); - try body.append(Vec2{ 9, 10 }); - try body.append(Vec2{ 8, 10 }); + + const startPos: u8 = 10; + for (0..bodySize) |i| { + const index = std.math.cast(i32, i) orelse unreachable; + try body.append(Vec2{ startPos - index, 10 }); + } return Game{ .playFieldSize = Vec2{ 20, 20 }, @@ -48,6 +51,10 @@ const Game = struct { }; } + pub fn create(allocator: std.mem.Allocator) !Game { + return createWithSize(allocator, 3); + } + pub fn deinit(self: *Game) void { self.body.deinit(); } @@ -79,6 +86,14 @@ const Game = struct { self.state = State.lost; return; } + + for (self.body.items) |pos| { + if (std.meta.eql(pos, newHead)) { + self.state = State.lost; + return; + } + } + try self.body.insert(0, newHead); _ = self.body.pop(); } @@ -138,7 +153,27 @@ test "should loose if exiting playField right" { try testing.expectEqual(State.lost, game.state); } -test "should loose if eating itself" {} +test "should loose if touching tail" { + const allocator = testing.allocator; + + var game = try Game.createWithSize(allocator, 4); + defer game.deinit(); + + game.setDirection(Direction.down); + try game.tick(); + game.setDirection(Direction.left); + try game.tick(); + try testing.expectEqual(State.running, game.state); + game.setDirection(Direction.up); + try game.tick(); + try testing.expectEqual(State.lost, game.state); + + const expected = [_]Vec2{ Vec2{ 9, 11 }, Vec2{ 10, 11 }, Vec2{ 10, 10 }, Vec2{ 9, 10 } }; + try testing.expectEqualSlices(Vec2, &expected, game.body.items); + + try testing.expectEqual(State.lost, game.state); +} + test "should grow if eating food" {} test "should win if no space is left" {} test "should tick if running" {}