// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! One level being played: a board, the lives left, and whether it has been //! won or lost. const std = @import("std"); const Board = @import("Board.zig"); const Game = @This(); pub const max_lives = 3; pub const State = enum { playing, won, lost }; /// The game takes ownership of the board. board: Board, lives: u8 = max_lives, state: State = .playing, pub fn init(board: Board) Game { return .{ .board = board, .state = if (board.remaining == 0) .won else .playing, }; } pub fn deinit(game: *Game, gpa: std.mem.Allocator) void { game.board.deinit(gpa); game.* = undefined; } /// Taps `arrow`. A tap on an arrow that has already left, or after the /// level is over, is ignored and returns null. pub fn tap(game: *Game, arrow: Board.ArrowIndex) ?Board.Outcome { if (game.state != .playing or !game.board.isPresent(arrow)) return null; const outcome = game.board.tap(arrow); switch (outcome) { .exit => if (game.board.remaining == 0) { game.state = .won; }, .block => { game.lives -= 1; if (game.lives == 0) game.state = .lost; }, } return outcome; } /// Starts the level over: every arrow back, every life back. pub fn restart(game: *Game) void { game.board.reset(); game.lives = max_lives; game.state = if (game.board.remaining == 0) .won else .playing; } const testing = std.testing; fn d(x: u16, y: u16) Board.Dot { return .{ .x = x, .y = y }; } /// Arrow 0 points right at arrow 1, which points up and out. fn blockedPair() !Game { return .init(try .init(testing.allocator, 4, 2, &.{ &.{ d(0, 1), d(1, 1) }, &.{ d(3, 1), d(3, 0) }, })); } test "clearing the board wins" { var game = try blockedPair(); defer game.deinit(testing.allocator); try testing.expectEqual(Board.Outcome.exit, game.tap(1).?); try testing.expectEqual(State.playing, game.state); try testing.expectEqual(Board.Outcome.exit, game.tap(0).?); try testing.expectEqual(State.won, game.state); try testing.expectEqual(max_lives, game.lives); } test "a block costs a life, and the last one loses" { var game = try blockedPair(); defer game.deinit(testing.allocator); for (0..max_lives) |i| { try testing.expectEqual(State.playing, game.state); try testing.expect(game.tap(0).? == .block); try testing.expectEqual(max_lives - 1 - i, game.lives); } try testing.expectEqual(State.lost, game.state); // Nothing more happens once the level is lost. try testing.expectEqual(null, game.tap(1)); } test "a tap on an arrow that has gone is ignored" { var game = try blockedPair(); defer game.deinit(testing.allocator); _ = game.tap(1); try testing.expectEqual(null, game.tap(1)); try testing.expectEqual(max_lives, game.lives); } test "restart puts the arrows and the lives back" { var game = try blockedPair(); defer game.deinit(testing.allocator); _ = game.tap(0); _ = game.tap(1); game.restart(); try testing.expectEqual(max_lives, game.lives); try testing.expectEqual(2, game.board.remaining); try testing.expectEqual(State.playing, game.state); }