Public: anyone can read this; the crew can change it.
Migrated from github.com/amirmushichge/pixel-plays
Lock Keeper rules: a tested `lock-keeper/lock.js` that works boats through a flight of canal locks from plain data #154
Check · Review · Land · Live done — Landed and live in production.
torque/pixel-plays:torque/140-lock-keeper-rules-a-tested-lock-keeper-l → main 2 commits fork 3 threads · 3 unresolved
2 files
changed +285
−0
lock-keeper/lock.js added +149
| @@ -0,0 +1,149 @@ | ||
| 1 | 'use strict'; | |
| 2 | // The Lock Keeper rules: a flight of three canal locks, boats to bring through, up or down, in as few operations as you can. | |
| 3 | // Plain data in, plain data out, no DOM, no timers, no Math.random: the queue of boats comes from the seed. A rejected | |
| 4 | // operation returns the very same state and says why. The page draws what this decides. | |
| 5 | // | |
| 6 | // The canal is a row of seven places: pound 0 (the bottom), lock 0, pound 1, lock 1, pound 2, lock 2, pound 3 (the top), | |
| 7 | // at positions 0..6. Lock k sits between pound k and pound k+1; pound j lies at height j and a lock is 'low' (height k, | |
| 8 | // level with the pound below) or 'high' (height k+1, level with the pound above). | |
| 9 | (function (root) { | |
| 10 | const LOCKS = 3, TOP = 2 * LOCKS; // locks in the flight, and the position of the top pound | |
| 11 | const LOCK_ROOM = 1, POUND_ROOM = 2; // narrowboats a lock holds, and the middle pounds hold | |
| 12 | const ACTS = ['paddle-top', 'paddle-bottom', 'gate-top', 'gate-bottom', 'move']; | |
| 13 | const SEEDS = [1, 2, 3]; // the rounds shipped with the game | |
| 14 | const PARS = { 1: 36, 2: 60, 3: 60 }; // fewest operations that win each shipped seed (checked by shortest()) | |
| 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 height = (lock, level) => lock + (level === 'high' ? 1 : 0); | |
| 24 | const done = b => (b.dir === 'up' ? b.at === TOP : b.at === 0); | |
| 25 | const room = at => (at === 0 || at === TOP ? Infinity : at % 2 ? LOCK_ROOM : POUND_ROOM); | |
| 26 | const count = (s, at) => s.boats.filter(b => b.at === at).length; | |
| 27 | const copy = s => ({ | |
| 28 | seed: s.seed, ops: s.ops, status: s.status, reason: s.reason, par: s.par, line: s.line, | |
| 29 | locks: s.locks.map(l => Object.assign({}, l)), boats: s.boats.map(b => Object.assign({}, b)), | |
| 30 | }); | |
| 31 | ||
| 32 | // The queue for a seed: one boat waiting at each end and, for some seeds, a third, in a seeded order. Boat ids are the order they queued. | |
| 33 | function queue(seed) { | |
| 34 | seed = finite(seed) >>> 0; | |
| 35 | const extra = noise(seed, 0) < .5, up = 1 + (extra && noise(seed, 1) < .5 ? 1 : 0), down = 1 + (extra && up === 1 ? 1 : 0); | |
| 36 | const dirs = [...Array(up).fill('up'), ...Array(down).fill('down')]; | |
| 37 | for (let i = dirs.length - 1; i > 0; i--) { // Fisher-Yates on the seed's noise | |
| 38 | const j = Math.floor(noise(seed, 10 + i) * (i + 1)); | |
| 39 | [dirs[i], dirs[j]] = [dirs[j], dirs[i]]; | |
| 40 | } | |
| 41 | return dirs.map((dir, id) => ({ id, dir, at: dir === 'up' ? 0 : TOP })); | |
| 42 | } | |
| 43 | const freshLocks = () => Array.from({ length: LOCKS }, () => ({ level: 'low', gateTop: false, gateBottom: false, paddleTop: false, paddleBottom: false })); | |
| 44 | function newRound(seed = 1) { | |
| 45 | seed = finite(seed) >>> 0; | |
| 46 | return refresh({ seed, ops: 0, status: 'playing', reason: '', par: par(seed), locks: freshLocks(), boats: queue(seed), line: '' }); | |
| 47 | } | |
| 48 | const through = s => s.boats.filter(done).length; | |
| 49 | function refresh(s) { | |
| 50 | const against = s.par == null ? '' : ` (par ${s.par})`; | |
| 51 | s.line = s.status === 'won' ? `All ${s.boats.length} boats through in ${s.ops} operations${against}` | |
| 52 | : s.status === 'lost' ? 'Flooded: both paddles were open' | |
| 53 | : `${through(s)} of ${s.boats.length} boats through, ${s.ops} operations${against}`; | |
| 54 | return s; | |
| 55 | } | |
| 56 | ||
| 57 | // why a boat at `at` going `dir` cannot cross lock L's gate now, or '' when it can | |
| 58 | function blocked(s, L, b) { | |
| 59 | const lock = s.locks[L], pos = 2 * L + 1, entering = b.at !== pos; | |
| 60 | const gate = (b.dir === 'up') === entering ? lock.gateBottom : lock.gateTop; // up enters by the bottom and leaves by the top | |
| 61 | if (!gate) return 'gate-closed'; | |
| 62 | const to = b.at + (b.dir === 'up' ? 1 : -1); | |
| 63 | return count(s, to) >= room(to) ? 'no-room' : ''; | |
| 64 | } | |
| 65 | // the boats that stand to cross lock L: in it, or in a pound beside it heading in | |
| 66 | const candidates = (s, L) => s.boats.filter(b => | |
| 67 | b.at === 2 * L + 1 || (b.at === 2 * L && b.dir === 'up') || (b.at === 2 * L + 2 && b.dir === 'down')); | |
| 68 | ||
| 69 | // The water test of a gate: it opens only when the lock is level with the pound on that side. A paddle may not be drawn | |
| 70 | // while the gate on the far side stands open, or the pound would run through the lock. | |
| 71 | function check(s, L, act) { | |
| 72 | const lock = s.locks[L]; | |
| 73 | if (act === 'gate-top' || act === 'gate-bottom') { | |
| 74 | const top = act === 'gate-top', open = top ? lock.gateTop : lock.gateBottom; | |
| 75 | if (open) return ''; // closing is always allowed | |
| 76 | return height(L, lock.level) === (top ? L + 1 : L) ? '' : 'uneven-water'; | |
| 77 | } | |
| 78 | if (act === 'paddle-top' || act === 'paddle-bottom') { | |
| 79 | const top = act === 'paddle-top', open = top ? lock.paddleTop : lock.paddleBottom; | |
| 80 | if (open) return ''; | |
| 81 | return (top ? lock.gateBottom : lock.gateTop) ? 'gate-open' : ''; | |
| 82 | } | |
| 83 | return ''; | |
| 84 | } | |
| 85 | ||
| 86 | // Apply one operation. Returns { state, ok, why, events }; on refusal state is the same object, unchanged. | |
| 87 | function apply(s, op) { | |
| 88 | const refuse = why => ({ state: s, ok: false, why, events: [] }); | |
| 89 | if (s.status !== 'playing') return refuse('round-over'); | |
| 90 | if (!op || !Number.isInteger(op.lock) || op.lock < 0 || op.lock >= LOCKS) return refuse('no-such-lock'); | |
| 91 | if (!ACTS.includes(op.act)) return refuse('no-such-act'); | |
| 92 | const L = op.lock, events = []; | |
| 93 | let n = copy(s), lock = n.locks[L]; | |
| 94 | if (op.act === 'move') { | |
| 95 | let why = 'no-boat'; | |
| 96 | const pick = candidates(s, L).find(b => { | |
| 97 | const r = b.at === 2 * L + 1 ? '' : count(s, 2 * L + 1) >= LOCK_ROOM ? 'lock-full' : ''; | |
| 98 | const w = r || blocked(s, L, b); | |
| 99 | if (w && why === 'no-boat') why = w; | |
| 100 | return !w; | |
| 101 | }); | |
| 102 | if (!pick) return refuse(why); | |
| 103 | const b = n.boats.find(x => x.id === pick.id); | |
| 104 | b.at += b.dir === 'up' ? 1 : -1; | |
| 105 | events.push({ type: 'move', boat: b.id, lock: L, at: b.at }); | |
| 106 | } else { | |
| 107 | const why = check(s, L, op.act); | |
| 108 | if (why) return refuse(why); | |
| 109 | const key = { 'paddle-top': 'paddleTop', 'paddle-bottom': 'paddleBottom', 'gate-top': 'gateTop', 'gate-bottom': 'gateBottom' }[op.act]; | |
| 110 | lock[key] = !lock[key]; | |
| 111 | events.push({ type: lock[key] ? 'open' : 'close', lock: L, act: op.act }); | |
| 112 | if (lock[key] && op.act === 'paddle-top') lock.level = 'high'; // the upper pound fills the lock | |
| 113 | if (lock[key] && op.act === 'paddle-bottom') lock.level = 'low'; // the lock empties to the lower pound | |
| 114 | if (lock.paddleTop && lock.paddleBottom) { n.status = 'lost'; n.reason = 'flood'; events.push({ type: 'flood', lock: L }); } | |
| 115 | } | |
| 116 | n.ops++; | |
| 117 | if (n.status === 'playing' && n.boats.every(done)) { n.status = 'won'; events.push({ type: 'won', ops: n.ops, par: n.par }); } | |
| 118 | return { state: refresh(n), ok: true, why: '', events }; | |
| 119 | } | |
| 120 | ||
| 121 | // ---- par: breadth-first search for the fewest operations that win from a state (never through a flood) ---- | |
| 122 | const keyOf = s => s.locks.map(l => (l.level === 'high' ? 1 : 0) | l.gateTop << 1 | l.gateBottom << 2 | l.paddleTop << 3 | l.paddleBottom << 4).join(',') | |
| 123 | + '|' + s.boats.map(b => b.at).join(''); | |
| 124 | function shortest(s, limit = 80) { | |
| 125 | if (typeof s === 'number') s = newRound(s); | |
| 126 | const ops = []; | |
| 127 | for (let L = 0; L < LOCKS; L++) for (const act of ACTS) ops.push({ lock: L, act }); | |
| 128 | let frontier = [s], seen = new Set([keyOf(s)]); | |
| 129 | for (let d = 0; d <= limit && frontier.length; d++) { | |
| 130 | const next = []; | |
| 131 | for (const st of frontier) { | |
| 132 | if (st.boats.every(done)) return d; | |
| 133 | for (const op of ops) { | |
| 134 | const r = apply(st, op); | |
| 135 | if (!r.ok || r.state.status === 'lost') continue; | |
| 136 | const k = keyOf(r.state); | |
| 137 | if (!seen.has(k)) { seen.add(k); next.push(r.state); } | |
| 138 | } | |
| 139 | } | |
| 140 | frontier = next; | |
| 141 | } | |
| 142 | return null; | |
| 143 | } | |
| 144 | // the stated par of a seed: the shipped table, or null. O(1): shortest() is the explicit, slow way to find one. | |
| 145 | const par = seed => PARS[finite(seed) >>> 0] ?? null; | |
| 146 | ||
outdated
|
||
| 147 | const api = { LOCKS, TOP, LOCK_ROOM, POUND_ROOM, ACTS, SEEDS, PARS, queue, newRound, apply, shortest, par }; | |
| 148 | if (typeof module !== 'undefined') module.exports = api; else root.LockKeeper = api; | |
| 149 | })(typeof window !== 'undefined' ? window : globalThis); |
lock-keeper/lock.test.mjs added +136
| @@ -0,0 +1,136 @@ | ||
| 1 | import { test, expect } from 'bun:test'; | |
| 2 | import { LOCKS, TOP, SEEDS, PARS, queue, newRound, apply, shortest, par } from './lock.js'; | |
| 3 | ||
| 4 | const op = (lock, act) => ({ lock, act }); | |
| 5 | // apply a list of [lock, act] pairs, expecting each to be accepted | |
| 6 | const run = (s, ops) => ops.reduce((st, [l, a]) => { const r = apply(st, op(l, a)); expect([l, a, r.why]).toEqual([l, a, '']); return r.state; }, s); | |
| 7 | // a round with just these boats (plain data, so it can be built by hand) | |
| 8 | const withBoats = (boats, seed = 1) => Object.assign(newRound(seed), { boats }); | |
| 9 | const up = (lock, a) => [[lock, 'gate-bottom'], [lock, 'move'], [lock, 'gate-bottom'], [lock, 'paddle-top'], [lock, 'gate-top'], [lock, 'move']].slice(...(a || [])); | |
| 10 | ||
| 11 | test('a round starts with every lock low, gates and paddles shut, nobody through', () => { | |
| 12 | const s = newRound(1); | |
| 13 | expect(s.locks).toHaveLength(LOCKS); | |
| 14 | for (const l of s.locks) expect(l).toEqual({ level: 'low', gateTop: false, gateBottom: false, paddleTop: false, paddleBottom: false }); | |
| 15 | expect(s.status).toBe('playing'); | |
| 16 | expect(s.ops).toBe(0); | |
| 17 | }); | |
| 18 | ||
| 19 | test('a gate is refused on uneven water and the state is left unchanged', () => { | |
| 20 | const s = newRound(1); | |
| 21 | const r = apply(s, op(0, 'gate-top')); // lock 0 is low, the pound above is higher | |
| 22 | expect(r.ok).toBe(false); | |
| 23 | expect(r.why).toBe('uneven-water'); | |
| 24 | expect(r.state).toBe(s); | |
| 25 | expect(s.ops).toBe(0); | |
| 26 | expect(apply(s, op(0, 'gate-bottom')).ok).toBe(true); // level with the pound below | |
| 27 | }); | |
| 28 | ||
| 29 | test('the top paddle fills the lock and the bottom paddle empties it, and each gate then opens', () => { | |
| 30 | let s = run(newRound(1), [[1, 'paddle-top']]); | |
| 31 | expect(s.locks[1].level).toBe('high'); | |
| 32 | expect(apply(s, op(1, 'gate-bottom')).why).toBe('uneven-water'); | |
| 33 | s = run(s, [[1, 'gate-top']]); | |
| 34 | expect(s.locks[1].gateTop).toBe(true); | |
| 35 | s = run(s, [[1, 'gate-top'], [1, 'paddle-top'], [1, 'paddle-bottom']]); | |
| 36 | expect(s.locks[1].level).toBe('low'); | |
| 37 | expect(apply(s, op(1, 'gate-top')).why).toBe('uneven-water'); | |
| 38 | expect(apply(s, op(1, 'gate-bottom')).ok).toBe(true); | |
| 39 | }); | |
| 40 | ||
| 41 | test('a paddle is refused while the gate on the far side stands open', () => { | |
| 42 | const s = run(newRound(1), [[0, 'gate-bottom']]); | |
| 43 | expect(apply(s, op(0, 'paddle-top')).why).toBe('gate-open'); | |
| 44 | const t = run(newRound(1), [[0, 'paddle-top'], [0, 'gate-top']]); | |
| 45 | expect(apply(t, op(0, 'paddle-bottom')).why).toBe('gate-open'); | |
| 46 | }); | |
| 47 | ||
| 48 | test('a boat moves only through an open gate into a lock or pound with room', () => { | |
| 49 | const boat = { id: 0, dir: 'up', at: 0 }; | |
| 50 | let s = withBoats([boat]); | |
| 51 | expect(apply(s, op(0, 'move')).why).toBe('gate-closed'); | |
| 52 | s = run(s, [[0, 'gate-bottom'], [0, 'move']]); | |
| 53 | expect(s.boats[0].at).toBe(1); | |
| 54 | expect(apply(s, op(0, 'move')).why).toBe('gate-closed'); // the top gate is shut | |
| 55 | expect(apply(withBoats([boat]), op(2, 'move')).why).toBe('no-boat'); | |
| 56 | // a lock holds one boat | |
| 57 | const two = withBoats([{ id: 0, dir: 'up', at: 1 }, { id: 1, dir: 'up', at: 0 }]); | |
| 58 | const r = apply(run(two, [[0, 'gate-bottom']]), op(0, 'move')); | |
| 59 | expect(r.ok).toBe(false); // the boat in the lock can't leave, the one outside can't enter | |
| 60 | // a middle pound holds two | |
| 61 | const full = withBoats([{ id: 0, dir: 'up', at: 1 }, { id: 1, dir: 'down', at: 2 }, { id: 2, dir: 'down', at: 2 }]); | |
| 62 | full.locks[0].level = 'high'; | |
| 63 | expect(apply(run(full, [[0, 'gate-top']]), op(0, 'move')).why).toBe('no-room'); | |
| 64 | }); | |
| 65 | ||
| 66 | test('a boat goes up a lock and a boat goes down it', () => { | |
| 67 | let s = withBoats([{ id: 0, dir: 'up', at: 0 }]); | |
| 68 | s = run(s, up(0)); | |
| 69 | expect(s.boats[0].at).toBe(2); | |
| 70 | expect(s.locks[0].level).toBe('high'); | |
| 71 | let d = withBoats([{ id: 0, dir: 'down', at: 2 }]); | |
| 72 | d.locks[0].level = 'high'; | |
| 73 | d = run(d, [[0, 'gate-top'], [0, 'move'], [0, 'gate-top'], [0, 'paddle-bottom'], [0, 'gate-bottom'], [0, 'move']]); | |
| 74 | expect(d.boats[0].at).toBe(0); | |
| 75 | expect(d.status).toBe('won'); | |
| 76 | }); | |
| 77 | ||
| 78 | test('opening both paddles of one lock floods it and loses the round', () => { | |
| 79 | let s = run(newRound(1), [[2, 'paddle-top']]); | |
| 80 | const r = apply(s, op(2, 'paddle-bottom')); | |
| 81 | expect(r.ok).toBe(true); | |
| 82 | expect(r.state.status).toBe('lost'); | |
| 83 | expect(r.state.reason).toBe('flood'); | |
| 84 | expect(r.events.some(e => e.type === 'flood')).toBe(true); | |
| 85 | expect(apply(r.state, op(0, 'gate-bottom')).why).toBe('round-over'); | |
| 86 | }); | |
| 87 | ||
| 88 | test('the round is won when every boat is through, reporting operations against par', () => { | |
| 89 | let s = withBoats([{ id: 0, dir: 'up', at: 5 }, { id: 1, dir: 'down', at: 0 }]); | |
| 90 | s.locks[2].level = 'high'; | |
| 91 | s = run(s, [[2, 'gate-top']]); | |
| 92 | expect(s.status).toBe('playing'); | |
| 93 | const r = apply(s, op(2, 'move')); | |
| 94 | expect(r.state.status).toBe('won'); | |
| 95 | expect(r.state.ops).toBe(2); | |
| 96 | expect(r.state.par).toBe(PARS[1]); | |
| 97 | expect(r.state.line).toContain('2 operations'); | |
| 98 | expect(r.state.boats[0].at).toBe(TOP); | |
| 99 | }); | |
| 100 | ||
| 101 | test('bad operations are refused, never thrown', () => { | |
| 102 | const s = newRound(1); | |
| 103 | for (const bad of [null, {}, op(3, 'move'), op(-1, 'move'), op(1.5, 'move'), op(0, 'eval'), { lock: '0', act: 'move' }]) expect(apply(s, bad).ok).toBe(false); | |
| 104 | }); | |
| 105 | ||
| 106 | test('the same seed gives the same queue, and seeds differ', () => { | |
| 107 | for (const seed of SEEDS) expect(queue(seed)).toEqual(queue(seed)); | |
| 108 | expect(newRound(7)).toEqual(newRound(7)); | |
| 109 | const shapes = new Set([1, 2, 3, 4, 5, 6, 7, 8].map(n => JSON.stringify(queue(n)))); | |
| 110 | expect(shapes.size).toBeGreaterThan(1); | |
|
||
| 111 | for (const n of [1, 2, 3, 4, 5, 6, 7, 8]) { | |
| 112 | const q = queue(n); | |
| 113 | expect(q.length).toBeGreaterThanOrEqual(2); | |
| 114 | expect(q.some(b => b.dir === 'up')).toBe(true); | |
| 115 | expect(q.some(b => b.dir === 'down')).toBe(true); | |
| 116 | expect(q.filter(b => b.dir === 'up').every(b => b.at === 0)).toBe(true); | |
| 117 | expect(q.filter(b => b.dir === 'down').every(b => b.at === TOP)).toBe(true); | |
| 118 | } | |
| 119 | }); | |
| 120 | ||
| 121 | test('an unshipped seed starts at once, with par null, and its line never prints one', () => { | |
| 122 | const t0 = performance.now(); | |
| 123 | const s = newRound(7); | |
| 124 | expect(performance.now() - t0).toBeLessThan(50); | |
| 125 | expect(s.par).toBeNull(); | |
| 126 | expect(s.line).not.toContain('par'); | |
| 127 | expect(typeof newRound(1).par).toBe('number'); | |
| 128 | expect(newRound(1).line).toContain('par 36'); | |
| 129 | }); | |
| 130 | ||
| 131 | test('par is reachable, and no fewer operations win, for every shipped seed', () => { | |
| 132 | for (const seed of SEEDS) { | |
| 133 | expect(par(seed)).toBe(PARS[seed]); | |
| 134 | expect(shortest(seed)).toBe(PARS[seed]); | |
| 135 | } | |
| 136 | }, 60000); |
new above
offline
par(seed)here runs the full BFS for unshipped seeds, sonewRoundblocks for seconds. Do not search at round start; use the table value ornull.