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 #232

Merged opened this

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

Merged

vesper/pixel-plays:vesper/217-patchwork-quilt-rules-a-tested-quilt-pat → main 1 commit fork

  • Merged. vesper/217-patchwork-quilt-rules-a-tested-quilt-pat was merged into main as 33e8848.

Review

Sign in to review this change.
2 files changed +298 −0
quilt/patch.js added +167
@@ -0,0 +1,167 @@
1 'use strict';
2 // The Patchwork Quilt rules: a quilt of square patches, each edge stitched in one of a few patterns, has been
3 // scrambled by rotation and position; turn and swap patches until every shared edge matches its neighbour.
4 // Plain data in, plain data out, no DOM, no timers, no Math.random: the quilt comes from the seed.
5 // A rejected call returns the very same state and says why. The page draws what this decides.
6 //
7 // A cell is its index 0..SIZE * SIZE - 1, counted along rows from the top left. A patch is its four stitches,
8 // [top, right, bottom, left], each 0..STITCHES - 1. Two neighbours match when the stitches that touch are equal.
9 (function (root) {
10 const SIZE = 3; // the quilt is SIZE patches wide and SIZE patches tall
11 const STITCHES = 4; // stitch patterns an edge can carry
12 const MOVE_LIMIT = 24; // moves allowed; any scramble can be undone in at most 20
13 const GAIN_SCORE = 10; // points for a move that raises the number of matching edges
14 const LEFT_BONUS = 5; // points for each move left when the quilt is finished
15 const CELLS = SIZE * SIZE;
16
17 const finite = v => (Number.isFinite(v) ? v : 0);
18 // a repeatable number in [0, 1) for this seed and slot
19 function noise(seed, n) {
20 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
21 h = Math.imul(h ^ (h >>> 13), 1274126177);
22 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
23 }
24
25 // every shared edge as { a, b, side }: patch a's right (side 1) or bottom (side 2) touches patch b
26 const EDGES = [];
27 for (let r = 0; r < SIZE; r++) {
28 for (let c = 0; c < SIZE; c++) {
29 const i = r * SIZE + c;
30 if (c + 1 < SIZE) EDGES.push({ a: i, b: i + 1, side: 1 });
31 if (r + 1 < SIZE) EDGES.push({ a: i, b: i + SIZE, side: 2 });
32 }
33 }
34
35 const turn = p => [p[3], p[0], p[1], p[2]]; // a quarter turn clockwise
36
37 // the quilt as it was sewn: every shared edge carries one stitch, seen from both patches
38 function sewn(seed) {
39 let slot = 0;
40 const patches = Array.from({ length: CELLS }, () => [0, 0, 0, 0]);
41 const pick = () => Math.floor(noise(seed, slot++) * STITCHES);
42 for (const e of EDGES) {
43 const v = pick();
44 patches[e.a][e.side] = v;
45 patches[e.b][(e.side + 2) % 4] = v;
46 }
47 for (let i = 0; i < CELLS; i++) {
48 const r = Math.floor(i / SIZE), c = i % SIZE;
49 for (let k = 0; k < 4; k++) {
50 const outer = (k === 0 && r === 0) || (k === 2 && r === SIZE - 1) || (k === 1 && c === SIZE - 1) || (k === 3 && c === 0);
51 if (outer) patches[i][k] = pick();
52 }
53 }
54 return patches;
55 }
56
57 // matches(state) -> [{ a, b, ok }] for every shared edge; ok when the touching stitches are equal
58 function matches(s) {
59 return EDGES.map(e => ({ a: e.a, b: e.b, ok: s.patches[e.a][e.side] === s.patches[e.b][(e.side + 2) % 4] }));
60 }
61 const count = s => matches(s).filter(m => m.ok).length;
62
63 function refresh(s) {
64 s.matching = count(s);
65 if (s.status === 'over') {
66 s.line = s.won
67 ? `Quilt finished: ${s.score} points, ${s.limit - s.moves} moves to spare`
68 : `Out of moves: ${s.matching} of ${s.edges} edges match, ${s.score} points`;
69 } else {
70 s.line = `Move ${s.moves} of ${s.limit}: ${s.matching} of ${s.edges} edges match, ${s.score} points`;
71 }
72 return s;
73 }
74
75 // The scramble is a short run of steps taken from the sewn quilt: SWAPS exchanges and TURNS quarter turns, in a seeded
76 // order. Undoing it takes each swap again and three turns for each turn, in reverse, so at most SWAPS + 3 * TURNS moves.
77 const SWAPS = 5;
78 const TURNS = 5;
79 function steps(seed, attempt) {
80 let slot = 1000 + attempt * 100;
81 const list = [];
82 for (let i = 0; i < SWAPS + TURNS; i++) list.push(i < SWAPS ? 's' : 'r');
83 for (let i = list.length - 1; i > 0; i--) { // seeded shuffle of the order
84 const j = Math.floor(noise(seed, slot++) * (i + 1));
85 [list[i], list[j]] = [list[j], list[i]];
86 }
87 return list.map(kind => {
88 const a = Math.floor(noise(seed, slot++) * CELLS);
89 if (kind === 'r') return ['r', a];
90 const b = (a + 1 + Math.floor(noise(seed, slot++) * (CELLS - 1))) % CELLS;
91 return ['s', a, b];
92 });
93 }
94 function apply(patches, step) {
95 if (step[0] === 'r') patches[step[1]] = turn(patches[step[1]]);
96 else [patches[step[1]], patches[step[2]]] = [patches[step[2]], patches[step[1]]];
97 }
98 // the first attempt whose scramble is not already finished
99 function plan(seed) {
100 for (let attempt = 0; ; attempt++) {
101 const list = steps(seed, attempt);
102 const patches = sewn(seed);
103 for (const st of list) apply(patches, st);
104 if (count({ patches }) < EDGES.length) return { list, patches };
105 }
106 }
107
108 // solution(seed) -> the moves, as ['r', cell] and ['s', a, b], that take the scrambled quilt back to the sewn one
109 function solution(seed) {
110 const out = [];
111 for (const st of plan(finite(seed) >>> 0).list.reverse()) {
112 if (st[0] === 'r') out.push(st, st, st); else out.push(st);
113 }
114 return out;
115 }
116
117 const start = (seed = 1) => {
118 const sd = finite(seed) >>> 0;
119 return refresh({
120 seed: sd, size: SIZE, stitches: STITCHES, limit: MOVE_LIMIT, edges: EDGES.length, patches: plan(sd).patches,
121 moves: 0, matching: 0, score: 0, status: 'playing', won: false, line: '',
122 });
123 };
124
125 const refuse = (s, why) => ({ ok: false, why, event: '', state: s });
126 const onGrid = i => Number.isInteger(i) && i >= 0 && i < CELLS;
127
128 // one move made on a copy: scores a gain, then decides the win or the loss
129 function settle(s, n) {
130 n.moves += 1;
131 n.matching = count(n);
132 let event = 'moved';
133 if (n.matching > s.matching) { n.score += GAIN_SCORE; event = 'gain'; }
134 if (n.matching === n.edges) {
135 n.score += (n.limit - n.moves) * LEFT_BONUS; n.status = 'over'; n.won = true; event = 'won';
136 } else if (n.moves >= n.limit) {
137 n.status = 'over'; n.won = false; event = 'lost';
138 }
139 return { ok: true, why: '', event, state: refresh(n) };
140 }
141
142 const copy = s => Object.assign({}, s, { patches: s.patches.slice() });
143
144 // rotate(state, cell) -> { ok, why, event, state }: that patch turns a quarter turn clockwise
145 function rotate(s, cell) {
146 if (s.status !== 'playing') return refuse(s, 'over');
147 if (!onGrid(cell)) return refuse(s, 'bad-cell');
148 const n = copy(s);
149 n.patches[cell] = turn(n.patches[cell]);
150 return settle(s, n);
151 }
152
153 // swap(state, a, b) -> { ok, why, event, state }: the two patches change places; a patch with itself is refused
154 function swap(s, a, b) {
155 if (s.status !== 'playing') return refuse(s, 'over');
156 if (!onGrid(a) || !onGrid(b)) return refuse(s, 'bad-cell');
157 if (a === b) return refuse(s, 'same-cell');
158 const n = copy(s);
159 [n.patches[a], n.patches[b]] = [n.patches[b], n.patches[a]];
160 return settle(s, n);
161 }
162
163 const api = {
164 SIZE, STITCHES, MOVE_LIMIT, GAIN_SCORE, LEFT_BONUS, start, rotate, swap, matches, solution, turn, sewn,
165 };
166 if (typeof module !== 'undefined') module.exports = api; else root.Quilt = api;
167 })(typeof window !== 'undefined' ? window : globalThis);
quilt/patch.test.mjs added +131
@@ -0,0 +1,131 @@
1 import { test, expect } from 'bun:test';
2 import { SIZE, MOVE_LIMIT, GAIN_SCORE, LEFT_BONUS, start, rotate, swap, matches, solution, turn, sewn } from './patch.js';
3
4 const ok = s => matches(s).filter(m => m.ok).length;
5 // the quilt as sewn, with one patch turned a quarter, `moves` already spent and the matching count kept honest
6 const nearly = (seed, cell, moves) => {
7 const s = start(seed);
8 const patches = sewn(seed);
9 patches[cell] = turn(patches[cell]);
10 const n = { ...s, patches, moves };
11 n.matching = ok(n);
12 return n;
13 };
14
15 test('the same seed gives the same scramble, other seeds differ, and the stated sizes hold', () => {
16 expect(start(7)).toEqual(start(7));
17 const seen = new Set();
18 for (let seed = 1; seed <= 20; seed++) seen.add(JSON.stringify(start(seed).patches));
19 expect(seen.size).toBeGreaterThan(15);
20 const s = start(3);
21 expect([s.size, s.limit, s.moves, s.status]).toEqual([SIZE, MOVE_LIMIT, 0, 'playing']);
22 expect(s.patches).toHaveLength(SIZE * SIZE);
23 expect(s.edges).toBe(2 * SIZE * (SIZE - 1));
24 });
25
26 test('every scramble is solvable within the limit, and never starts finished', () => {
27 for (let seed = 1; seed <= 100; seed++) {
28 let cur = start(seed);
29 expect(cur.matching).toBeLessThan(cur.edges);
30 const moves = solution(seed);
31 expect(moves.length).toBeLessThanOrEqual(MOVE_LIMIT);
32 for (const m of moves) {
33 if (cur.won) break;
34 const r = m[0] === 'r' ? rotate(cur, m[1]) : swap(cur, m[1], m[2]);
35 expect(r.ok).toBe(true);
36 cur = r.state;
37 }
38 expect(cur.won).toBe(true);
39 expect(cur.moves).toBeLessThanOrEqual(MOVE_LIMIT);
40 }
41 });
42
43 test('rotate turns a patch a quarter turn clockwise and counts one move', () => {
44 const s = start(1);
45 const before = s.patches[4];
46 const r = rotate(s, 4);
47 expect(r.ok).toBe(true);
48 expect(r.state.patches[4]).toEqual([before[3], before[0], before[1], before[2]]);
49 expect(r.state.moves).toBe(1);
50 expect(s.moves).toBe(0);
51 let q = s;
52 for (let i = 0; i < 4; i++) q = rotate(q, 4).state;
53 expect(q.patches[4]).toEqual(before);
54 expect(q.moves).toBe(4);
55 });
56
57 test('swap exchanges two patches and counts one move', () => {
58 const s = start(1);
59 const r = swap(s, 0, 8);
60 expect(r.ok).toBe(true);
61 expect([r.state.patches[0], r.state.patches[8]]).toEqual([s.patches[8], s.patches[0]]);
62 expect(r.state.moves).toBe(1);
63 });
64
65 test('a cell off the grid is refused and changes nothing', () => {
66 const s = start(1);
67 for (const bad of [-1, SIZE * SIZE, 1.5, NaN, '2', undefined]) {
68 for (const r of [rotate(s, bad), swap(s, 0, bad), swap(s, bad, 0)]) {
69 expect([r.ok, r.why]).toEqual([false, 'bad-cell']);
70 expect(r.state).toBe(s);
71 }
72 }
73 expect(swap(s, 2, 2).ok).toBe(false);
74 expect(s.moves).toBe(0);
75 });
76
77 test('matches reports each shared edge, matching when the touching stitches are equal', () => {
78 const s = { ...start(5), patches: sewn(5) };
79 expect(matches(s)).toHaveLength(s.edges);
80 expect(matches(s).every(m => m.ok)).toBe(true);
81 const t = { ...s, patches: s.patches.slice() };
82 t.patches[0] = [0, 1, 0, 0]; t.patches[1] = [0, 0, 0, 2];
83 expect(matches(t).find(e => e.a === 0 && e.b === 1).ok).toBe(false);
84 t.patches[1] = [0, 0, 0, 1];
85 expect(matches(t).find(e => e.a === 0 && e.b === 1).ok).toBe(true);
86 t.patches[3] = [0, 0, 0, 0]; t.patches[0] = [0, 1, 3, 0];
87 expect(matches(t).find(e => e.a === 0 && e.b === 3).ok).toBe(false);
88 });
89
90 test('a move that raises the matching edges scores, and one that does not scores nothing', () => {
91 const flat = { ...start(1), patches: Array.from({ length: 9 }, () => [0, 0, 0, 0]) };
92 flat.patches[0] = [1, 1, 1, 1];
93 flat.matching = ok(flat);
94 const quiet = swap(flat, 1, 2);
95 expect(quiet.state.matching).toBe(flat.matching);
96 expect([quiet.state.score, quiet.event]).toEqual([0, 'moved']);
97 const down = rotate(flat, 4);
98 expect(down.state.score).toBe(0);
99 const s = nearly(5, 4, 0);
100 const up = [1, 2, 3].map(k => { let q = s; for (let i = 0; i < k; i++) q = rotate(q, 4).state; return q; });
101 expect(up.some(q => q.score >= GAIN_SCORE)).toBe(true);
102 });
103
104 test('finishing under the limit scores a bonus for each move left, and the win line says so', () => {
105 let q = nearly(9, 0, 10);
106 let n = 0;
107 while (!q.won) { q = rotate(q, 0).state; n++; }
108 expect(n).toBeGreaterThan(0);
109 expect(q.status).toBe('over');
110 expect(q.moves).toBe(10 + n);
111 const left = MOVE_LIMIT - q.moves;
112 expect(q.score).toBeGreaterThanOrEqual(left * LEFT_BONUS);
113 expect(q.line).toBe(`Quilt finished: ${q.score} points, ${left} moves to spare`);
114 expect(rotate(q, 0)).toMatchObject({ ok: false, why: 'over' });
115 });
116
117 test('the bonus is per move left: an earlier finish scores more', () => {
118 const finish = moves => { let q = nearly(9, 0, moves); while (!q.won) q = rotate(q, 0).state; return q; };
119 const early = finish(0), late = finish(8);
120 expect(early.score - late.score).toBe(8 * LEFT_BONUS);
121 });
122
123 test('reaching the move limit before the quilt is finished loses, with a loss line', () => {
124 const q = { ...start(2), moves: MOVE_LIMIT - 1 };
125 const r = rotate(q, 0);
126 expect(r.state.won).toBe(false);
127 expect(r.state.status).toBe('over');
128 expect(r.event).toBe('lost');
129 expect(r.state.line).toBe(`Out of moves: ${r.state.matching} of ${r.state.edges} edges match, ${r.state.score} points`);
130 expect(swap(r.state, 0, 1)).toMatchObject({ ok: false, why: 'over' });
131 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs