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

Migrated from github.com/amirmushichge/pixel-plays

Clock Mender rules: a tested `clock-mender/gears.js` where you set gears on pegs to link the winding key to the clock hands within par, from plain data, in a two-file pull with a test file that runs in under a second #312

Merged opened this

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

Merged

torque/pixel-plays:torque/293-clock-mender-rules-a-tested-clock-mender → main 1 commit fork 1 thread · 1 unresolved

  • Merged. torque/293-clock-mender-rules-a-tested-clock-mender was merged into main as 829fd74.

Review

Sign in to review this change.
2 files changed +287 −0
clock-mender/gears.js added +143
@@ -0,0 +1,143 @@
1 'use strict';
2 // The Clock Mender rules: set gears on the pegs of a stopped clock's back plate so that turning the winding key
3 // turns the hands the right way round. Plain data in, plain data out, no DOM, no timers, no randomness. A rejected
4 // call returns the very same state and says why. There is no loss: restart is always allowed.
5 //
6 // Geometry (pegs sit on an integer grid, x to the right, y down, a peg is named "x,y"):
7 // A gear of size s has pitch radius s pegs, so its teeth reach exactly s pegs from its own peg.
8 // Gears at pegs P and Q of sizes a and b, with d² = (Px−Qx)² + (Py−Qy)²:
9 // d² < (a+b)² the gears overlap (refused when placing)
10 // d² == (a+b)² the teeth touch: the gears MESH
11 // d² > (a+b)² they do not touch
12 // Comparing squares keeps everything in exact integers (no square roots, no rounding). So a size-1 gear reaches
13 // the four pegs 2 away along a row or column; sizes 1 and 2 reach 3 away; sizes 1,2,3 also reach the 3-4-5 pegs.
14 // Direction: a meshed pair turns opposite ways (external gears). From the key (turning clockwise) directions
15 // alternate along every mesh; the arbor therefore turns clockwise when an even number of meshes separate it from
16 // the key and anticlockwise when odd. A loop with an odd number of gears would need a gear to turn both ways at
17 // once, so it jams the whole train.
18 (function (root) {
19 const KEY_SIZE = 1; // the winding key and the hands' arbor are fixed gears of this size
20 const KEY_DIR = 'cw'; // the key is wound clockwise
21 const DIRS = ['cw', 'ccw'];
22
23 // Hand-made levels. `key`, `arbor`: pegs; `blocked`: pegs that take no gear; `tray`: gear sizes available;
24 // `want`: direction the hands must turn; `par`: gears used by the stated `solution` ([peg, size] pairs).
25 const LEVELS = [
26 { name: 'Straight run', w: 7, h: 2, key: '0,0', arbor: '6,0', blocked: [], tray: [1, 1], want: 'ccw', par: 2,
27 solution: [['2,0', 1], ['4,0', 1]] },
28 { name: 'Big wheel', w: 7, h: 2, key: '0,0', arbor: '6,0', blocked: [], tray: [1, 2, 1], want: 'cw', par: 1,
29 solution: [['3,0', 2]] },
30 { name: 'Round the post', w: 7, h: 3, key: '0,0', arbor: '6,0', blocked: ['3,0'], tray: [2, 1, 1], want: 'ccw', par: 2,
31 solution: [['2,0', 1], ['4,0', 1]] },
32 { name: 'Square corner', w: 5, h: 5, key: '0,0', arbor: '3,3', blocked: ['1,1'], tray: [2, 1, 3], want: 'cw', par: 1,
33 solution: [['3,0', 2]] },
34 { name: 'Staircase', w: 5, h: 5, key: '0,0', arbor: '4,4', blocked: ['1,1', '3,3'], tray: [1, 1, 1, 1], want: 'cw', par: 3,
35 solution: [['2,0', 1], ['2,2', 1], ['4,2', 1]] },
36 { name: 'Three-gear trap', w: 7, h: 5, key: '0,0', arbor: '6,0', blocked: [], tray: [2, 3, 1, 1], want: 'cw', par: 1,
37 solution: [['3,0', 2]] },
38 { name: 'Long way round', w: 7, h: 5, key: '0,0', arbor: '6,4', blocked: ['3,0', '4,0', '3,2'], tray: [1, 1, 1, 1, 2, 3], want: 'ccw', par: 4,
39 solution: [['0,2', 1], ['2,2', 1], ['4,2', 1], ['6,2', 1]] },
40 ];
41
42 const PEG = /^(0|[1-9][0-9]{0,2}),(0|[1-9][0-9]{0,2})$/;
43 const parse = peg => { const m = typeof peg === 'string' && PEG.exec(peg); return m ? [+m[1], +m[2]] : null; };
44 const d2 = (p, q) => { const a = parse(p), b = parse(q); return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2; };
45 const reject = (state, why) => ({ ok: false, state, why });
46 const opposite = d => (d === 'cw' ? 'ccw' : 'cw');
47
48 // meshes(pegA, sizeA, pegB, sizeB) -> true when the teeth touch exactly (d² == (a+b)²)
49 const meshes = (p, a, q, b) => d2(p, q) === (a + b) ** 2;
50 // overlaps(...) -> true when the gears would collide (d² < (a+b)²)
51 const overlaps = (p, a, q, b) => d2(p, q) < (a + b) ** 2;
52
53 // fixedGears(level) -> { peg: size } for the key and the arbor
54 const fixed = lv => ({ [lv.key]: KEY_SIZE, [lv.arbor]: KEY_SIZE });
55
56 // drive(state) -> { turning: { peg: dir }, jammed, jam: [pegs], arbor: dir|null, solved }
57 // Breadth-first from the key, giving each meshed gear the opposite direction to the gear that reached it. When a
58 // mesh joins two gears already turning the same way, the train is jammed and nothing turns.
59 function drive(state) {
60 const lv = state.level;
61 const all = { ...fixed(lv), ...state.gears };
62 const pegs = Object.keys(all);
63 const dir = { [lv.key]: KEY_DIR };
64 const queue = [lv.key];
65 const jam = [];
66 for (let i = 0; i < queue.length; i++) {

Only gears reachable from the key are checked for jams; an unreachable odd loop is silently ignored. Fine for 'nothing jammed in the train', but pin it with a test.

67 const p = queue[i];
68 for (const q of pegs) {
69 if (q === p || !meshes(p, all[p], q, all[q])) continue;
70 if (!(q in dir)) { dir[q] = opposite(dir[p]); queue.push(q); }
71 else if (dir[q] === dir[p]) jam.push([p, q].sort().join(' '));
72 }
73 }
74 if (jam.length) return { turning: {}, jammed: true, jam: [...new Set(jam)].sort(), arbor: null, solved: false };
75 const arbor = dir[lv.arbor] || null;
76 return { turning: dir, jammed: false, jam: [], arbor, solved: arbor === lv.want };
77 }
78
79 const dirName = d => (d === 'cw' ? 'clockwise' : 'anticlockwise');
80
81 // winLine(state) -> the win line, gears used against par
82 function winLine(state) {
83 const used = Object.keys(state.gears).length, par = state.level.par;
84 const vs = used === par ? 'on par' : used < par ? `${par - used} under par` : `${used - par} over par`;
85 return `You win: the hands turn ${dirName(state.level.want)} with ${used} ${used === 1 ? 'gear' : 'gears'}, par ${par} (${vs})`;
86 }
87
88 function describe(state) {
89 if (state.status === 'won') return winLine(state);
90 const d = drive(state), n = Object.keys(state.gears).length;
91 if (d.jammed) return `Jammed: ${d.jam.join(', ')} fight each other; ${n} placed, tray ${state.tray.length}`;
92 const hands = d.arbor ? `the hands turn ${dirName(d.arbor)}` : 'the hands are still';
93 return `${hands}, want ${dirName(state.level.want)}; ${n} placed, par ${state.level.par}, tray ${state.tray.length}`;
94 }
95
96 // settle(state) -> the state with status and line worked out from the gears
97 function settle(s) {
98 s.status = drive(s).solved ? 'won' : 'playing';
99 s.line = describe(s);
100 return s;
101 }
102
103 // start(level) -> a fresh board for LEVELS[level]; anything that is not a level number gives level 0
104 function start(level) {
105 const i = Number.isInteger(level) && level >= 0 && level < LEVELS.length ? level : 0;
106 const lv = LEVELS[i];
107 return settle({ levelIndex: i, level: lv, gears: {}, tray: [...lv.tray], status: 'playing', line: '' });
108 }
109
110 // restart(state) -> the same level from scratch; always allowed
111 const restart = state => start(state.levelIndex);
112
113 // place(state, peg, size) -> { ok, state, why }
114 function place(state, peg, size) {
115 if (state.status !== 'playing') return reject(state, 'game-over');
116 const lv = state.level, xy = parse(peg);
117 if (!xy || xy[0] >= lv.w || xy[1] >= lv.h) return reject(state, 'off-plate');
118 if (lv.blocked.includes(peg)) return reject(state, 'blocked');
119 if (peg in fixed(lv) || peg in state.gears) return reject(state, 'taken');
120 const at = state.tray.indexOf(size);
121 if (!Number.isInteger(size) || at < 0) return reject(state, 'not-in-tray');
122 const others = { ...fixed(lv), ...state.gears };
123 for (const q of Object.keys(others)) if (overlaps(peg, size, q, others[q])) return reject(state, 'overlap');
124 const tray = state.tray.filter((_, i) => i !== at);
125 return { ok: true, state: settle({ ...state, gears: { ...state.gears, [peg]: size }, tray }), why: '' };
126 }
127
128 // lift(state, peg) -> { ok, state, why }: the gear goes back to the tray
129 function lift(state, peg) {
130 if (state.status !== 'playing') return reject(state, 'game-over');
131 const lv = state.level, xy = parse(peg);
132 if (!xy || xy[0] >= lv.w || xy[1] >= lv.h) return reject(state, 'off-plate');
133 if (peg in fixed(lv)) return reject(state, 'fixed');
134 if (!(peg in state.gears)) return reject(state, 'empty');
135 const gears = { ...state.gears };
136 const size = gears[peg];
137 delete gears[peg];
138 return { ok: true, state: settle({ ...state, gears, tray: [...state.tray, size].sort((a, b) => a - b) }), why: '' };
139 }
140
141 const api = { KEY_SIZE, KEY_DIR, DIRS, LEVELS, start, restart, place, lift, drive, meshes, overlaps, describe, winLine };
142 if (typeof module !== 'undefined') module.exports = api; else root.ClockMender = api;
143 })(typeof window !== 'undefined' ? window : globalThis);
clock-mender/gears.test.mjs added +144
@@ -0,0 +1,144 @@
1 import { test, expect } from 'bun:test';
2 import { LEVELS, KEY_DIR, start, restart, place, lift, drive, meshes, overlaps, winLine } from './gears.js';
3
4 const put = (s, ...moves) => moves.reduce((st, [p, z]) => { const r = place(st, p, z); expect(r.why).toBe(''); return r.state; }, s);
5 // a board with the given gears set directly, for loops no level allows by hand
6 const board = (i, gears) => ({ ...start(i), gears });
7
8 test('there are at least six hand-made levels, each fully stated', () => {
9 expect(LEVELS.length).toBeGreaterThanOrEqual(6);
10 for (let i = 0; i < LEVELS.length; i++) {
11 const s = start(i), lv = s.level;
12 expect(lv.w).toBeGreaterThan(0); expect(lv.h).toBeGreaterThan(0);
13 expect(lv.key).toMatch(/^\d+,\d+$/); expect(lv.arbor).toMatch(/^\d+,\d+$/);
14 expect(['cw', 'ccw']).toContain(lv.want);
15 expect(lv.tray.length).toBeGreaterThan(0);
16 expect(lv.par).toBe(lv.solution.length);
17 expect(s.tray).toEqual(lv.tray); expect(s.status).toBe('playing');
18 }
19 });
20
21 test('mesh and overlap by hand: size 1 + 1 touch at 2 apart, 1 + 2 at 3, 2 + 3 at 5 (3-4-5)', () => {
22 expect(meshes('0,0', 1, '2,0', 1)).toBe(true);
23 expect(meshes('0,0', 1, '3,0', 2)).toBe(true);
24 expect(meshes('0,0', 2, '3,4', 3)).toBe(true); // 3² + 4² = 25 = (2+3)²
25 expect(meshes('0,0', 1, '3,0', 1)).toBe(false); // 9 > 4: a gap
26 expect(overlaps('0,0', 1, '1,0', 1)).toBe(true); // 1 < 4
27 expect(overlaps('0,0', 1, '2,0', 1)).toBe(false); // touching is not overlapping
28 });
29
30 test('each level: its stated solution solves it, within par, and the board is not solved before', () => {
31 for (let i = 0; i < LEVELS.length; i++) {
32 let s = start(i);
33 expect(drive(s).solved).toBe(false);
34 s = put(s, ...s.level.solution);
35 expect(s.status).toBe('won');
36 expect(drive(s).solved).toBe(true);
37 expect(Object.keys(s.gears).length).toBeLessThanOrEqual(s.level.par);
38 expect(s.line).toBe(winLine(s));
39 }
40 });
41
42 test('directions alternate along the mesh from the key', () => {
43 const s = put(start(0), ['2,0', 1]);
44 const d = drive(s);
45 expect(d.turning).toEqual({ '0,0': KEY_DIR, '2,0': 'ccw' });
46 expect(d.arbor).toBeNull(); // arbor not yet reached
47 const t = put(s, ['4,0', 1]);
48 expect(drive(t).turning).toEqual({ '0,0': 'cw', '2,0': 'ccw', '4,0': 'cw', '6,0': 'ccw' });
49 expect(drive(t).arbor).toBe('ccw');
50 });
51
52 test('a loop of an odd number of gears jams the whole train and solves nothing', () => {
53 // key size 1 at 0,0; 2 at 3,0; 3 at 0,4: all three pairs touch (3, 4 and 5 apart)
54 const s = board(5, { '3,0': 2, '0,4': 3 });
55 const d = drive(s);
56 expect(d.jammed).toBe(true);
57 expect(d.jam).toEqual(['0,4 3,0']);
58 expect(d.turning).toEqual({}); expect(d.arbor).toBeNull(); expect(d.solved).toBe(false);
59 // placing it through the rules reaches the same jam
60 const t = put(start(5), ['3,0', 2]);
61 expect(t.status).toBe('won');
62 const j = put(start(5), ['0,4', 3], ['3,0', 2]);
63 expect(drive(j).jammed).toBe(true);
64 expect(j.status).toBe('playing');
65 expect(j.line).toMatch(/^Jammed: 0,4 3,0/);
66 });
67
68 test('the wrong direction does not solve', () => {
69 const s = put(start(0), ['2,0', 1], ['4,0', 1]); // ccw wanted: solved
70 expect(s.status).toBe('won');
71 const lv = { ...start(0).level, want: 'cw' };
72 const w = { ...s, level: lv, status: 'playing' };
73 expect(drive(w).arbor).toBe('ccw');
74 expect(drive(w).solved).toBe(false);
75 });
76
77 test('place refuses with a reason and returns the same state', () => {
78 const s = put(start(2), ['2,0', 1]); // level 2 blocks 3,0
79 const cases = [
80 [s, '3,0', 1, 'blocked'],
81 [s, '2,0', 1, 'taken'],
82 [s, '0,0', 1, 'taken'], // the key's peg
83 [s, '6,0', 1, 'taken'], // the arbor's peg
84 [s, '4,2', 3, 'not-in-tray'],
85 [s, '4,2', 1.5, 'not-in-tray'],
86 [s, '4,2', '1', 'not-in-tray'],
87 [s, '2,1', 1, 'overlap'], // 1 from the gear at 2,0
88 [s, '1,0', 1, 'overlap'],
89 [s, '9,9', 1, 'off-plate'],
90 [s, 'nonsense', 1, 'off-plate'],
91 [s, '01,0', 1, 'off-plate'],
92 ];
93 for (const [st, peg, size, why] of cases) {
94 const r = place(st, peg, size);
95 expect([peg, size, r.ok, r.why]).toEqual([peg, size, false, why]);
96 expect(r.state).toBe(st);
97 }
98 const used = put(start(0), ['2,0', 1], ['4,0', 1]);
99 expect(used.status).toBe('won');
100 const r = place(used, '2,1', 1);
101 expect([r.ok, r.why, r.state]).toEqual([false, 'game-over', used]);
102 });
103
104 test('the tray: a size runs out, and lift returns the gear', () => {
105 let s = put(start(0), ['2,0', 1], ['4,0', 1]); // both size-1 gears used (and solved)
106 expect(s.tray).toEqual([]);
107 const l = lift(start(0), '2,0');
108 expect(l.why).toBe('empty');
109 let t = put(start(2), ['2,0', 1]);
110 expect(t.tray).toEqual([2, 1]);
111 const back = lift(t, '2,0');
112 expect(back.ok).toBe(true);
113 expect(back.state.tray).toEqual([1, 1, 2]);
114 expect(back.state.gears).toEqual({});
115 expect(t.gears).toEqual({ '2,0': 1 }); // the old state is untouched
116 const dup = place(back.state, '2,0', 1);
117 expect(dup.ok).toBe(true);
118 });
119
120 test('lift refuses the key, the arbor, an empty peg, a bad peg and a finished game', () => {
121 const s = put(start(2), ['2,0', 1]);
122 for (const [peg, why] of [['0,0', 'fixed'], ['6,0', 'fixed'], ['4,2', 'empty'], ['x', 'off-plate'], ['8,8', 'off-plate']]) {
123 const r = lift(s, peg);
124 expect([r.ok, r.why]).toEqual([false, why]);
125 expect(r.state).toBe(s);
126 }
127 const won = put(start(0), ['2,0', 1], ['4,0', 1]);
128 const r = lift(won, '2,0');
129 expect([r.ok, r.why, r.state]).toEqual([false, 'game-over', won]);
130 });
131
132 test('win line reports gears used against par; restart is always allowed; no loss', () => {
133 const on = put(start(0), ['2,0', 1], ['4,0', 1]);
134 expect(on.line).toBe('You win: the hands turn anticlockwise with 2 gears, par 2 (on par)');
135 expect(winLine({ ...on, gears: { '2,0': 1 } })).toContain('1 gear, par 2 (1 under par)');
136 expect(winLine({ ...on, gears: { a: 1, b: 1, c: 1 } })).toContain('3 gears, par 2 (1 over par)');
137 const fresh = restart(on);
138 expect(fresh).toEqual(start(0));
139 expect(restart(start(3))).toEqual(start(3));
140 const stuck = put(start(5), ['0,4', 3], ['3,0', 2]);
141 expect(restart(stuck).status).toBe('playing'); // a jam is never the end
142 expect(start(99)).toEqual(start(0));
143 expect(start('1')).toEqual(start(0));
144 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs