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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
|
//! snake.zig: a snake game as a pardes addon, over src/kinds/addon.zig
//! (`zig build addon-test` builds it as snake.so and runs snake.script).
//! h j k l steer; once dead, any key starts again. It steps only while its
//! pane has the keyboard, and asks for nothing otherwise.
const std = @import("std");
const addon = @import("addon");
const W = 20; // the board, in cells, inside its wall
const H = 5;
const period = 150 * std.time.ns_per_ms;
const Pt = extern struct { x: u8, y: u8 };
pub const Snake = extern struct {
segs: [W * H]Pt, // segs[0] is the head
len: u16,
food: Pt,
dir: [2]i8, // the direction last stepped
turn: [2]i8, // the direction the next step takes
dead: bool,
score: u32,
steps: u32,
rng: u64,
next: addon.Deadline,
pub const head: addon.Head = .{ .name = "snake", .version = 1, .words = &.{
.{ .name = "Snake", .opens = true, .doc = "a game of snake: h j k l steer" },
} };
fn rnd(s: *Snake) u64 {
s.rng ^= s.rng << 13;
s.rng ^= s.rng >> 7;
s.rng ^= s.rng << 17;
return s.rng;
}
/// Is (x, y) one of the snake's first n segments?
fn on(s: *const Snake, x: i32, y: i32, n: usize) bool {
for (s.segs[0..n]) |q| if (q.x == x and q.y == y) return true;
return false;
}
fn placeFood(s: *Snake) void {
s.dead = s.len == W * H; // the board full: a win, and over
if (s.dead) return;
var k = s.rnd() % (W * H - s.len);
s.food = for (0..W * H) |i| {
const p: Pt = .{ .x = @intCast(i % W), .y = @intCast(i / W) };
if (s.on(p.x, p.y, s.len)) continue;
if (k == 0) break p;
k -= 1;
} else s.food;
}
fn restart(s: *Snake) void {
s.len = 3;
for (s.segs[0..3], 0..) |*p, i| p.* = .{ .x = @intCast(W / 2 - i), .y = H / 2 };
s.dir, s.turn, s.dead, s.score, s.steps = .{ .{ 1, 0 }, .{ 1, 0 }, false, 0, 0 };
s.placeFood();
}
fn step(s: *Snake) void {
s.dir = s.turn;
const x = @as(i32, s.segs[0].x) + s.dir[0];
const y = @as(i32, s.segs[0].y) + s.dir[1];
const eats = x == s.food.x and y == s.food.y;
// The tail moves away this step unless the snake grows.
s.dead = x < 0 or y < 0 or x >= W or y >= H or s.on(x, y, if (eats) s.len else s.len - 1);
if (s.dead) return;
if (eats) s.len += 1;
std.mem.copyBackwards(Pt, s.segs[1..s.len], s.segs[0 .. s.len - 1]);
s.segs[0] = .{ .x = @intCast(x), .y = @intCast(y) };
s.steps += 1;
if (!eats) return;
s.score += 1;
s.placeFood();
}
pub fn open(s: *Snake, _: ?[]const u8, _: ?[]const u8) void {
s.rng = addon.seed() | 1;
s.restart();
}
/// Unfocused or over, it stands still and asks for nothing: a key, or
/// the keyboard coming back, ticks it again.
pub fn tick(s: *Snake, now: u64, flags: addon.Flags) u64 {
if (s.next.due(now) and flags.focused and !s.dead) s.step();
return if (!flags.focused or s.dead) s.next.stop() else s.next.every(now, period);
}
pub fn prefix(s: *const Snake, w: *std.Io.Writer) !void {
try w.print("Snake {d}{s}", .{ s.score, if (s.dead) " over" else "" });
}
pub fn paint(s: *const Snake, w: addon.Window, _: addon.Paint) void {
const wall: addon.Style = .{ .fg = .index(8) };
for (0..H + 2) |y| for (0..W + 2) |x| if (x % (W + 1) == 0 or y % (H + 1) == 0) w.put(x, y, "#", wall);
w.put(1 + s.food.x, 1 + s.food.y, "*", .{ .fg = .index(1), .attrs = .{ .bold = true } });
for (s.segs[0..s.len], 0..) |p, i|
w.put(1 + p.x, 1 + p.y, if (i > 0) "o" else if (s.dead) "x" else "@", .{ .fg = .index(2), .attrs = .{ .bold = i == 0 } });
if (s.dead) w.put(0, H + 2, "game over: any key", .{ .fg = .index(1) }) else if (!w.focused) w.put(0, H + 2, "paused", wall);
}
pub fn key(s: *Snake, k: addon.Key) bool {
if (k.code == .esc) return false; // Esc leaves
if (s.dead or k.code == addon.char('r')) {
s.restart();
return true;
}
const d: [2]i8 = switch (k.code) {
.left, addon.char('h') => .{ -1, 0 },
.right, addon.char('l') => .{ 1, 0 },
.up, addon.char('k') => .{ 0, -1 },
.down, addon.char('j') => .{ 0, 1 },
else => return false,
};
if (d[0] != -s.dir[0] or d[1] != -s.dir[1]) s.turn = d; // no turning back
return true;
}
pub fn body(s: *const Snake, w: *std.Io.Writer) !void {
try w.print("score {d}\nlength {d}\nsteps {d}\n{s}\n", .{ s.score, s.len, s.steps, if (s.dead) "over" else "alive" });
}
pub fn ctlRead(s: *const Snake, w: *std.Io.Writer) !void {
try w.print("score {d}\nlength {d}\n", .{ s.score, s.len });
}
pub const dump = addon.dumpBytes;
pub const load = addon.loadBytes;
};
pub const pardes_addon = addon.ops(Snake);
comptime {
addon.exportLib(&pardes_addon);
}
test "it eats, grows a segment and a point, dies on the wall, and its record is its state" {
var s = std.mem.zeroInit(Snake, .{ .rng = 3 });
s.restart();
s.food = .{ .x = s.segs[0].x + 1, .y = s.segs[0].y };
s.step();
try std.testing.expectEqual(4, s.len);
try std.testing.expectEqual(1, s.score);
_ = s.key(.{ .code = addon.char('k') });
while (!s.dead) s.step();
try std.testing.expectEqual(0, s.segs[0].y);
var record: [@sizeOf(Snake)]u8 = undefined;
var back = std.mem.zeroInit(Snake, .{});
try std.testing.expect(addon.loadBytes(&back, record[0..addon.dumpBytes(&s, &record)], 1));
try std.testing.expect(std.meta.eql(back, s));
try std.testing.expect(!addon.loadBytes(&back, &record, 2));
}
|