Public: anyone can read this; the crew can change it.
Migrated from github.com/amirmushichge/pixel-plays
Rock Pool rules: a tested `rock-pool/pool.js` where crabs dart between rocks and you scoop them into a bucket before the tide comes back, from plain data #221
torque/pixel-plays:torque/198-rock-pool-rules-a-tested-rock-pool-pool → main 3 commits fork
7 files
changed +263
−4
README.md +1 −1
| @@ -76,7 +76,7 @@ node serve.mjs | ||
| 76 | 76 | |
| 77 | 77 | Then open http://127.0.0.1:5300/. `PORT` and `HOST` override the port and address; `bun serve.mjs` works the same. Any static file server works, and the site deploys as plain static files. |
| 78 | 78 | |
| 79 | On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is only the play counts, under `FORGE_APP_DATA`. `bun test` checks that the server answers every game page and track. | |
| 79 | On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is only the play counts, under `FORGE_APP_DATA`. `bun scripts/test.mjs` is the forge's test command: the same tests as `bun test`, run in parallel (the playtest suite in 8 shards via `PLAYTEST_SHARD=i/n`, everything else in one more process), because the serial run outgrew the deploy's 600-second limit as the catalogue grew. `bun test` still works and checks that the server answers every game page and track. | |
| 80 | 80 | |
| 81 | 81 | ## Plays |
| 82 | 82 | `/stats/` ranks the games by how much they are played, and `/api/stats` returns the same rows as JSON. Each game page reports three anonymous events to `POST /api/play` (an Origin check against browser cross-site posts, which a script can still forge, so the endpoint is also limited as below): the page opened, the first tap or key press (a play), and the seconds the page stayed visible after that. Only totals per game are kept, with no ids or cookies, in `plays.json` under `FORGE_APP_DATA` (in memory when it is unset). `stats.mjs` holds the counting; it needs no dependency, so the file is plain JSON rather than SQLite, which would tie the server to Bun. Limits: 60 events a minute per client address (the socket address, never a header) and 600 a minute per game, answered with 429; a play is refused unless an open is ahead of it and time unless plays can account for it (at most 3600 s each), so forged events cannot show a ratio real ones never could. They cannot stop someone slowly inflating a game within those bounds, so treat the numbers as a guide. Counts are flushed to disk on SIGTERM. Not recorded yet: a finished round, since each game ends in its own way. |
forge.json +1 −1
| @@ -2,6 +2,6 @@ | ||
| 2 | 2 | "app": { |
| 3 | 3 | "run": "bun serve.mjs", |
| 4 | 4 | "health": "/", |
| 5 | "test": "bun test" | |
| 5 | "test": "bun scripts/test.mjs" | |
| 6 | 6 | } |
| 7 | 7 | } |
playtest.test.mjs +5 −1
| @@ -9,6 +9,10 @@ setDefaultTimeout(60000); | ||
| 9 | 9 | const GAMES = readdirSync(import.meta.dir, { withFileTypes: true }) |
| 10 | 10 | .filter(d => d.isDirectory() && readdirSync(`${import.meta.dir}/${d.name}`).includes('index.html')).map(d => d.name).sort(); |
| 11 | 11 | |
| 12 | // PLAYTEST_SHARD="i/n" plays only every n-th game from the i-th (scripts/test.mjs runs the shards side by side) | |
| 13 | const [shard, shards] = (process.env.PLAYTEST_SHARD ?? '0/1').split('/').map(Number); | |
| 14 | const MINE = GAMES.filter((_, k) => k % shards === shard); | |
| 15 | ||
| 12 | 16 | const rand = seed => () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; }; |
| 13 | 17 | const KEYS = [' ', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Enter']; |
| 14 | 18 | |
| @@ -30,7 +34,7 @@ test('every game has a scripted round, and every script has a game', () => { | ||
| 30 | 34 | |
| 31 | 35 | test('the games folder is not empty', () => { expect(GAMES.length).toBeGreaterThanOrEqual(19); }); |
| 32 | 36 | |
| 33 | for (const id of GAMES) { | |
| 37 | for (const id of MINE) { | |
| 34 | 38 | test(`${id}: boots, paints a picture and says what to do`, () => { |
| 35 | 39 | const g = boot(id); |
| 36 | 40 | g.run(2); |
rock-pool/pool.js added +109
| @@ -0,0 +1,109 @@ | ||
| 1 | 'use strict'; | |
| 2 | // The Rock Pool rules: the tide is out, crabs dart from one rock to another, and you scoop a crab into the bucket | |
| 3 | // while it is in the open, before the tide comes back. Plain data in, plain data out, no DOM, no timers, no | |
| 4 | // Math.random: the schedule of dashes comes from the seed. A refused scoop returns the very same state and says why. | |
| 5 | // | |
| 6 | // Units: seconds for time, cells for position. The pool is COLS x ROWS cells; a cell is named by its index | |
| 7 | // r * COLS + c. Rock i sits at the centre of cell i, (c + 0.5, r + 0.5). A dashing crab moves along the straight line | |
| 8 | // from its rock to its target rock at constant speed; it is in the open only while it dashes (start <= t < start + | |
| 9 | // duration) and hidden under a rock otherwise. A scoop on a cell catches a crab in the open whose position lies in | |
| 10 | // that cell; a scoop on a cell with none is a miss and starts COOLDOWN seconds in which scoops are refused. | |
| 11 | (function (root) { | |
| 12 | const COLS = 4; // rocks across | |
| 13 | const ROWS = 4; // rocks down | |
| 14 | const CELLS = COLS * ROWS; | |
| 15 | const TIDE = 30; // s until the tide comes back | |
| 16 | const DASHES = 14; // crab dashes in the schedule | |
| 17 | const MIN_DASH = 1.2; // s, shortest dash | |
| 18 | const MAX_DASH = 2.4; // s, longest dash | |
| 19 | const CRAB_POINTS = 10; // points per crab | |
| 20 | const EARLY = 1 / 3; // a catch in the first third of the dash earns the bonus | |
| 21 | const BONUS = 5; // extra points for an early catch | |
| 22 | const BUCKET = 8; // crabs the bucket holds | |
| 23 | const COOLDOWN = 1; // s of refused scoops after a miss | |
| 24 | const WIN = 80; // score at or over this wins the round | |
| 25 | const MAX_DT = 0.1; // s, the longest step tick takes (longer is clamped) | |
| 26 | ||
| 27 | const finite = v => (Number.isFinite(v) ? v : 0); | |
| 28 | // a repeatable number in [0, 1) for this seed and slot | |
| 29 | function noise(seed, n) { | |
| 30 | let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0; | |
| 31 | h = Math.imul(h ^ (h >>> 13), 1274126177); | |
| 32 | return ((h ^ (h >>> 16)) >>> 0) / 4294967296; | |
| 33 | } | |
| 34 | const round = v => Math.round(v * 1e6) / 1e6; | |
| 35 | const centre = i => ({ x: (i % COLS) + 0.5, y: Math.floor(i / COLS) + 0.5 }); | |
| 36 | ||
| 37 | // The schedule: DASHES dashes, each from one rock to a different rock, starting so that it ends before the tide. | |
| 38 | function schedule(seed) { | |
| 39 | const out = []; | |
| 40 | for (let k = 0; k < DASHES; k++) { | |
| 41 | const from = Math.floor(noise(seed, 4 * k + 1) * CELLS); | |
| 42 | const to = (from + 1 + Math.floor(noise(seed, 4 * k + 2) * (CELLS - 1))) % CELLS; // never the same rock | |
| 43 | const duration = round(MIN_DASH + noise(seed, 4 * k + 3) * (MAX_DASH - MIN_DASH)); | |
| 44 | const start = round(noise(seed, 4 * k + 4) * (TIDE - duration)); | |
| 45 | out.push({ id: 'c' + k, from, to, start, duration }); | |
| 46 | } | |
| 47 | return out.sort((a, b) => a.start - b.start || (a.id < b.id ? -1 : 1)); | |
| 48 | } | |
| 49 | ||
| 50 | // Where a crab is at time t: null while hidden, else its position and how far through the dash it is (0..1). | |
| 51 | function place(d, t) { | |
| 52 | if (t < d.start || t >= d.start + d.duration) return null; | |
| 53 | const p = (t - d.start) / d.duration, a = centre(d.from), b = centre(d.to); | |
| 54 | return { x: a.x + (b.x - a.x) * p, y: a.y + (b.y - a.y) * p, progress: p }; | |
| 55 | } | |
| 56 | const cellOf = pos => Math.min(ROWS - 1, Math.floor(pos.y)) * COLS + Math.min(COLS - 1, Math.floor(pos.x)); | |
| 57 | ||
| 58 | function refresh(s) { | |
| 59 | s.tide = round(Math.max(0, TIDE - s.time)); | |
| 60 | s.open = s.dashes.filter(d => !s.caught.includes(d.id)).map(d => ({ d, pos: place(d, s.time) })).filter(o => o.pos) | |
| 61 | .map(o => ({ id: o.d.id, x: round(o.pos.x), y: round(o.pos.y), cell: cellOf(o.pos), progress: round(o.pos.progress) })); | |
| 62 | s.crabs = s.caught.length; | |
| 63 | if (s.status !== 'playing') { | |
| 64 | s.line = s.status === 'won' ? `The tide is in: ${s.crabs} crabs, ${s.score} points: a win (${WIN} or more needed)` | |
| 65 | : `The tide is in: ${s.crabs} crabs, ${s.score} points: a loss (${WIN} or more needed)`; | |
| 66 | } else { | |
| 67 | s.line = `${s.crabs} of ${BUCKET} crabs in the bucket, ${s.score} points, ${Math.ceil(s.tide)} s of tide left`; | |
| 68 | } | |
| 69 | return s; | |
| 70 | } | |
| 71 | const copy = s => Object.assign({}, s, { caught: s.caught.slice() }); | |
| 72 | ||
| 73 | function start(seed = 1) { | |
| 74 | seed = finite(seed) >>> 0; | |
| 75 | return refresh({ seed, time: 0, cooldown: 0, dashes: schedule(seed), caught: [], score: 0, status: 'playing', why: '', line: '', tide: TIDE, open: [], crabs: 0 }); | |
| 76 | } | |
| 77 | ||
| 78 | // Advance by dt seconds (clamped to MAX_DT): the tide counts down, the cooldown runs out. At zero the round ends. | |
| 79 | function tick(state, dt) { | |
| 80 | if (state.status !== 'playing') return state; | |
| 81 | dt = Number.isFinite(dt) ? Math.min(MAX_DT, Math.max(0, dt)) : 0; | |
| 82 | const s = copy(state); | |
| 83 | s.time = round(Math.min(TIDE, s.time + dt)); | |
| 84 | s.cooldown = round(Math.max(0, s.cooldown - dt)); | |
| 85 | if (s.time >= TIDE) s.status = s.score >= WIN ? 'won' : 'lost'; | |
| 86 | return refresh(s); | |
| 87 | } | |
| 88 | ||
| 89 | const refuse = (s, why) => ({ ok: false, why, state: s }); | |
| 90 | // Scoop a cell (an integer index 0..CELLS-1). Catches the first crab in the open there, else a miss. | |
| 91 | function scoop(state, cell) { | |
| 92 | if (state.status !== 'playing') return refuse(state, 'over'); | |
| 93 | if (!Number.isInteger(cell) || cell < 0 || cell >= CELLS) return refuse(state, 'no-such-cell'); | |
| 94 | if (state.cooldown > 0) return refuse(state, 'cooldown'); | |
| 95 | if (state.caught.length >= BUCKET) return refuse(state, 'bucket-full'); | |
| 96 | const s = copy(state), hit = state.open.find(o => o.cell === cell); | |
| 97 | if (!hit) { | |
| 98 | s.cooldown = COOLDOWN; | |
| 99 | return { ok: true, caught: false, points: 0, why: 'miss', state: refresh(s) }; | |
| 100 | } | |
| 101 | const early = hit.progress < EARLY, points = CRAB_POINTS + (early ? BONUS : 0); | |
| 102 | s.caught.push(hit.id); | |
| 103 | s.score += points; | |
| 104 | return { ok: true, caught: true, early, points, why: '', state: refresh(s) }; | |
| 105 | } | |
| 106 | ||
| 107 | const api = { COLS, ROWS, CELLS, TIDE, DASHES, MIN_DASH, MAX_DASH, CRAB_POINTS, EARLY, BONUS, BUCKET, COOLDOWN, WIN, MAX_DT, start, tick, scoop }; | |
| 108 | if (typeof module !== 'undefined') module.exports = api; else root.RockPool = api; | |
| 109 | })(typeof window !== 'undefined' ? window : globalThis); |
rock-pool/pool.test.mjs added +113
| @@ -0,0 +1,113 @@ | ||
| 1 | import { test, expect } from 'bun:test'; | |
| 2 | import * as P from './pool.js'; | |
| 3 | const { CELLS, TIDE, CRAB_POINTS, BONUS, BUCKET, COOLDOWN, WIN, start, tick, scoop } = P; | |
| 4 | ||
| 5 | // a state at time t with the given dashes and nothing else | |
| 6 | const at = (t, dashes) => { const s = start(1); s.dashes = dashes; s.time = t; return tick(s, 0); }; | |
| 7 | const dash = (id, from, to, st, duration = 2) => ({ id, from, to, start: st, duration }); | |
| 8 | const advance = (s, secs) => { for (let i = 0; i < Math.round(secs / 0.1); i++) s = tick(s, 0.1); return s; }; | |
| 9 | ||
| 10 | test('the same seed gives the same schedule, other seeds differ, and every dash is well-formed', () => { | |
| 11 | expect(start(7).dashes).toEqual(start(7).dashes); | |
| 12 | expect(start(7).dashes).not.toEqual(start(8).dashes); | |
| 13 | for (const seed of [1, 2, 3, 99, 12345]) { | |
| 14 | const d = start(seed).dashes; | |
| 15 | expect(d).toHaveLength(P.DASHES); | |
| 16 | for (const x of d) { | |
| 17 | expect(x.from).not.toBe(x.to); | |
| 18 | for (const c of [x.from, x.to]) { expect(c).toBeGreaterThanOrEqual(0); expect(c).toBeLessThan(CELLS); } | |
| 19 | expect(x.start).toBeGreaterThanOrEqual(0); | |
| 20 | expect(x.start + x.duration).toBeLessThanOrEqual(TIDE + 1e-6); | |
| 21 | } | |
| 22 | } | |
| 23 | }); | |
| 24 | ||
| 25 | test('a crab is in the open only while it dashes, moving from rock to rock', () => { | |
| 26 | const d = [dash('a', 0, 3, 5, 2)]; | |
| 27 | expect(at(4.9, d).open).toEqual([]); | |
| 28 | const mid = at(6, d).open; | |
| 29 | expect(mid).toHaveLength(1); | |
| 30 | expect(mid[0].x).toBeCloseTo(2, 6); // halfway from x 0.5 to x 3.5 | |
| 31 | expect(mid[0].y).toBeCloseTo(0.5, 6); | |
| 32 | expect(mid[0].cell).toBe(2); | |
| 33 | expect(at(7, d).open).toEqual([]); | |
| 34 | }); | |
| 35 | ||
| 36 | test('tick counts the tide down, clamps dt, and ends the round at zero', () => { | |
| 37 | let s = start(1); | |
| 38 | expect(s.tide).toBe(TIDE); | |
| 39 | s = tick(s, 5); // clamped to MAX_DT | |
| 40 | expect(s.time).toBe(P.MAX_DT); | |
| 41 | s = advance(start(1), 10); | |
| 42 | expect(s.tide).toBeCloseTo(TIDE - 10, 6); | |
| 43 | expect(s.status).toBe('playing'); | |
| 44 | s = advance(s, TIDE); | |
| 45 | expect(s.tide).toBe(0); | |
| 46 | expect(s.status).not.toBe('playing'); | |
| 47 | expect(tick(s, 0.1)).toBe(s); | |
| 48 | expect(scoop(s, 0).ok).toBe(false); | |
| 49 | }); | |
| 50 | ||
| 51 | test('a scoop catches a crab in the open on that cell; a hidden crab is not there', () => { | |
| 52 | const d = [dash('a', 0, 3, 5, 2)]; | |
| 53 | const hit = scoop(at(6, d), 2); | |
| 54 | expect(hit.ok).toBe(true); | |
| 55 | expect(hit.caught).toBe(true); | |
| 56 | expect(hit.state.crabs).toBe(1); | |
| 57 | expect(hit.state.score).toBe(hit.points); | |
| 58 | expect(hit.state.open).toEqual([]); // the caught crab is gone | |
| 59 | const hidden = scoop(at(4, d), 0); // its rock, before it dashes | |
| 60 | expect(hidden.caught).toBe(false); | |
| 61 | expect(hidden.why).toBe('miss'); | |
| 62 | }); | |
| 63 | ||
| 64 | test('a miss starts a cooldown in which scoops are refused, and tick runs it out', () => { | |
| 65 | const d = [dash('a', 0, 3, 5, 2)]; | |
| 66 | const miss = scoop(at(6, d), 15); | |
| 67 | expect(miss.caught).toBe(false); | |
| 68 | expect(miss.state.cooldown).toBe(COOLDOWN); | |
| 69 | const refused = scoop(miss.state, 2); // the crab is right there, but the net is down | |
| 70 | expect(refused.ok).toBe(false); | |
| 71 | expect(refused.why).toBe('cooldown'); | |
| 72 | expect(refused.state).toBe(miss.state); | |
| 73 | const later = advance(miss.state, COOLDOWN); | |
| 74 | expect(later.cooldown).toBe(0); | |
| 75 | expect(scoop(later, 15).ok).toBe(true); | |
| 76 | }); | |
| 77 | ||
| 78 | test('a catch in the first third of the dash scores the bonus, later does not', () => { | |
| 79 | const d = [dash('a', 0, 3, 0, 3)]; | |
| 80 | const early = scoop(at(0.3, d), 0); // progress 0.1, still in cell 0 | |
| 81 | expect(early.early).toBe(true); | |
| 82 | expect(early.points).toBe(CRAB_POINTS + BONUS); | |
| 83 | const late = scoop(at(1.5, d), 2); // progress 0.5 | |
| 84 | expect(late.early).toBe(false); | |
| 85 | expect(late.points).toBe(CRAB_POINTS); | |
| 86 | expect(late.state.score).toBe(CRAB_POINTS); | |
| 87 | }); | |
| 88 | ||
| 89 | test('the bucket holds a stated maximum', () => { | |
| 90 | const d = Array.from({ length: BUCKET + 1 }, (_, i) => dash('c' + i, 0, 1, 1, 2)); | |
| 91 | let s = at(1.5, d); // all in the open on the first rock's cell | |
| 92 | for (let i = 0; i < BUCKET; i++) { const r = scoop(s, 0); expect(r.caught).toBe(true); s = r.state; } | |
| 93 | expect(s.crabs).toBe(BUCKET); | |
| 94 | const full = scoop(s, 0); | |
| 95 | expect(full.ok).toBe(false); | |
| 96 | expect(full.why).toBe('bucket-full'); | |
| 97 | }); | |
| 98 | ||
| 99 | test('a bad cell is refused', () => { | |
| 100 | const s = start(1); | |
| 101 | for (const bad of [-1, CELLS, 1.5, NaN, '0', undefined]) expect(scoop(s, bad).state).toBe(s); | |
| 102 | }); | |
| 103 | ||
| 104 | test('at or over the win score is a win, under it a loss', () => { | |
| 105 | const winning = start(1); winning.score = WIN; winning.time = TIDE - 0.05; | |
| 106 | const w = tick(winning, 0.1); | |
| 107 | expect(w.status).toBe('won'); | |
| 108 | expect(w.line).toContain('a win'); | |
| 109 | const losing = start(1); losing.score = WIN - 1; losing.time = TIDE - 0.05; | |
| 110 | const l = tick(losing, 0.1); | |
| 111 | expect(l.status).toBe('lost'); | |
| 112 | expect(l.line).toContain('a loss'); | |
| 113 | }); |
scripts/test.mjs added +32
| @@ -0,0 +1,32 @@ | ||
| 1 | // The test run, in parallel: the playtest suite (every game booted and played, minutes in all) is split in shards | |
| 2 | // and every other test file runs in one more process alongside. Same tests as `bun test`, less wall-clock time. | |
| 3 | // Usage: bun scripts/test.mjs | |
| 4 | import { readdirSync } from 'node:fs'; | |
| 5 | import { join, relative } from 'node:path'; | |
| 6 | ||
| 7 | const root = join(import.meta.dir, '..'); | |
| 8 | const SHARDS = 8; | |
| 9 | ||
| 10 | function testFiles(dir) { | |
| 11 | const out = []; | |
| 12 | for (const e of readdirSync(dir, { withFileTypes: true })) { | |
| 13 | if (e.name === 'node_modules' || e.name.startsWith('.')) continue; | |
| 14 | const p = join(dir, e.name); | |
| 15 | if (e.isDirectory()) out.push(...testFiles(p)); | |
| 16 | else if (/\.test\.(m?[jt]s)$/.test(e.name)) out.push(relative(root, p)); | |
| 17 | } | |
| 18 | return out; | |
| 19 | } | |
| 20 | ||
| 21 | const rest = testFiles(root).filter(f => f !== 'playtest.test.mjs').map(f => './' + f); | |
| 22 | const runs = [{ name: 'rest', args: rest, env: {} }]; | |
| 23 | for (let i = 0; i < SHARDS; i++) runs.push({ name: `playtest ${i + 1}/${SHARDS}`, args: ['./playtest.test.mjs'], env: { PLAYTEST_SHARD: `${i}/${SHARDS}` } }); | |
| 24 | ||
| 25 | const results = await Promise.all(runs.map(async r => { | |
| 26 | const p = Bun.spawn(['bun', 'test', ...r.args], { cwd: root, env: { ...process.env, ...r.env }, stdout: 'pipe', stderr: 'pipe' }); | |
| 27 | const [out, err] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]); | |
| 28 | return { name: r.name, code: await p.exited, text: out + err }; | |
| 29 | })); | |
| 30 | ||
| 31 | for (const r of results) console.log(`\n===== ${r.name}: ${r.code === 0 ? 'ok' : 'FAILED'} =====\n${r.text}`); | |
| 32 | process.exit(results.every(r => r.code === 0) ? 0 : 1); |
serve.test.mjs +2 −1
| @@ -243,7 +243,8 @@ test('every committed card is what the games render now, and capture is determin | ||
| 243 | 243 | const frames = []; |
| 244 | 244 | for (const g of games()) { |
| 245 | 245 | const frame = capture(g.id); |
| 246 | expect(Buffer.from(capture(g.id)).equals(Buffer.from(frame))).toBe(true); | |
| 246 | // the committed-card comparison below already proves every game repeats; one second capture shows it directly | |
| 247 | if (!frames.length) expect(Buffer.from(capture(g.id)).equals(Buffer.from(frame))).toBe(true); | |
| 247 | 248 | frames.push(frame); |
| 248 | 249 | expect(card(frame).equals(readFileSync(new URL(`./og/${g.id}.png`, import.meta.url)))).toBe(true); |
| 249 | 250 | } |
new above
offline