diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-06 13:28:30 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-06 14:24:59 -0300 |
| commit | 0f81de017ca7b52e951bb70f6f5f3e8c88b425e6 (patch) | |
| tree | fde88db0ed0dd68fbeb7bf7aaa49d3cd1f08b1c1 /addons/snake | |
| parent | b7fdfb18ffd199d49a254c1c799bc3415ad45ec2 (diff) | |
| download | pardes-0f81de017ca7b52e951bb70f6f5f3e8c88b425e6.tar.gz pardes-0f81de017ca7b52e951bb70f6f5f3e8c88b425e6.zip | |
kinds #25, addons in Zig: src/kinds/addon.zig, over the translated header and nothing of the core, makes a kind's pa_ops from a struct of the functions it has (its head from name, version, extensions and words; a public function of no kind's name a compile error), the pane's arena and a job's pa_out as std Allocators, typed keys, a Window to put text in, a Paint for the prefix and placements, tick's flags and a Deadline, dump and load as an extern struct's bytes in one line each, and body and ctl over a Writer; snake.zig and image.zig (stb_image in stb.c, static, beside any zstbi) replace snake.c and image.c with the same goldens, harness and perf cell, and addon-test runs their own zig tests
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge
Diffstat (limited to 'addons/snake')
| -rw-r--r-- | addons/snake/snake.c | 154 | ||||
| -rw-r--r-- | addons/snake/snake.zig | 147 |
2 files changed, 147 insertions, 154 deletions
diff --git a/addons/snake/snake.c b/addons/snake/snake.c deleted file mode 100644 index ce9279dc..00000000 --- a/addons/snake/snake.c +++ /dev/null @@ -1,154 +0,0 @@ -/* snake.c: a snake game as a pardes addon. - * cc -shared -fPIC -O2 -Wall -Wextra -Werror -I src/kinds -o snake.so addons/snake/snake.c - * 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. */ -#include <stdio.h> -#include "pardes_addon.h" - -#define W 20 /* the board, in cells, inside its wall */ -#define H 5 -#define PERIOD 150000000ull /* ns a step */ -#define VERSION 1 - -typedef struct { uint8_t x, y; } pt; - -typedef struct snake { - pt body[W * H]; /* body[0] is the head */ - uint16_t len; - pt food; - int8_t dx, dy; /* the direction last stepped */ - int8_t ndx, ndy; /* the direction the next step takes */ - uint8_t dead, pad[3]; - uint32_t score, steps; - uint64_t rng, next; /* next: the deadline of the next step */ -} snake; - -static const pa_api *api; - -static uint64_t rnd(snake *s) { - 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? */ -static int on_snake(const snake *s, int x, int y, unsigned n) { - for (unsigned i = 0; i < n; i++) - if (s->body[i].x == x && s->body[i].y == y) return 1; - return 0; -} - -static void place_food(snake *s) { - unsigned free_cells = W * H - s->len; - if (!free_cells) { s->dead = 1; return; } /* the board is full: a win, and over */ - unsigned k = (unsigned)(rnd(s) % free_cells); - for (int y = 0; y < H; y++) - for (int x = 0; x < W; x++) - if (!on_snake(s, x, y, s->len) && k-- == 0) { s->food = (pt){(uint8_t)x, (uint8_t)y}; return; } -} - -static void restart(snake *s) { - s->len = 3; - for (unsigned i = 0; i < 3; i++) s->body[i] = (pt){(uint8_t)(W / 2 - i), H / 2}; - s->dx = s->ndx = 1, s->dy = s->ndy = 0; - s->dead = 0, s->score = 0, s->steps = 0; - place_food(s); -} - -static void step(snake *s) { - s->dx = s->ndx, s->dy = s->ndy; - int x = s->body[0].x + s->dx, y = s->body[0].y + s->dy; - int eats = x == s->food.x && y == s->food.y; - /* the tail moves away this step unless the snake grows */ - if (x < 0 || y < 0 || x >= W || y >= H || on_snake(s, x, y, eats ? s->len : s->len - 1u)) { - s->dead = 1; - return; - } - if (eats) s->len++; - memmove(&s->body[1], &s->body[0], (s->len - 1) * sizeof(pt)); - s->body[0] = (pt){(uint8_t)x, (uint8_t)y}; - s->steps++; - if (eats) s->score++, place_food(s); -} - -/* ---- the contract ---- */ - -static int init(const pa_api *a) { api = a; return PA_OK; } - -static void *open(const char *path, const uint8_t *bytes, uint64_t len) { - (void)path, (void)bytes, (void)len; - snake *s = api->alloc(sizeof *s); - if (!s) return 0; - s->rng = api->seed() | 1; - restart(s); - return s; -} - -/* Unfocused or over, it stands still and asks for nothing: a key, or the - * keyboard coming back, ticks it again. */ -static uint64_t tick(void *st, uint64_t now, uint32_t flags) { - snake *s = st; - if (!(flags & PA_FOCUSED) || s->dead) return s->next = 0; - if (s->next && now >= s->next) step(s); - if (s->dead) return s->next = 0; - if (!s->next || now >= s->next) s->next = now + PERIOD; - return s->next; -} - -static void paint(void *st, const pa_window *w, pa_paint *out) { - const snake *s = st; - for (unsigned x = 0; x < W + 2; x++) pa_put(w, 0, x, "#", PA_INDEX(8), PA_DEFAULT, 0), pa_put(w, H + 1, x, "#", PA_INDEX(8), PA_DEFAULT, 0); - for (unsigned y = 1; y <= H; y++) pa_put(w, y, 0, "#", PA_INDEX(8), PA_DEFAULT, 0), pa_put(w, y, W + 1, "#", PA_INDEX(8), PA_DEFAULT, 0); - pa_put(w, 1 + s->food.y, 1 + s->food.x, "*", PA_INDEX(1), PA_DEFAULT, PA_BOLD); - for (unsigned i = s->len; i-- > 0;) - pa_put(w, 1 + s->body[i].y, 1 + s->body[i].x, i ? "o" : s->dead ? "x" : "@", PA_INDEX(2), PA_DEFAULT, i ? 0 : PA_BOLD); - if (s->dead) pa_put(w, H + 2, 0, "game over: any key", PA_INDEX(1), PA_DEFAULT, 0); - else if (!w->focused) pa_put(w, H + 2, 0, "paused", PA_INDEX(8), PA_DEFAULT, 0); - int n = snprintf(out->prefix, sizeof out->prefix, "Snake %u%s", s->score, s->dead ? " over" : ""); - out->prefix_len = n < 0 ? 0 : (uint32_t)n; -} - -static int key(void *st, const pa_key *k) { - snake *s = st; - if (k->cp == 0x1b) return 0; /* Esc leaves */ - if (s->dead) { restart(s); return 1; } - int dx = 0, dy = 0; - switch (k->cp) { - case 'h': case PA_KEY_LEFT: dx = -1; break; - case 'l': case PA_KEY_RIGHT: dx = 1; break; - case 'k': case PA_KEY_UP: dy = -1; break; - case 'j': case PA_KEY_DOWN: dy = 1; break; - case 'r': restart(s); return 1; - default: return 0; - } - if (dx != -s->dx || dy != -s->dy) s->ndx = (int8_t)dx, s->ndy = (int8_t)dy; /* no turning back */ - return 1; -} - -static uint32_t text(const snake *s, char *buf, uint32_t n) { - int r = snprintf(buf, n, "score %u\nlength %u\nsteps %u\n%s\n", s->score, s->len, s->steps, s->dead ? "over" : "alive"); - return r < 0 ? 0 : (uint32_t)r < n ? (uint32_t)r : n; -} - -static uint64_t body_len(void *st) { char b[96]; return text(st, b, sizeof b); } - -static uint32_t body(void *st, uint64_t off, char *buf, uint32_t n) { - char b[96]; - return pa_copy(b, text(st, b, sizeof b), off, buf, n); -} - -static uint32_t ctl_read(void *st, char *buf, uint32_t n) { - const snake *s = st; - int r = snprintf(buf, n, "score %u\nlength %u\n", s->score, s->len); - return r < 0 ? 0 : (uint32_t)r < n ? (uint32_t)r : n; -} - -PA_POD(snake, VERSION) - -static const pa_word words[] = { PA_WORD("Snake", 0, PA_ARG_NONE, 1, "a game of snake: h j k l steer") }; - -const pa_ops pardes_addon = { - .head = PA_ADDON("snake", VERSION, "", words, 1), - .init = init, .open = open, .tick = tick, .paint = paint, .key = key, - .body_len = body_len, .body = body, .ctl_read = ctl_read, - .dump = snake_dump, .load = snake_load, -}; diff --git a/addons/snake/snake.zig b/addons/snake/snake.zig new file mode 100644 index 00000000..badafc54 --- /dev/null +++ b/addons/snake/snake.zig @@ -0,0 +1,147 @@ +//! 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) 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 paint(s: *const Snake, w: addon.Window, out: 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); + out.prefix("Snake {d}{s}", .{ s.score, if (s.dead) " over" else "" }); + } + + 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; +}; + +export const pardes_addon = addon.ops(Snake); + +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)); +} |
