// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A game being played on a screen: the rules' `Game`, the level it is, //! and how each arrow is moving. What the rules decide at once, this shows //! over time — an exit sliding off the board, a block bumping against its //! blocker — and it moves from level to level when one is won, or starts a //! level over when it is lost. //! //! Time is whatever the caller says it is, in nanoseconds on a clock that //! only goes forward; nothing here reads a clock. const std = @import("std"); const Allocator = std.mem.Allocator; const rules = @import("rules"); const Board = rules.Board; const Game = rules.Game; const draw = @import("draw.zig"); const Layout = @import("Layout.zig"); const Point = draw.Point; const Play = @This(); /// How long things take, in nanoseconds, and how fast they go, in dots per /// second. pub const timing = struct { /// An exit starts at this speed and speeds up. pub const exit_speed = 12.0; pub const exit_acceleration = 80.0; /// A bump goes out and back at this speed. pub const bump_speed = 20.0; /// How long a life lost shows the block color for. pub const life_flash = 330 * std.time.ns_per_ms; /// How long the board celebrates a level won before the next. pub const celebrate = 700 * std.time.ns_per_ms; /// How long a lost level shows before it starts over. pub const lost = 900 * std.time.ns_per_ms; }; /// The shapes things are drawn with, in dot spacings. const geometry = struct { const dot_radius = 0.07; const line_radius = 0.09; /// The arrowhead: its tip ahead of the head's dot, its base behind it, /// and half its width. const tip = 0.42; const base = 0.08; const half_width = 0.24; const life_radius = 0.16; const life_gap = 0.5; }; /// How an arrow is moving, if it is. pub const Motion = union(enum) { still, /// Leaving the board, since `start`. exiting: i64, /// Blocked at `start`: bumping against its blocker and back, and in the /// block color from then until it leaves the board or the level starts /// over. bumping: struct { start: i64, gap: u16 }, }; gpa: Allocator, level: rules.level.Number, game: Game, motions: []Motion, /// When each life was lost, for its flash. lost_at: [Game.max_lives]?i64 = @splat(null), /// When the level was won or lost. ended_at: ?i64 = null, pub fn init(gpa: Allocator, level: rules.level.Number) !Play { var board = try rules.level.board(gpa, level); errdefer board.deinit(gpa); const motions = try gpa.alloc(Motion, board.arrowCount()); @memset(motions, .still); return .{ .gpa = gpa, .level = level, .game = .init(board), .motions = motions }; } pub fn deinit(p: *Play) void { p.game.deinit(p.gpa); p.gpa.free(p.motions); p.* = undefined; } /// The board's layout in a window of `width` by `height` pixels. pub fn layout(p: *const Play, width: f32, height: f32) Layout { return .fit(p.game.board.width, p.game.board.height, width, height); } /// The same, within the part of a window that is `width` by `height` with /// its top left corner at `corner`. pub fn layoutIn(p: *const Play, corner: draw.Point, width: f32, height: f32) Layout { return .fitIn(p.game.board.width, p.game.board.height, corner, width, height); } /// A tap at `point`: on an arrow, it exits or is blocked. Anywhere else, or /// once the level is over, nothing happens. pub fn tap(p: *Play, l: Layout, point: Point, now: i64) void { const dot = l.dotAt(point) orelse return; const arrow = p.game.board.arrowAt(dot) orelse return; const outcome = p.game.tap(arrow) orelse return; switch (outcome) { .exit => p.motions[arrow] = .{ .exiting = now }, .block => |b| { p.motions[arrow] = .{ .bumping = .{ .start = now, .gap = b.gap } }; p.lost_at[p.game.lives] = now; }, } if (p.game.state != .playing) p.ended_at = now; } /// Starts the level over, with every life back. pub fn restart(p: *Play) void { p.game.restart(); @memset(p.motions, .still); p.lost_at = @splat(null); p.ended_at = null; } /// Moves on once a level won has been celebrated, or starts a lost one /// over once it has been seen. Returns the new level's number when it /// moved on, for the caller to remember. pub fn update(p: *Play, now: i64) !?rules.level.Number { const ended = p.ended_at orelse return null; switch (p.game.state) { .playing => return null, .lost => if (now - ended >= timing.lost) p.restart(), .won => if (now - ended >= timing.celebrate) { var next = try init(p.gpa, p.level + 1); errdefer next.deinit(); p.deinit(); p.* = next; return p.level; }, } return null; } /// Whether anything is still moving, or will change by itself, so that /// another frame is wanted. pub fn animating(p: *const Play, now: i64) bool { if (p.ended_at != null) return true; for (p.lost_at) |at| if (at) |t| if (now - t < timing.life_flash) return true; for (p.motions, 0..) |m, i| switch (m) { .still => {}, .exiting => |start| if (exitDistance(&p.game.board, @intCast(i), seconds(now - start)) != null) return true, .bumping => |b| if (bumpDistance(b.gap, seconds(now - b.start)) != null) return true, }; return false; } /// Appends the frame at `now` to `list`. pub fn render(p: *const Play, l: Layout, theme: draw.Theme, now: i64, list: *draw.List) Allocator.Error!void { const gpa = p.gpa; const board = &p.game.board; const sp = l.spacing; const celebrating = p.game.state == .won; const dot_color = if (celebrating) theme.accent else theme.dot; for (0..board.height) |y| for (0..board.width) |x| { try list.append(gpa, .{ .shape = .{ .circle = .{ .center = l.center(.{ .x = @intCast(x), .y = @intCast(y) }), .radius = geometry.dot_radius * sp } }, .color = dot_color, }); }; var buffer: std.ArrayList(Point) = .empty; defer buffer.deinit(gpa); for (p.motions, 0..) |m, i| { const arrow: Board.ArrowIndex = @intCast(i); var shift: f32 = 0; var color = theme.arrow; var opacity: f32 = 1; switch (m) { .still => if (!board.isPresent(arrow)) continue, .exiting => |start| { const t = seconds(now - start); shift = exitDistance(board, arrow, t) orelse continue; color = theme.accent; // Fading over the last stretch, as it leaves the board. const ray = rayLength(board, arrow); const len: f32 = @floatFromInt(board.path(arrow).len); opacity = 1 - (shift - ray) / (len + 1); }, .bumping => |b| { shift = bumpDistance(b.gap, seconds(now - b.start)) orelse 0; color = theme.block; }, } try buffer.resize(gpa, board.path(arrow).len + 2); const body = window(board.path(arrow), board.heading(arrow), shift, buffer.items); try arrowShapes(gpa, l, body, board.heading(arrow), draw.mix(color, theme.background, opacity), list); } // The lives, filled while they last. for (0..Game.max_lives) |i| { const offset = (@as(f32, @floatFromInt(i)) - @as(f32, Game.max_lives - 1) / 2) * geometry.life_gap * sp; const lit = i < p.game.lives; const flashing = if (p.lost_at[i]) |t| now - t < timing.life_flash else false; try list.append(gpa, .{ .shape = .{ .circle = .{ .center = l.lives_center + Point{ offset, 0 }, .radius = geometry.life_radius * sp } }, .color = if (flashing) theme.block else if (lit) theme.arrow else theme.dot, }); } } fn arrowShapes(gpa: Allocator, l: Layout, body: []const Point, heading: Board.Heading, color: draw.Color, list: *draw.List) Allocator.Error!void { const r = geometry.line_radius * l.spacing; for (body[0 .. body.len - 1], body[1..]) |a, b| { try list.append(gpa, .{ .shape = .{ .segment = .{ .a = l.at(a), .b = l.at(b), .radius = r } }, .color = color }); } const head = body[body.len - 1]; const d = direction(heading); const side: Point = .{ -d[1], d[0] }; const s = struct { fn by(v: Point, k: f32) Point { return v * @as(Point, @splat(k)); } }.by; const base = head - s(d, geometry.base); try list.append(gpa, .{ .shape = .{ .triangle = .{ .a = l.at(head + s(d, geometry.tip)), .b = l.at(base + s(side, geometry.half_width)), .c = l.at(base - s(side, geometry.half_width)), } }, .color = color, }); } /// The arrow's body moved `shift` dots along its own path and on out along /// its heading, as dot coordinates from tail to head, written into `out` /// (at least the path's length plus two) and returned. /// /// The body follows the head like a snake: what was the tail moves up /// along where the rest of the arrow was, and past the head everything /// moves in a straight line. pub fn window(path: []const Board.Dot, heading: Board.Heading, shift: f32, out: []Point) []Point { const len: f32 = @floatFromInt(path.len - 1); var n: usize = 0; out[n] = along(path, heading, shift); n += 1; // Every corner strictly inside the stretch. const first: usize = @intFromFloat(@floor(shift) + 1); var i = first; while (i < path.len and @as(f32, @floatFromInt(i)) < shift + len) : (i += 1) { out[n] = dotPoint(path[i]); n += 1; } out[n] = along(path, heading, shift + len); n += 1; return out[0..n]; } /// The point `t` dots along the path from its tail, and past its head along /// its heading. fn along(path: []const Board.Dot, heading: Board.Heading, t: f32) Point { const last = path.len - 1; const len: f32 = @floatFromInt(last); if (t >= len) return dotPoint(path[last]) + direction(heading) * @as(Point, @splat(t - len)); const i: usize = @intFromFloat(@floor(@max(t, 0))); const f = t - @as(f32, @floatFromInt(i)); const a = dotPoint(path[i]); const b = dotPoint(path[i + 1]); return a + (b - a) * @as(Point, @splat(f)); } fn dotPoint(d: Board.Dot) Point { return .{ @floatFromInt(d.x), @floatFromInt(d.y) }; } fn direction(h: Board.Heading) Point { return switch (h) { .up => .{ 0, -1 }, .right => .{ 1, 0 }, .down => .{ 0, 1 }, .left => .{ -1, 0 }, }; } /// How many dots lie between an arrow's head and the edge. fn rayLength(board: *const Board, arrow: Board.ArrowIndex) f32 { var ray = board.rayFrom(arrow); var n: f32 = 0; while (ray.next()) |_| n += 1; return n; } /// How far an exiting arrow has gone after `t` seconds, or null once it is /// gone: off the board, and its length again past that, by which time it /// has faded away. fn exitDistance(board: *const Board, arrow: Board.ArrowIndex, t: f32) ?f32 { const s = timing.exit_speed * t + timing.exit_acceleration * t * t / 2; const len: f32 = @floatFromInt(board.path(arrow).len); if (s >= rayLength(board, arrow) + len + 1) return null; return s; } /// How far a blocked arrow has bumped forward after `t` seconds, or null /// once it is back. It goes until its arrowhead touches the line of the /// blocker, which runs through the dot `gap + 1` ahead. fn bumpDistance(gap: u16, t: f32) ?f32 { const reach = @as(f32, @floatFromInt(gap)) + 1 - geometry.tip - geometry.line_radius; const travelled = timing.bump_speed * t; if (travelled >= 2 * reach) return null; return reach - @abs(reach - travelled); } fn seconds(ns: i64) f32 { return @as(f32, @floatFromInt(ns)) / std.time.ns_per_s; } const testing = std.testing; fn dt(x: u16, y: u16) Board.Dot { return .{ .x = x, .y = y }; } test "a still arrow's window is its path" { var buf: [8]Point = undefined; const path = [_]Board.Dot{ dt(0, 0), dt(1, 0), dt(1, 1) }; const w = window(&path, .down, 0, &buf); try testing.expectEqualSlices(Point, &.{ .{ 0, 0 }, .{ 1, 0 }, .{ 1, 1 } }, w); } test "a moving arrow's body follows its head round the corner" { var buf: [8]Point = undefined; const path = [_]Board.Dot{ dt(0, 0), dt(1, 0), dt(1, 1) }; // Half a dot on: the tail halfway to the corner, the head halfway out, // passing through the corner and where the head was. const half = window(&path, .down, 0.5, &buf); try testing.expectEqualSlices(Point, &.{ .{ 0.5, 0 }, .{ 1, 0 }, .{ 1, 1 }, .{ 1, 1.5 } }, half); // Past the corner, it is a straight line. const past = window(&path, .down, 1.5, &buf); try testing.expectEqualSlices(Point, &.{ .{ 1, 0.5 }, .{ 1, 1 }, .{ 1, 2.5 } }, past); const out = window(&path, .down, 3, &buf); try testing.expectEqualSlices(Point, &.{ .{ 1, 2 }, .{ 1, 4 } }, out); } test "a bump goes until the arrowhead touches the blocker and comes back" { // Right next to the blocker: the tip already reaches most of the way. const reach: f32 = 1 - geometry.tip - geometry.line_radius; try testing.expectEqual(0, bumpDistance(0, 0).?); try testing.expectApproxEqAbs(reach, bumpDistance(0, reach / timing.bump_speed).?, 1e-6); try testing.expectEqual(null, bumpDistance(0, 2 * reach / timing.bump_speed + 1e-4)); } const ms = std.time.ns_per_ms; /// A play of a known board rather than a generated one. fn testPlay(source: []const u8) !Play { const gpa = testing.allocator; var board = try rules.text.parse(gpa, source); errdefer board.deinit(gpa); const motions = try gpa.alloc(Motion, board.arrowCount()); @memset(motions, .still); return .{ .gpa = gpa, .level = 1, .game = .init(board), .motions = motions }; } test "tapping an arrow that can leave sends it off, and it is drawn going" { var p = try testPlay("4x2\n0,1 1,1\n3,1 3,0\n"); defer p.deinit(); const l = p.layout(400, 300); p.tap(l, l.center(dt(3, 1)), 0); try testing.expect(p.motions[1] == .exiting); try testing.expect(!p.game.board.isPresent(1)); try testing.expect(p.animating(10 * ms)); var list: draw.List = .empty; defer list.deinit(testing.allocator); // Just tapped, it has not moved yet and is all accent: one segment and // its arrowhead. try p.render(l, .{}, 0, &list); var accent: usize = 0; for (list.items) |item| if (std.mem.eql(u8, &item.color, &draw.Theme.default_accent)) { accent += 1; }; try testing.expectEqual(2, accent); try testing.expect(!p.animating(5000 * ms)); } test "a blocked arrow bumps, flashes, and costs a life" { var p = try testPlay("4x2\n0,1 1,1\n3,1 3,0\n"); defer p.deinit(); const l = p.layout(400, 300); p.tap(l, l.center(dt(0, 1)), 0); try testing.expect(p.motions[0] == .bumping); try testing.expectEqual(Game.max_lives - 1, p.game.lives); try testing.expect(p.lost_at[Game.max_lives - 1] != null); try testing.expect(p.animating(100 * ms)); try testing.expect(!p.animating(2000 * ms)); } /// How many of the frame's shapes are in `color`. fn countColored(p: *const Play, l: Layout, now: i64, color: draw.Color) !usize { var list: draw.List = .empty; defer list.deinit(testing.allocator); try p.render(l, .{}, now, &list); var n: usize = 0; for (list.items) |item| { if (std.mem.eql(u8, &item.color, &color)) n += 1; } return n; } test "a blocked arrow stays red until it leaves" { var p = try testPlay("4x2\n0,1 1,1\n3,1 3,0\n"); defer p.deinit(); const l = p.layout(400, 300); const red = (draw.Theme{}).block; p.tap(l, l.center(dt(0, 1)), 0); // Long after the bump, and after another arrow has been tapped: its // segment and arrowhead are still red. p.tap(l, l.center(dt(3, 1)), 5000 * ms); try testing.expectEqual(2, try countColored(&p, l, 10_000 * ms, red)); // Gone, it is not drawn at all. p.tap(l, l.center(dt(0, 1)), 10_000 * ms); try testing.expectEqual(0, try countColored(&p, l, 20_000 * ms, red)); } test "starting over makes a blocked arrow black again" { var p = try testPlay("4x2\n0,1 1,1\n3,1 3,0\n"); defer p.deinit(); const l = p.layout(400, 300); p.tap(l, l.center(dt(0, 1)), 0); p.restart(); try testing.expectEqual(0, try countColored(&p, l, 5000 * ms, (draw.Theme{}).block)); } test "a tap on nothing does nothing" { var p = try testPlay("4x2\n0,1 1,1\n3,1 3,0\n"); defer p.deinit(); const l = p.layout(400, 300); p.tap(l, l.center(dt(2, 0)), 0); p.tap(l, .{ -10, -10 }, 0); try testing.expectEqual(Game.max_lives, p.game.lives); try testing.expect(!p.animating(0)); } test "a lost level starts over once it has been seen" { var p = try testPlay("4x2\n0,1 1,1\n3,1 3,0\n"); defer p.deinit(); const l = p.layout(400, 300); for (0..Game.max_lives) |_| p.tap(l, l.center(dt(0, 1)), 0); try testing.expectEqual(Game.State.lost, p.game.state); try testing.expectEqual(null, try p.update(timing.lost - 1)); try testing.expectEqual(Game.State.lost, p.game.state); try testing.expectEqual(null, try p.update(timing.lost)); try testing.expectEqual(Game.State.playing, p.game.state); try testing.expectEqual(Game.max_lives, p.game.lives); } test "a won level moves on to the next" { var p = try testPlay("4x2\n0,1 1,1\n3,1 3,0\n"); defer p.deinit(); const l = p.layout(400, 300); p.tap(l, l.center(dt(3, 1)), 0); p.tap(l, l.center(dt(0, 1)), 0); try testing.expectEqual(Game.State.won, p.game.state); try testing.expectEqual(null, try p.update(timing.celebrate - 1)); try testing.expectEqual(2, (try p.update(timing.celebrate)).?); try testing.expectEqual(Game.State.playing, p.game.state); try testing.expectEqual(p.game.board.arrowCount(), p.motions.len); }