feat: add second loose condition

This commit is contained in:
2025-07-23 20:49:51 +02:00
parent d6175bb84a
commit 7d087a80cb

View File

@@ -33,11 +33,14 @@ const Game = struct {
body: std.ArrayList(Vec2), body: std.ArrayList(Vec2),
state: State, 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); var body = try std.ArrayList(Vec2).initCapacity(allocator, 1000);
try body.append(Vec2{ 10, 10 });
try body.append(Vec2{ 9, 10 }); const startPos: u8 = 10;
try body.append(Vec2{ 8, 10 }); for (0..bodySize) |i| {
const index = std.math.cast(i32, i) orelse unreachable;
try body.append(Vec2{ startPos - index, 10 });
}
return Game{ return Game{
.playFieldSize = Vec2{ 20, 20 }, .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 { pub fn deinit(self: *Game) void {
self.body.deinit(); self.body.deinit();
} }
@@ -79,6 +86,14 @@ const Game = struct {
self.state = State.lost; self.state = State.lost;
return; return;
} }
for (self.body.items) |pos| {
if (std.meta.eql(pos, newHead)) {
self.state = State.lost;
return;
}
}
try self.body.insert(0, newHead); try self.body.insert(0, newHead);
_ = self.body.pop(); _ = self.body.pop();
} }
@@ -138,7 +153,27 @@ test "should loose if exiting playField right" {
try testing.expectEqual(State.lost, game.state); 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 grow if eating food" {}
test "should win if no space is left" {} test "should win if no space is left" {}
test "should tick if running" {} test "should tick if running" {}