Public: anyone can read this; the crew can change it.

Migrated from github.com/amirmushichge/pixel-plays

Lily Pond rules: a tested `lily-pond/pond.js` where a frog must hop every lily pad once before they sink, from plain data #173

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

vesper/pixel-plays:vesper/166-lily-pond-rules-a-tested-lily-pond-pond → main 2 commits fork 1 thread · 1 unresolved

  • Merged. vesper/166-lily-pond-rules-a-tested-lily-pond-pond was merged into main as a189dc4.

Review

Sign in to review this change.
2 files changed +270 −0
lily-pond/pond.js added +140
@@ -0,0 +1,140 @@
1 'use strict';
2 // The Lily Pond rules: a frog on a pond of lily pads, every pad to be landed on once before it sinks.
3 // Plain data in, plain data out, no DOM, no timers, no Math.random: the pond comes from the seed and the level.
4 // A rejected hop returns the very same state and says why. The page draws what this decides.
5 //
6 // The pond is a SIZE x SIZE grid, x to the east and y to the south (north is y - 1). A hop goes north, east, south or
7 // west to the nearest live pad in that line, no more than REACH cells away, and the pad left behind sinks. The frog
8 // starts on a pad: it sinks with the first hop. Level n has n + 3 pads, up to LAST_LEVEL.
9 (function (root) {
10 const SIZE = 6, REACH = 3, LAST_LEVEL = 6;
11 const WIN_LEVEL = LAST_LEVEL, WIN_RETRIES = 3; // the win line: this many levels cleared, no more retries than this
12 const MAX_RETRIES = 6; // one retry past this and the game is over
13 const DIRS = { north: [0, -1], east: [1, 0], south: [0, 1], west: [-1, 0] };
14 const DIR_NAMES = Object.keys(DIRS);
15
16 const finite = v => (Number.isFinite(v) ? v : 0);
17 const padsIn = level => level + 3;
18 const clampLevel = l => Math.min(LAST_LEVEL, Math.max(1, Math.floor(finite(l)) || 1));
19 // a repeatable number in [0, 1) for this seed and slot
20 function noise(seed, n) {
21 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
22 h = Math.imul(h ^ (h >>> 13), 1274126177);
23 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
24 }
25 const inside = (x, y) => x >= 0 && y >= 0 && x < SIZE && y < SIZE;
26 const key = (x, y) => y * SIZE + x;
27
28 // One attempt at a route: a self-avoiding walk of straight hops where every cell skipped over stays empty water for good,
29 // so that following the route is always the nearest-pad hop. Null when the walk paints itself into a corner.
30 function walk(seed, level, attempt) {
31 const want = padsIn(level), base = attempt * 997 + level * 31;
32 let n = 0;
33 const rnd = () => noise(seed, base + n++);
34 const sx = Math.floor(rnd() * SIZE), sy = Math.floor(rnd() * SIZE);
35 const route = [{ x: sx, y: sy }], used = new Set([key(sx, sy)]), water = new Set();
36 while (route.length < want) {
37 const { x, y } = route[route.length - 1], options = [];
38 for (const d of DIR_NAMES) {
39 const [dx, dy] = DIRS[d];
40 for (let k = 1; k <= REACH; k++) {
41 const nx = x + dx * k, ny = y + dy * k;
42 if (!inside(nx, ny)) break;
43 const gaps = [];
44 for (let j = 1; j < k; j++) gaps.push(key(x + dx * j, y + dy * j));
45 if (used.has(key(nx, ny)) || water.has(key(nx, ny))) continue;
46 options.push({ nx, ny, gaps });
47 }
48 }
49 if (!options.length) return null;
50 const o = options[Math.floor(rnd() * options.length)];
51 for (const g of o.gaps) if (!used.has(g)) water.add(g);
52 used.add(key(o.nx, o.ny));
53 route.push({ x: o.nx, y: o.ny });
54 }
55 return route;
56 }
57 // A snake along the rows, back and forth: every hop is one cell and no cell repeats. Used only if every seeded attempt fails.
58 function snake(level) {
59 const out = [];
60 for (let i = 0; i < padsIn(level); i++) {
outdated

Medium: snake puts pad i at x: i % SIZE, y: 0. With SIZE 6, any level with more than 6 pads (levels 4 to 6 have 7, 8 and 9) repeats cells, so the pond has duplicate pads and is not solvable by hop. The issue requires every pond to have a route over every pad. The fallback is also untested dead weight. Fix: lay the snake out boustrophedon, so row r = floor(i / SIZE) and x runs left to right on even rows and right to left on odd rows. Every hop is then 1 cell and the pads are distinct. Add a test that calls snake, or drives the fallback, for all levels and follows the route. Alternatively, remove the fallback and make route keep trying attempts until one succeeds.

61 const r = Math.floor(i / SIZE), c = i % SIZE;
62 out.push({ x: r % 2 ? SIZE - 1 - c : c, y: r });
63 }
64 return out;
65 }
66 // The route for a seed and level: the pads in the order the frog is meant to take them. Pads are placed only on it.
67 function route(seed, level) {
68 seed = finite(seed) >>> 0; level = clampLevel(level);
69 for (let a = 0; a < 40; a++) { const r = walk(seed, level, a); if (r) return r; }
70 return snake(level);
71 }
72
73 const copy = s => Object.assign({}, s, { pads: s.pads.map(p => ({ ...p })), frog: { ...s.frog }, route: s.route.map(p => ({ ...p })) });
74 function pond(seed, level, cleared, retries) {
75 const r = route(seed, level);
76 return refresh({
77 seed: finite(seed) >>> 0, level, size: SIZE, reach: REACH, last: LAST_LEVEL, status: 'playing', cleared, retries,
78 pads: r.map(p => ({ ...p })), frog: { ...r[0] }, route: r, hops: 0, line: '',
79 });
80 }
81 // start(seed, level): level 1 unless told otherwise
82 const start = (seed = 1, level = 1) => pond(seed, clampLevel(level), 0, 0);
83
84 const verdict = s => (s.cleared >= WIN_LEVEL && s.retries <= WIN_RETRIES ? 'won' : 'lost');
85 function refresh(s) {
86 if (s.status === 'over') {
87 s.line = verdict(s) === 'won'
88 ? `Pond cleared: ${s.cleared} levels, ${s.retries} ${s.retries === 1 ? 'retry' : 'retries'}`
89 : `The pads sank: ${s.cleared} of ${LAST_LEVEL} levels cleared, ${s.retries} ${s.retries === 1 ? 'retry' : 'retries'}`;
90 } else {
91 s.line = `Level ${s.level} of ${LAST_LEVEL}: ${s.pads.length - 1} pads to go, ${s.retries} ${s.retries === 1 ? 'retry' : 'retries'}`;
92 }
93 return s;
94 }
95
96 // the pad a hop in this direction would land on, or null: the nearest live pad in that line within reach
97 function target(s, dir) {
98 const d = DIRS[dir];
99 if (!d) return null;
100 for (let k = 1; k <= s.reach; k++) {
101 const x = s.frog.x + d[0] * k, y = s.frog.y + d[1] * k;
102 if (!inside(x, y)) return null;
103 if (s.pads.some(p => p.x === x && p.y === y)) return { x, y };
104 }
105 return null;
106 }
107 const moves = s => (s.status === 'over' ? [] : DIR_NAMES.filter(d => target(s, d)));
108
109 // hop(state, dir) -> { ok, why, event, state }; event is '', 'cleared', 'lost' or 'over'.
110 function hop(s, dir) {
111 if (s.status !== 'playing') return { ok: false, why: 'over', event: '', state: s };
112 if (typeof dir !== 'string' || !Object.hasOwn(DIRS, dir)) return { ok: false, why: 'bad-direction', event: '', state: s };
113 const to = target(s, dir);
114 if (!to) return { ok: false, why: 'no-pad', event: '', state: s };
115 const n = copy(s);
116 n.pads = n.pads.filter(p => !(p.x === n.frog.x && p.y === n.frog.y)); // the pad behind the frog sinks
117 n.frog = to;
118 n.hops = s.hops + 1;
119 if (n.pads.length === 1) { // only the pad under the frog is left
120 if (n.level >= LAST_LEVEL) {
121 n.cleared = s.cleared + 1; n.status = 'over';
122 return { ok: true, why: '', event: 'over', state: refresh(n) };
123 }
124 return { ok: true, why: '', event: 'cleared', state: pond(n.seed, n.level + 1, s.cleared + 1, s.retries) };
125 }
126 if (!moves(n).length) { // stuck: the pond is lost, the level restarts
127 if (s.retries + 1 > MAX_RETRIES) {
128 n.status = 'over'; n.retries = s.retries + 1;
129 return { ok: true, why: '', event: 'over', state: refresh(n) };
130 }
131 return { ok: true, why: '', event: 'lost', state: pond(n.seed, n.level, s.cleared, s.retries + 1) };
132 }
133 return { ok: true, why: '', event: '', state: refresh(n) };
134 }
135
136 const api = {
137 SIZE, REACH, LAST_LEVEL, WIN_LEVEL, WIN_RETRIES, MAX_RETRIES, padsIn, route, start, hop, moves, snake,
138 };
139 if (typeof module !== 'undefined') module.exports = api; else root.LilyPond = api;
140 })(typeof window !== 'undefined' ? window : globalThis);
lily-pond/pond.test.mjs added +130
@@ -0,0 +1,130 @@
1 import { test, expect } from 'bun:test';
2 import { SIZE, REACH, LAST_LEVEL, WIN_LEVEL, WIN_RETRIES, MAX_RETRIES, padsIn, route, start, hop, moves, snake } from './pond.js';
3
4 const dirOf = (a, b) => (b.x > a.x ? 'east' : b.x < a.x ? 'west' : b.y > a.y ? 'south' : 'north');
5 // follow the pond's route to the end, returning the last hop's result
6 function follow(s) {
7 const r = s.route; let res;
8 for (let i = 1; i < r.length; i++) {
9 res = hop(s, dirOf(r[i - 1], r[i]));
10 expect([i, res.ok, res.why]).toEqual([i, true, '']);
11 s = res.state;
12 }
13 return res;
14 }
15 // a hand-made pond (plain data)
16 const hand = (pads, frog, extra = {}) => ({ ...start(1, 1), pads, frog, route: [frog], reach: REACH, ...extra });
17
18 test('the same seed and level give the same pond, other seeds differ, and pads sit inside the stated grid', () => {
19 expect(start(7, 3)).toEqual(start(7, 3));
20 expect(route(7, 3)).toEqual(route(7, 3));
21 const seen = new Set();
22 for (let seed = 1; seed <= 20; seed++) seen.add(JSON.stringify(start(seed, 2).pads));
23 expect(seen.size).toBeGreaterThan(5);
24 for (let l = 1; l <= LAST_LEVEL; l++) {
25 const s = start(5, l);
26 expect(s.size).toBe(SIZE);
27 expect(s.pads).toHaveLength(padsIn(l));
28 expect(new Set(s.pads.map(p => `${p.x},${p.y}`)).size).toBe(s.pads.length);
29 for (const p of s.pads) { expect(p.x).toBeGreaterThanOrEqual(0); expect(p.x).toBeLessThan(SIZE); expect(p.y).toBeGreaterThanOrEqual(0); expect(p.y).toBeLessThan(SIZE); }
30 expect(s.frog).toEqual(s.pads[0]);
31 }
32 expect(padsIn(2)).toBeGreaterThan(padsIn(1));
33 });
34
35 test('every generated pond is solvable by following its route', () => {
36 for (let seed = 0; seed < 60; seed++) for (let l = 1; l <= LAST_LEVEL; l++) {
37 const s = start(seed, l);
38 let cur = s, res;
39 for (let i = 1; i < s.route.length; i++) {
40 res = hop(cur, dirOf(s.route[i - 1], s.route[i]));
41 if (!res.ok) throw new Error(`seed ${seed} level ${l} hop ${i}: ${res.why}`);
42 cur = res.state;
43 }
44 expect(res.event).toBe(l === LAST_LEVEL ? 'over' : 'cleared');
45 }
46 });
47
48 test('a hop with no pad in reach is refused and the state is returned unchanged', () => {
49 const s = hand([{ x: 0, y: 0 }, { x: 5, y: 0 }, { x: 0, y: 1 }], { x: 0, y: 0 });
50 const r = hop(s, 'east'); // the pad is 5 away, reach is 3
51 expect(r.ok).toBe(false);
52 expect(r.why).toBe('no-pad');
53 expect(r.state).toBe(s);
54 expect(hop(s, 'north').why).toBe('no-pad'); // off the edge
55 expect(hop(s, 'up').why).toBe('bad-direction');
56 expect(hop(s, '__proto__').why).toBe('bad-direction');
57 expect(moves(s)).toEqual(['south']);
58 });
59
60 test('a hop lands on the nearest pad in that line and the pad behind the frog sinks', () => {
61 const s = hand([{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 3, y: 0 }, { x: 0, y: 3 }], { x: 0, y: 0 });
62 const r = hop(s, 'east');
63 expect(r.ok).toBe(true);
64 expect(r.state.frog).toEqual({ x: 2, y: 0 });
65 expect(r.state.pads).toEqual([{ x: 2, y: 0 }, { x: 3, y: 0 }, { x: 0, y: 3 }]);
66 expect(s.pads).toHaveLength(4); // the old state is untouched
67 expect(hop(r.state, 'west').why).toBe('no-pad'); // nothing to go back to
68 });
69
70 test('a stuck frog loses the pond: the level restarts and counts one retry', () => {
71 const s = hand([{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 5, y: 5 }], { x: 0, y: 0 }, { level: 2, cleared: 1 });
72 const r = hop(s, 'east'); // lands with the far pad out of reach
73 expect(r.event).toBe('lost');
74 expect(r.state.retries).toBe(1);
75 expect(r.state.level).toBe(2);
76 expect(r.state.cleared).toBe(1);
77 expect(r.state.pads).toEqual(start(1, 2).pads);
78 expect(r.state.status).toBe('playing');
79 expect(typeof r.state.undo).toBe('undefined');
80 });
81
82 test('taking the last pad clears the pond and starts the next level, with more pads', () => {
83 const s = start(3, 1);
84 const res = follow(s);
85 expect(res.event).toBe('cleared');
86 expect(res.state.level).toBe(2);
87 expect(res.state.cleared).toBe(1);
88 expect(res.state.pads.length).toBe(padsIn(2));
89 expect(res.state.pads).toEqual(start(3, 2).pads);
90 });
91
92 test('the last level ends the game, and the win line needs the level and few enough retries', () => {
93 let s = start(4, 1), res;
94 for (let l = 1; l <= LAST_LEVEL; l++) { res = follow(s); s = res.state; }
95 expect(res.event).toBe('over');
96 expect(s.status).toBe('over');
97 expect(s.cleared).toBe(WIN_LEVEL);
98 expect(s.line).toBe(`Pond cleared: ${WIN_LEVEL} levels, 0 retries`);
99 expect(hop(s, 'east').why).toBe('over');
100 // with too many retries the same clear reads as a loss
101 let t = { ...start(4, LAST_LEVEL), cleared: LAST_LEVEL - 1, retries: WIN_RETRIES };
102 expect(follow(t).state.line).toContain('Pond cleared');
103 t = { ...t, retries: WIN_RETRIES + 1 };
104 const end = follow(t).state;
105 expect(end.line).toBe(`The pads sank: ${LAST_LEVEL} of ${LAST_LEVEL} levels cleared, ${WIN_RETRIES + 1} retries`);
106 });
107
108 test('too many lost ponds end the game with the loss line', () => {
109 const s = hand([{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 5, y: 5 }], { x: 0, y: 0 }, { cleared: 2, retries: MAX_RETRIES });
110 const r = hop(s, 'east');
111 expect(r.event).toBe('over');
112 expect(r.state.status).toBe('over');
113 expect(r.state.line).toBe(`The pads sank: 2 of ${LAST_LEVEL} levels cleared, ${MAX_RETRIES + 1} retries`);
114 });
115
116 test('the fallback snake is a valid pond for every level: distinct pads, one cell apart, followable', () => {
117 for (let l = 1; l <= LAST_LEVEL; l++) {
118 const r = snake(l);
119 expect(r).toHaveLength(padsIn(l));
120 expect(new Set(r.map(p => `${p.x},${p.y}`)).size).toBe(r.length);
121 let s = { ...start(1, l), pads: r.map(p => ({ ...p })), frog: { ...r[0] }, route: r }, res;
122 for (let i = 1; i < r.length; i++) {
123 expect(Math.abs(r[i].x - r[i - 1].x) + Math.abs(r[i].y - r[i - 1].y)).toBe(1);
124 res = hop(s, dirOf(r[i - 1], r[i]));
125 expect(res.ok).toBe(true);
126 s = res.state;
127 }
128 expect(res.event).toBe(l === LAST_LEVEL ? 'over' : 'cleared');
129 }
130 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs