summaryrefslogtreecommitdiff
path: root/addons/life/life.zig
blob: 278990f8ce6bf4800247ca1829a4ffea6304ed9c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
//! Conway's Game of Life in a pane: ten generations a second while the
//! pane has the keyboard. Space pauses, r reseeds, hjkl move the cursor,
//! x toggles the cell under it.
const std = @import("std");
const addon = @import("addon");

pub const pardes_addon = addon.ops(Life);
comptime {
    addon.exportLib(&pardes_addon);
}

const W = 32;
const H = 16;
const period = std.time.ns_per_s / 10;

const Life = extern struct {
    cells: [H][W]bool,
    /// The pane's, kept: r after a restore reseeds as before it.
    seed: u64,
    gen: u32,
    cx: u8,
    cy: u8,
    paused: bool,
    next: addon.Deadline,

    pub const head: addon.Head = .{ .name = "life", .version = 1, .words = &.{.{ .name = "Life", .opens = true, .doc = "a pane of Conway's Game of Life" }} };

    pub fn open(s: *Life, _: ?[]const u8, _: ?[]const u8) void {
        s.seed = addon.seed();
        s.reseed();
    }

    pub fn tick(s: *Life, now: u64, flags: addon.Flags) u64 {
        if (!flags.focused or s.paused) return s.next.stop();
        if (s.next.due(now)) s.step();
        return s.next.every(now, period);
    }

    pub fn key(s: *Life, k: addon.Key) bool {
        switch (k.code) {
            addon.char(' ') => s.paused = !s.paused,
            addon.char('r') => s.reseed(),
            addon.char('h') => s.cx = (s.cx + W - 1) % W,
            addon.char('l') => s.cx = (s.cx + 1) % W,
            addon.char('k') => s.cy = (s.cy + H - 1) % H,
            addon.char('j') => s.cy = (s.cy + 1) % H,
            addon.char('x') => s.cells[s.cy][s.cx] = !s.cells[s.cy][s.cx],
            else => return false,
        }
        return true;
    }

    pub fn prefix(s: *const Life, w: *std.Io.Writer) !void {
        try w.print("gen {d} alive {d}{s}", .{ s.gen, s.alive(), if (s.paused) " paused" else "" });
    }

    pub fn paint(s: *const Life, w: addon.Window, _: addon.Paint) void {        for (s.cells, 0..) |row, y| for (row, 0..) |on, x| {
            const cursor = w.focused and x == s.cx and y == s.cy;
            w.put(x, y, if (on) "#" else ".", .{ .attrs = .{ .reverse = cursor } });
        };
    }

    pub fn body(s: *Life, out: *std.Io.Writer) !void {
        for (s.cells) |row| {
            for (row) |on| try out.writeByte(if (on) '#' else '.');
            try out.writeByte('\n');
        }
    }

    pub const dump = addon.dumpBytes;
    pub const load = addon.loadBytes;

    fn reseed(s: *Life) void {
        var prng: std.Random.DefaultPrng = .init(s.seed);
        const r = prng.random();
        for (&s.cells) |*row| for (row) |*on| {
            on.* = r.uintLessThan(u8, 4) == 0;
        };
        s.gen = 0;
    }

    fn alive(s: *const Life) u32 {
        var n: u32 = 0;
        for (s.cells) |row| for (row) |on| {
            n += @intFromBool(on);
        };
        return n;
    }

    fn step(s: *Life) void {
        var next: [H][W]bool = undefined;
        for (0..H) |y| for (0..W) |x| {
            var n: u8 = 0;
            for ([_]usize{ H - 1, 0, 1 }) |dy| for ([_]usize{ W - 1, 0, 1 }) |dx| {
                if (dy == 0 and dx == 0) continue;
                n += @intFromBool(s.cells[(y + dy) % H][(x + dx) % W]);
            };
            next[y][x] = n == 3 or (n == 2 and s.cells[y][x]);
        };
        s.cells = next;
        s.gen += 1;
    }
};

test "a blinker blinks, wrapping at the edges" {
    var s = std.mem.zeroes(Life);
    for ([_]usize{ W - 1, 0, 1 }) |x| s.cells[0][x] = true;
    s.step();
    try std.testing.expectEqual(3, s.alive());
    for ([_]usize{ H - 1, 0, 1 }) |y| try std.testing.expect(s.cells[y][0]);
    s.step();
    try std.testing.expect(s.cells[0][W - 1] and s.cells[0][1] and !s.cells[1][0]);
    try std.testing.expectEqual(2, s.gen);
}

test "a record loads back into a fresh pane" {
    var a = std.mem.zeroes(Life);
    a.seed = 42;
    a.reseed();
    a.step();
    var buf: [@sizeOf(Life)]u8 = undefined;
    try std.testing.expectEqual(buf.len, Life.dump(&a, &buf));
    var b = std.mem.zeroes(Life);
    try std.testing.expect(Life.load(&b, &buf, Life.head.version));
    try std.testing.expectEqualDeep(a.cells, b.cells);
    try std.testing.expect(!Life.load(&b, &buf, 2));
}