Public: anyone can read this; the crew can change it.
Migrated from github.com/amirmushichge/pixel-plays
Patchwork Quilt rules: a tested `quilt/patch.js` where you rotate and swap square patches until every stitched edge matches its neighbour, from plain data #223
torque/pixel-plays:torque/217-patchwork-quilt-rules-a-tested-quilt-pat → main 3 commits fork
5 files
changed +256
−4
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 +6 −3
| @@ -6,8 +6,11 @@ setDefaultTimeout(60000); | ||
| 6 | 6 | |
| 7 | 7 | // Every game page is booted for real (its scripts, the shell and the engine) and played by a |
| 8 | 8 | // seeded stand-in for a person: taps, holds, drags and key presses at the canvas. |
| 9 | const GAMES = readdirSync(import.meta.dir, { withFileTypes: true }) | |
| 9 | const ALL = 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 | // PLAYTEST_SHARD="i/n" plays only every n-th game from i, so scripts/test.mjs can run the shards side by side | |
| 12 | const [shard, shards] = /^(\d+)\/(\d+)$/.test(process.env.PLAYTEST_SHARD || '') ? process.env.PLAYTEST_SHARD.split('/').map(Number) : [0, 1]; | |
| 13 | const GAMES = ALL.filter((_, i) => i % shards === shard); | |
| 11 | 14 | |
| 12 | 15 | const rand = seed => () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; }; |
| 13 | 16 | const KEYS = [' ', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Enter']; |
| @@ -25,10 +28,10 @@ function gesture(g, r) { | ||
| 25 | 28 | function sync(idle, played) { idle.step(played.frames - idle.frames); expect(idle.frames).toBe(played.frames); } |
| 26 | 29 | |
| 27 | 30 | test('every game has a scripted round, and every script has a game', () => { |
| 28 | expect(Object.keys(ROUNDS).sort()).toEqual(GAMES); | |
| 31 | expect(Object.keys(ROUNDS).sort()).toEqual(ALL); | |
| 29 | 32 | }); |
| 30 | 33 | |
| 31 | test('the games folder is not empty', () => { expect(GAMES.length).toBeGreaterThanOrEqual(19); }); | |
| 34 | test('the games folder is not empty', () => { expect(ALL.length).toBeGreaterThanOrEqual(19); }); | |
| 32 | 35 | |
| 33 | 36 | for (const id of GAMES) { |
| 34 | 37 | test(`${id}: boots, paints a picture and says what to do`, () => { |
quilt/patch.js added +133
| @@ -0,0 +1,133 @@ | ||
| 1 | 'use strict'; | |
| 2 | // The Patchwork Quilt rules: a quilt of square patches, each edge stitched with one pattern, scrambled by turning and | |
| 3 | // moving patches; put it back so every shared edge matches its neighbour. | |
| 4 | // Plain data in, plain data out, no DOM, no timers, no Math.random: the quilt and its scramble come from the seed. | |
| 5 | // A rejected move returns the very same state and says why. The page draws what this decides. | |
| 6 | // | |
| 7 | // The quilt is a SIZE x SIZE grid, x to the east and y to the south, cells given as { x, y }. A patch lists its edges | |
| 8 | // clockwise from the top: [top, right, bottom, left], each a stitch number 0 .. STITCHES - 1. A quarter turn clockwise | |
| 9 | // moves the left edge to the top. Every rotate and every swap is one move; MOVE_LIMIT moves are allowed. | |
| 10 | // Scoring: SCORE_PER_EDGE points for each shared edge a move newly matches; finishing with moves to spare adds | |
| 11 | // BONUS_PER_MOVE points for every move left. | |
| 12 | (function (root) { | |
| 13 | const SIZE = 3, STITCHES = 4, MOVE_LIMIT = 40, SCORE_PER_EDGE = 10, BONUS_PER_MOVE = 5; | |
| 14 | const SHARED = 2 * SIZE * (SIZE - 1); // shared edges: SIZE - 1 seams in each of SIZE rows and SIZE columns | |
| 15 | ||
| 16 | const finite = v => (Number.isFinite(v) ? v : 0); | |
| 17 | // a repeatable number in [0, 1) for this seed and slot | |
| 18 | function noise(seed, n) { | |
| 19 | let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0; | |
| 20 | h = Math.imul(h ^ (h >>> 13), 1274126177); | |
| 21 | return ((h ^ (h >>> 16)) >>> 0) / 4294967296; | |
| 22 | } | |
| 23 | const turn = e => [e[3], e[0], e[1], e[2]]; // one quarter turn clockwise | |
| 24 | const index = (x, y) => y * SIZE + x; | |
| 25 | const cellOk = c => !!c && Number.isInteger(c.x) && Number.isInteger(c.y) && c.x >= 0 && c.y >= 0 && c.x < SIZE && c.y < SIZE; | |
| 26 | ||
| 27 | // the solved quilt for a seed: every seam gets one stitch seen from both sides, border edges are free | |
| 28 | function solved(seed) { | |
| 29 | let n = 0; | |
| 30 | const rnd = () => Math.floor(noise(seed, n++) * STITCHES); | |
| 31 | const patches = []; | |
| 32 | for (let i = 0; i < SIZE * SIZE; i++) patches.push([0, 0, 0, 0]); | |
| 33 | for (let y = 0; y < SIZE; y++) for (let x = 0; x < SIZE; x++) { | |
| 34 | const p = patches[index(x, y)]; | |
| 35 | p[0] = y > 0 ? patches[index(x, y - 1)][2] : rnd(); | |
| 36 | p[3] = x > 0 ? patches[index(x - 1, y)][1] : rnd(); | |
| 37 | p[1] = rnd(); p[2] = rnd(); | |
| 38 | } | |
| 39 | return patches; | |
| 40 | } | |
| 41 | ||
| 42 | // the seams of a quilt: each pair of neighbouring cells once, with whether their touching edges carry the same stitch | |
| 43 | function seams(s) { | |
| 44 | const out = []; | |
| 45 | for (let y = 0; y < SIZE; y++) for (let x = 0; x < SIZE; x++) { | |
| 46 | const p = s.patches[index(x, y)].edges; | |
| 47 | if (x < SIZE - 1) out.push({ a: { x, y }, b: { x: x + 1, y }, match: p[1] === s.patches[index(x + 1, y)].edges[3] }); | |
| 48 | if (y < SIZE - 1) out.push({ a: { x, y }, b: { x, y: y + 1 }, match: p[2] === s.patches[index(x, y + 1)].edges[0] }); | |
| 49 | } | |
| 50 | return out; | |
| 51 | } | |
| 52 | // matches(state) -> { count, total, edges }: which shared edges match | |
| 53 | function matches(s) { | |
| 54 | const edges = seams(s); | |
| 55 | return { count: edges.filter(e => e.match).length, total: edges.length, edges }; | |
| 56 | } | |
| 57 | ||
| 58 | function refresh(s) { | |
| 59 | const m = matches(s).count, left = s.limit - s.moves; | |
| 60 | if (s.status === 'won') s.line = `Quilt finished: all ${SHARED} edges match with ${left} ${left === 1 ? 'move' : 'moves'} to spare`; | |
| 61 | else if (s.status === 'lost') s.line = `Out of moves: ${m} of ${SHARED} edges match`; | |
| 62 | else s.line = `${m} of ${SHARED} edges match, ${left} ${left === 1 ? 'move' : 'moves'} left`; | |
| 63 | return s; | |
| 64 | } | |
| 65 | const copy = s => ({ ...s, patches: s.patches.map(p => ({ id: p.id, edges: p.edges.slice() })) }); | |
| 66 | ||
| 67 | // start(seed): a solved quilt, then scrambled by a seeded shuffle of the patches and a seeded turn of each. | |
| 68 | // Patches remember their home cell (id) so the way back is always known: solvable by construction. | |
| 69 | function start(seed = 1) { | |
| 70 | seed = finite(seed) >>> 0; | |
| 71 | const home = solved(seed); | |
| 72 | for (let attempt = 0; attempt < 50; attempt++) { | |
| 73 | let n = attempt * 101; | |
| 74 | const order = home.map((_, i) => i); | |
| 75 | for (let i = order.length - 1; i > 0; i--) { | |
| 76 | const j = Math.floor(noise(seed, 1000 + n++) * (i + 1)); | |
| 77 | [order[i], order[j]] = [order[j], order[i]]; | |
| 78 | } | |
| 79 | const patches = order.map(id => { | |
| 80 | let edges = home[id]; | |
| 81 | for (let t = Math.floor(noise(seed, 2000 + n++) * 4); t > 0; t--) edges = turn(edges); | |
| 82 | return { id, edges }; | |
| 83 | }); | |
| 84 | const s = { seed, size: SIZE, stitches: STITCHES, limit: MOVE_LIMIT, moves: 0, score: 0, status: 'playing', line: '', patches }; | |
| 85 | if (matches(s).count < SHARED) return refresh(s); | |
| 86 | } | |
| 87 | throw new Error('no scramble found'); // unreachable for any seed in practice | |
| 88 | } | |
| 89 | ||
| 90 | // after a move: score what it gained, then settle the game | |
| 91 | function settle(before, n) { | |
| 92 | n.moves = before.moves + 1; | |
| 93 | const was = matches(before).count, now = matches(n).count; | |
| 94 | if (now > was) n.score = before.score + SCORE_PER_EDGE * (now - was); | |
| 95 | if (now === SHARED) { n.status = 'won'; n.score += BONUS_PER_MOVE * (n.limit - n.moves); } | |
| 96 | else if (n.moves >= n.limit) n.status = 'lost'; | |
| 97 | return refresh(n); | |
| 98 | } | |
| 99 | const refuse = (s, why) => ({ ok: false, why, state: s }); | |
| 100 | ||
| 101 | // rotate(state, cell) -> { ok, why, state } | |
| 102 | function rotate(s, cell) { | |
| 103 | if (s.status !== 'playing') return refuse(s, 'over'); | |
| 104 | if (!cellOk(cell)) return refuse(s, 'off-grid'); | |
| 105 | const n = copy(s), p = n.patches[index(cell.x, cell.y)]; | |
| 106 | p.edges = turn(p.edges); | |
| 107 | return { ok: true, why: '', state: settle(s, n) }; | |
| 108 | } | |
| 109 | // swap(state, a, b) -> { ok, why, state } | |
| 110 | function swap(s, a, b) { | |
| 111 | if (s.status !== 'playing') return refuse(s, 'over'); | |
| 112 | if (!cellOk(a) || !cellOk(b)) return refuse(s, 'off-grid'); | |
| 113 | const i = index(a.x, a.y), j = index(b.x, b.y); | |
| 114 | if (i === j) return refuse(s, 'same-cell'); | |
| 115 | const n = copy(s); | |
| 116 | [n.patches[i], n.patches[j]] = [n.patches[j], n.patches[i]]; | |
| 117 | return { ok: true, why: '', state: settle(s, n) }; | |
| 118 | } | |
| 119 | ||
| 120 | // solution(state): moves ({ type: 'swap' | 'rotate', ... }) that restore the original quilt, at most MOVE_LIMIT of them | |
| 121 | function solution(s) { | |
| 122 | const home = solved(s.seed), cur = s.patches.map(p => ({ id: p.id, edges: p.edges.slice() })), out = []; | |
| 123 | for (let i = 0; i < cur.length; i++) { | |
| 124 | const j = cur.findIndex(p => p.id === i); | |
| 125 | if (j !== i) { out.push({ type: 'swap', a: { x: i % SIZE, y: Math.floor(i / SIZE) }, b: { x: j % SIZE, y: Math.floor(j / SIZE) } }); [cur[i], cur[j]] = [cur[j], cur[i]]; } | |
| 126 | while (cur[i].edges.join() !== home[i].join()) { cur[i].edges = turn(cur[i].edges); out.push({ type: 'rotate', cell: { x: i % SIZE, y: Math.floor(i / SIZE) } }); } | |
| 127 | } | |
| 128 | return out; | |
| 129 | } | |
| 130 | ||
| 131 | const api = { SIZE, STITCHES, MOVE_LIMIT, SCORE_PER_EDGE, BONUS_PER_MOVE, SHARED, start, rotate, swap, matches, solution, turn }; | |
| 132 | if (typeof module !== 'undefined') module.exports = api; else root.Quilt = api; | |
| 133 | })(typeof window !== 'undefined' ? window : globalThis); |
quilt/patch.test.mjs added +105
| @@ -0,0 +1,105 @@ | ||
| 1 | import { test, expect } from 'bun:test'; | |
| 2 | import { SIZE, STITCHES, MOVE_LIMIT, SCORE_PER_EDGE, BONUS_PER_MOVE, SHARED, start, rotate, swap, matches, solution, turn } from './patch.js'; | |
| 3 | ||
| 4 | const play = (s, moves) => moves.reduce((st, m) => (m.type === 'swap' ? swap(st, m.a, m.b) : rotate(st, m.cell)).state, s); | |
| 5 | // a hand-made quilt where every patch is the same, so every seam matches | |
| 6 | const flat = (extra = {}) => ({ ...start(1), patches: Array.from({ length: 9 }, (_, i) => ({ id: i, edges: [1, 1, 1, 1] })), moves: 0, score: 0, status: 'playing', ...extra }); | |
| 7 | ||
| 8 | test('the same seed gives the same scramble, other seeds differ, and the grid size and limit are stated', () => { | |
| 9 | expect(start(7)).toEqual(start(7)); | |
| 10 | const seen = new Set(); | |
| 11 | for (let seed = 1; seed <= 20; seed++) seen.add(JSON.stringify(start(seed).patches)); | |
| 12 | expect(seen.size).toBeGreaterThan(15); | |
| 13 | const s = start(3); | |
| 14 | expect(s.size).toBe(SIZE); expect(s.limit).toBe(MOVE_LIMIT); expect(s.patches).toHaveLength(SIZE * SIZE); | |
| 15 | expect(SHARED).toBe(12); | |
| 16 | for (const p of s.patches) for (const e of p.edges) { expect(e).toBeGreaterThanOrEqual(0); expect(e).toBeLessThan(STITCHES); } | |
| 17 | }); | |
| 18 | ||
| 19 | test('every scramble is solvable within the move limit and never starts finished', () => { | |
| 20 | for (let seed = 0; seed < 200; seed++) { | |
| 21 | const s = start(seed); | |
| 22 | expect(matches(s).count).toBeLessThan(SHARED); | |
| 23 | const sol = solution(s); | |
| 24 | expect(sol.length).toBeLessThanOrEqual(MOVE_LIMIT); | |
| 25 | const end = play(s, sol); | |
| 26 | expect([seed, end.status]).toEqual([seed, 'won']); | |
| 27 | expect(matches(end).count).toBe(SHARED); | |
| 28 | } | |
| 29 | }); | |
| 30 | ||
| 31 | test('rotate turns a patch a quarter turn clockwise and counts one move', () => { | |
| 32 | const s = start(5), before = s.patches[4].edges; | |
| 33 | const r = rotate(s, { x: 1, y: 1 }); | |
| 34 | expect(r.ok).toBe(true); | |
| 35 | expect(r.state.moves).toBe(1); | |
| 36 | expect(r.state.patches[4].edges).toEqual([before[3], before[0], before[1], before[2]]); | |
| 37 | expect(turn(turn(turn(turn(before))))).toEqual(before); | |
| 38 | expect(s.moves).toBe(0); // the old state is untouched | |
| 39 | }); | |
| 40 | ||
| 41 | test('swap exchanges two patches and counts one move', () => { | |
| 42 | const s = start(5); | |
| 43 | const r = swap(s, { x: 0, y: 0 }, { x: 2, y: 1 }); | |
| 44 | expect(r.ok).toBe(true); | |
| 45 | expect(r.state.moves).toBe(1); | |
| 46 | expect(r.state.patches[0]).toEqual(s.patches[5]); | |
| 47 | expect(r.state.patches[5]).toEqual(s.patches[0]); | |
| 48 | expect(swap(s, { x: 1, y: 1 }, { x: 1, y: 1 })).toEqual({ ok: false, why: 'same-cell', state: s }); | |
| 49 | }); | |
| 50 | ||
| 51 | test('a cell off the grid is refused and changes nothing', () => { | |
| 52 | const s = start(5); | |
| 53 | for (const c of [{ x: -1, y: 0 }, { x: 3, y: 0 }, { x: 0, y: 3 }, { x: 1.5, y: 1 }, null, {}, { x: '1', y: 1 }]) { | |
| 54 | const r = rotate(s, c); | |
| 55 | expect(r.ok).toBe(false); expect(r.why).toBe('off-grid'); expect(r.state).toBe(s); | |
| 56 | } | |
| 57 | const r = swap(s, { x: 0, y: 0 }, { x: 9, y: 9 }); | |
| 58 | expect(r.ok).toBe(false); expect(r.why).toBe('off-grid'); expect(r.state).toBe(s); | |
| 59 | expect(s.moves).toBe(0); | |
| 60 | }); | |
| 61 | ||
| 62 | test('matches reports which shared edges match', () => { | |
| 63 | const m = matches(flat()); | |
| 64 | expect(m.total).toBe(12); expect(m.count).toBe(12); expect(m.edges.every(e => e.match)).toBe(true); | |
| 65 | const s = flat(); | |
| 66 | s.patches[0] = { id: 0, edges: [1, 2, 1, 1] }; // its east edge now differs from patch 1's west edge | |
| 67 | const m2 = matches(s); | |
| 68 | expect(m2.count).toBe(11); | |
| 69 | expect(m2.edges.filter(e => !e.match)).toEqual([{ a: { x: 0, y: 0 }, b: { x: 1, y: 0 }, match: false }]); | |
| 70 | }); | |
| 71 | ||
| 72 | test('a move that raises the matching edges scores, one that does not scores nothing', () => { | |
| 73 | const s = flat(); | |
| 74 | s.patches[0] = { id: 0, edges: [1, 2, 1, 1] }; // one bad seam (east) | |
| 75 | const worse = rotate(s, { x: 0, y: 0 }); // [1,1,2,1]: east fixed, but south now differs | |
| 76 | expect(matches(worse.state).count).toBe(11); | |
| 77 | expect(worse.state.score).toBe(0); // 11 -> 11: no gain | |
| 78 | const better = rotate(worse.state, { x: 0, y: 0 }); // [1,1,1,2]: both seams good again | |
| 79 | expect(matches(better.state).count).toBe(12); | |
| 80 | expect(better.state.score).toBe(SCORE_PER_EDGE + BONUS_PER_MOVE * (MOVE_LIMIT - 2)); | |
| 81 | }); | |
| 82 | ||
| 83 | test('finishing under the limit adds a bonus per move left, and the game ends with a win line', () => { | |
| 84 | const s = start(11), sol = solution(s); | |
| 85 | const end = play(s, sol); | |
| 86 | expect(end.status).toBe('won'); | |
| 87 | expect(end.line).toBe(`Quilt finished: all ${SHARED} edges match with ${MOVE_LIMIT - sol.length} ${MOVE_LIMIT - sol.length === 1 ? 'move' : 'moves'} to spare`); | |
| 88 | expect(end.score).toBeGreaterThanOrEqual(BONUS_PER_MOVE * (MOVE_LIMIT - sol.length)); | |
| 89 | const again = rotate(end, { x: 0, y: 0 }); | |
| 90 | expect(again.ok).toBe(false); expect(again.why).toBe('over'); expect(again.state).toBe(end); | |
| 91 | }); | |
| 92 | ||
| 93 | test('reaching the move limit before the quilt matches ends the game with a loss line', () => { | |
| 94 | let s = flat(); | |
| 95 | s.patches[0] = { id: 0, edges: [1, 2, 3, 1] }; | |
| 96 | s.moves = MOVE_LIMIT - 1; | |
| 97 | const r = swap(s, { x: 1, y: 1 }, { x: 2, y: 2 }); // identical patches: nothing improves | |
| 98 | expect(r.ok).toBe(true); | |
| 99 | expect(r.state.status).toBe('lost'); | |
| 100 | expect(r.state.line).toBe(`Out of moves: ${matches(r.state).count} of ${SHARED} edges match`); | |
| 101 | expect(rotate(r.state, { x: 0, y: 0 }).why).toBe('over'); | |
| 102 | const playing = start(2); | |
| 103 | expect(playing.status).toBe('playing'); | |
| 104 | expect(playing.line).toContain('moves left'); | |
| 105 | }); |
scripts/test.mjs added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | // The full check: the playtest is the long pole (every game played in a software renderer), so it runs in SHARDS | |
| 2 | // parallel slices beside the rest of the suite. Exit status is non-zero if any slice fails. | |
| 3 | import { availableParallelism } from 'node:os'; | |
| 4 | const SHARDS = Math.max(2, Math.min(6, availableParallelism())); | |
| 5 | const run = (args, env = {}) => Bun.spawn(['bun', 'test', ...args], { stdout: 'inherit', stderr: 'inherit', env: { ...process.env, ...env } }).exited; | |
| 6 | const rest = [...new Bun.Glob('**/*.test.{mjs,js,ts}').scanSync('.')].filter(f => !f.startsWith('node_modules') && f !== 'playtest.test.mjs').map(f => './' + f); | |
| 7 | const codes = await Promise.all([ | |
| 8 | run(rest), | |
| 9 | ...Array.from({ length: SHARDS }, (_, i) => run(['./playtest.test.mjs'], { PLAYTEST_SHARD: `${i}/${SHARDS}` })), | |
| 10 | ]); | |
| 11 | process.exit(codes.some(c => c !== 0) ? 1 : 0); |
new above
offline