Public: anyone can read this; the crew can change it.
Migrated from github.com/amirmushichge/pixel-plays
Hedge Maze rules: a tested `hedge-maze/maze.js` that carves and walks a seeded maze from plain data #165
Check · Review · Land · Live done — Landed and live in production.
torque/pixel-plays:torque/150-hedge-maze-rules-a-tested-hedge-maze-maz → main 2 commits fork 3 threads · 3 unresolved
2 files
changed +300
−0
hedge-maze/maze.js added +118
| @@ -0,0 +1,118 @@ | ||
| 1 | 'use strict'; | |
| 2 | // The Hedge Maze rules: find the way through the hedge to the fountain before the gardener's bell; each solved maze | |
| 3 | // is a size larger. Plain data in, plain data out, no DOM, no timers, no Math.random: a maze comes from its seed. | |
| 4 | // step() and tick() return a new state and leave the one you gave them alone. | |
| 5 | // | |
| 6 | // A maze is w x h cells, cell (x, y) at index y * w + x, y growing southward. cells[i] is a bitmask of the sides of | |
| 7 | // that cell with no hedge: N=1, E=2, S=4, W=8. Carving is the randomised depth-first search (recursive backtracker), | |
| 8 | // which yields a spanning tree of the grid: every cell reachable and exactly w*h-1 passages, so one path between any two. | |
| 9 | // | |
| 10 | // Credits: the recursive-backtracker maze algorithm (randomised depth-first search) is a well-known classic; the | |
| 11 | // hedge maze is an old garden-game genre (Hampton Court's maze is the famous one); mulberry32 is by Tommy Ettinger. | |
| 12 | (function (root) { | |
| 13 | const N = 1, E = 2, S = 4, W = 8; | |
| 14 | const DIRS = { north: { bit: N, back: S, dx: 0, dy: -1 }, east: { bit: E, back: W, dx: 1, dy: 0 }, | |
| 15 | south: { bit: S, back: N, dx: 0, dy: 1 }, west: { bit: W, back: E, dx: -1, dy: 0 } }; | |
| 16 | const START_SIZE = 5, MAX_SIZE = 12; // the first maze is 5 x 5; each solved maze is one larger, up to 12 x 12 | |
| 17 | const TIME_LIMIT = 45; // seconds on the bell for each maze; the bell resets on every new maze | |
| 18 | const TARGET = 5; // mazes solved at or above this is a win | |
| 19 | ||
| 20 | const finite = v => (Number.isFinite(v) ? v : 0); | |
| 21 | // mulberry32 (Tommy Ettinger): a small seeded generator, returns a function giving repeatable numbers in [0, 1) | |
| 22 | function rng(seed) { | |
| 23 | let a = finite(seed) >>> 0; | |
| 24 | return () => { | |
| 25 | a = (a + 0x6D2B79F5) | 0; | |
| 26 | let t = Math.imul(a ^ (a >>> 15), 1 | a); | |
| 27 | t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; | |
| 28 | return ((t ^ (t >>> 14)) >>> 0) / 4294967296; | |
| 29 | }; | |
| 30 | } | |
| 31 | const clampSize = n => Math.min(MAX_SIZE, Math.max(2, Math.floor(finite(n)) || 2)); | |
| 32 | ||
| 33 | // a perfect maze for this seed and size: { w, h, cells } | |
| 34 | function carve(seed, w, h) { | |
| 35 | w = clampSize(w); h = clampSize(h === undefined ? w : h); | |
| 36 | const rand = rng(seed), cells = new Array(w * h).fill(0), seen = new Array(w * h).fill(false); | |
| 37 | const stack = [0]; seen[0] = true; | |
| 38 | while (stack.length) { | |
| 39 | const i = stack[stack.length - 1], x = i % w, y = (i - x) / w, open = []; | |
| 40 | for (const name of Object.keys(DIRS)) { | |
| 41 | const d = DIRS[name], nx = x + d.dx, ny = y + d.dy; | |
| 42 | if (nx >= 0 && ny >= 0 && nx < w && ny < h && !seen[ny * w + nx]) open.push(d); | |
| 43 | } | |
| 44 | if (!open.length) { stack.pop(); continue; } | |
| 45 | const d = open[Math.floor(rand() * open.length)], j = (y + d.dy) * w + x + d.dx; | |
| 46 | cells[i] |= d.bit; cells[j] |= d.back; seen[j] = true; stack.push(j); | |
| 47 | } | |
| 48 | return { w, h, cells }; | |
| 49 | } | |
| 50 | ||
| 51 | // the cell farthest from the entrance by passages: where the fountain stands | |
| 52 | function farthest(m) { | |
| 53 | const dist = new Array(m.cells.length).fill(-1), queue = [0]; | |
| 54 | dist[0] = 0; | |
outdated
|
||
| 55 | let last = 0; | |
| 56 | for (let q = 0; q < queue.length; q++) { | |
| 57 | const i = queue[q]; | |
| 58 | last = i; | |
| 59 | for (const name of Object.keys(DIRS)) { | |
| 60 | const d = DIRS[name]; | |
| 61 | if (!(m.cells[i] & d.bit)) continue; | |
| 62 | const j = i + d.dy * m.w + d.dx; | |
| 63 | if (dist[j] < 0) { dist[j] = dist[i] + 1; queue.push(j); } | |
| 64 | } | |
| 65 | } | |
| 66 | return last; | |
| 67 | } | |
| 68 | ||
| 69 | // the seed of the n-th maze of a game (n from 1): the game's seed mixed with n | |
| 70 | const mazeSeed = (seed, n) => (Math.imul(finite(seed) | 0, 2654435761) + Math.imul(n, 40503) + n) >>> 0; | |
| 71 | const sizeOf = n => Math.min(MAX_SIZE, START_SIZE + n - 1); | |
| 72 | ||
| 73 | function mazeFor(seed, n) { | |
| 74 | const size = sizeOf(n), maze = carve(mazeSeed(seed, n), size, size); | |
| 75 | return { maze, pos: 0, fountain: farthest(maze) }; | |
| 76 | } | |
outdated
This renders "1 mazes solved". Pluralise it ("1 maze solved") in both end lines, and add a test for the singular. |
||
| 77 | function describe(s) { | |
| 78 | const mazes = `${s.solved} ${s.solved === 1 ? 'maze' : 'mazes'} solved`; | |
| 79 | s.line = s.status === 'playing' ? `Maze ${s.solved + 1} of up to ${MAX_SIZE}x${MAX_SIZE}: ${Math.ceil(s.time)}s on the bell` | |
| 80 | : s.status === 'won' ? `The bell rings: ${mazes}, best ${s.best}. You win!` | |
| 81 | : `The bell rings: ${mazes}, best ${s.best}. Aim for ${TARGET}.`; | |
| 82 | return s; | |
| 83 | } | |
| 84 | // a new game; `best` is the best score from earlier games | |
| 85 | function newGame(seed = 1, best = 0) { | |
| 86 | seed = finite(seed) >>> 0; | |
| 87 | best = Math.max(0, Math.floor(finite(best))); | |
| 88 | return describe(Object.assign({ seed, solved: 0, best, time: TIME_LIMIT, limit: TIME_LIMIT, target: TARGET, | |
| 89 | status: 'playing', reason: '' }, mazeFor(seed, 1))); | |
| 90 | } | |
| 91 | ||
| 92 | // Move one cell. Returns { ok, why, state }; a refused move returns the very same state. | |
| 93 | function step(state, dir) { | |
| 94 | const d = DIRS[dir]; | |
| 95 | if (state.status !== 'playing') return { ok: false, why: 'over', state }; | |
| 96 | if (!Object.prototype.hasOwnProperty.call(DIRS, dir)) return { ok: false, why: 'bad-direction', state }; | |
| 97 | if (!(state.maze.cells[state.pos] & d.bit)) return { ok: false, why: 'hedge', state }; | |
| 98 | const pos = state.pos + d.dy * state.maze.w + d.dx; | |
| 99 | if (pos !== state.fountain) return { ok: true, why: '', state: describe(Object.assign({}, state, { pos })) }; | |
| 100 | const solved = state.solved + 1; | |
| 101 | const next = Object.assign({}, state, mazeFor(state.seed, solved + 1), | |
| 102 | { solved, best: Math.max(state.best, solved), time: state.limit }); | |
| 103 | return { ok: true, why: '', state: describe(next) }; | |
| 104 | } | |
| 105 | ||
| 106 | // Let dt seconds pass. When the time runs out the game ends: won at or above the target, lost below it. | |
| 107 | function tick(state, dt) { | |
| 108 | if (state.status !== 'playing') return state; | |
| 109 | dt = Math.max(0, finite(dt)); | |
| 110 | const time = state.time - dt; | |
| 111 | if (time > 0) return describe(Object.assign({}, state, { time })); | |
| 112 | const best = Math.max(state.best, state.solved); | |
| 113 | return describe(Object.assign({}, state, { time: 0, best, status: state.solved >= TARGET ? 'won' : 'lost' })); | |
| 114 | } | |
| 115 | ||
| 116 | const api = { N, E, S, W, DIRS, START_SIZE, MAX_SIZE, TIME_LIMIT, TARGET, carve, farthest, mazeSeed, sizeOf, newGame, step, tick }; | |
| 117 | if (typeof module !== 'undefined') module.exports = api; else root.HedgeMaze = api; | |
| 118 | })(typeof window !== 'undefined' ? window : globalThis); |
hedge-maze/maze.test.mjs added +182
| @@ -0,0 +1,182 @@ | ||
| 1 | import { test, expect } from 'bun:test'; | |
| 2 | import { DIRS, START_SIZE, MAX_SIZE, TIME_LIMIT, TARGET, carve, farthest, mazeSeed, sizeOf, newGame, step, tick } from './maze.js'; | |
| 3 | ||
| 4 | const names = Object.keys(DIRS); | |
| 5 | const reach = m => { | |
| 6 | const seen = new Set([0]), q = [0]; | |
| 7 | for (let k = 0; k < q.length; k++) for (const n of names) { | |
| 8 | const d = DIRS[n], i = q[k]; | |
| 9 | if (m.cells[i] & d.bit) { const j = i + d.dy * m.w + d.dx; if (!seen.has(j)) { seen.add(j); q.push(j); } } | |
| 10 | } | |
| 11 | return seen.size; | |
| 12 | }; | |
| 13 | const passages = m => m.cells.reduce((n, c) => n + [1, 2, 4, 8].filter(b => c & b).length, 0) / 2; | |
| 14 | // a direction that is open / hedged from the player's cell | |
| 15 | const open = s => names.find(n => s.maze.cells[s.pos] & DIRS[n].bit); | |
| 16 | const hedged = s => names.find(n => !(s.maze.cells[s.pos] & DIRS[n].bit)); | |
| 17 | // the directions that walk from the entrance to the fountain (depth-first over the tree) | |
| 18 | function route(s) { | |
| 19 | const { maze, fountain } = s, path = []; | |
| 20 | const go = (i, from) => { | |
| 21 | if (i === fountain) return true; | |
| 22 | for (const n of names) { | |
| 23 | const d = DIRS[n], j = i + d.dy * maze.w + d.dx; | |
| 24 | if (maze.cells[i] & d.bit && j !== from) { path.push(n); if (go(j, i)) return true; path.pop(); } | |
| 25 | } | |
| 26 | return false; | |
| 27 | }; | |
| 28 | go(s.pos, -1); | |
| 29 | return path; | |
| 30 | }; | |
| 31 | const solve = s => route(s).reduce((st, n) => { const r = step(st, n); expect(r.ok).toBe(true); return r.state; }, s); | |
| 32 | ||
| 33 | test('the same seed carves the same maze, other seeds differ', () => { | |
| 34 | expect(carve(7, 8, 8)).toEqual(carve(7, 8, 8)); | |
| 35 | expect(carve(7, 8, 8)).not.toEqual(carve(8, 8, 8)); | |
| 36 | }); | |
| 37 | ||
| 38 | test('a maze is perfect: every cell reachable and cells minus one passages', () => { | |
| 39 | for (const [seed, w, h] of [[1, 5, 5], [2, 8, 6], [99, 12, 12], [3, 2, 2]]) { | |
| 40 | const m = carve(seed, w, h); | |
| 41 | expect(m.cells).toHaveLength(w * h); | |
| 42 | expect(reach(m)).toBe(w * h); | |
| 43 | expect(passages(m)).toBe(w * h - 1); | |
| 44 | } | |
| 45 | }); | |
| 46 | ||
| 47 | test('the outer hedge is never open', () => { | |
| 48 | const m = carve(5, 6, 6); | |
| 49 | for (let x = 0; x < 6; x++) { expect(m.cells[x] & 1).toBe(0); expect(m.cells[30 + x] & 4).toBe(0); } | |
| 50 | for (let y = 0; y < 6; y++) { expect(m.cells[y * 6] & 8).toBe(0); expect(m.cells[y * 6 + 5] & 2).toBe(0); } | |
| 51 | }); | |
| 52 | ||
| 53 | test('a step through a hedge is refused and leaves the state as it was', () => { | |
| 54 | const s = newGame(1), dir = hedged(s); | |
| 55 | const r = step(s, dir); | |
| 56 | expect(r).toEqual({ ok: false, why: 'hedge', state: s }); | |
| 57 | expect(r.state).toBe(s); | |
| 58 | expect(step(s, 'up').why).toBe('bad-direction'); | |
| 59 | }); | |
| 60 | ||
| 61 | test('an open step moves one cell', () => { | |
| 62 | const s = newGame(1), r = step(s, open(s)); | |
| 63 | expect(r.ok).toBe(true); | |
| 64 | expect(r.state.pos).not.toBe(0); | |
| 65 | expect(s.pos).toBe(0); | |
| 66 | }); | |
| 67 | ||
| 68 | test('the fountain starts the next maze, one size larger', () => { | |
| 69 | let s = newGame(4); | |
| 70 | expect(s.maze.w).toBe(START_SIZE); | |
| 71 | s = solve(s); | |
| 72 | expect(s.solved).toBe(1); | |
| 73 | expect(s.maze.w).toBe(START_SIZE + 1); | |
| 74 | expect(s.maze.h).toBe(START_SIZE + 1); | |
| 75 | expect(s.pos).toBe(0); | |
| 76 | expect(s.time).toBe(TIME_LIMIT); | |
| 77 | expect(reach(s.maze)).toBe(s.maze.cells.length); | |
| 78 | }); | |
| 79 | ||
| 80 | test('mazes stop growing at the largest size', () => { | |
| 81 | let s = newGame(2); | |
| 82 | for (let i = 0; i < 12; i++) s = solve(s); | |
| 83 | expect(s.solved).toBe(12); | |
| 84 | expect(s.maze.w).toBe(MAX_SIZE); | |
| 85 | expect(s.maze.h).toBe(MAX_SIZE); | |
| 86 | }); | |
| 87 | ||
| 88 | test('the fountain is the cell farthest from the entrance', () => { | |
| 89 | const s = newGame(3); | |
| 90 | expect(s.fountain).toBe(farthest(s.maze)); | |
| 91 | expect(s.fountain).not.toBe(0); | |
| 92 | }); | |
| 93 | ||
| 94 | test('time counts down and, when it runs out, the game ends', () => { | |
| 95 | let s = newGame(1); | |
| 96 | s = tick(s, 10); | |
| 97 | expect(s.time).toBe(TIME_LIMIT - 10); | |
| 98 | expect(s.status).toBe('playing'); | |
| 99 | s = tick(s, TIME_LIMIT); | |
| 100 | expect(s.time).toBe(0); | |
| 101 | expect(s.status).not.toBe('playing'); | |
| 102 | expect(step(s, open(s)).ok).toBe(false); | |
| 103 | expect(tick(s, 5)).toBe(s); | |
| 104 | }); | |
| 105 | ||
| 106 | test('time is reset by each new maze', () => { | |
| 107 | let s = tick(newGame(1), 30); | |
| 108 | s = solve(s); | |
| 109 | expect(s.time).toBe(TIME_LIMIT); | |
| 110 | }); | |
| 111 | ||
| 112 | test('below the target is a loss, with mazes solved and the best', () => { | |
| 113 | let s = solve(newGame(1, 3)); | |
| 114 | s = tick(s, 1000); | |
| 115 | expect(s.status).toBe('lost'); | |
| 116 | expect(s.solved).toBe(1); | |
| 117 | expect(s.best).toBe(3); | |
| 118 | expect(s.line).toContain('1 maze solved'); | |
| 119 | expect(s.line).not.toContain('1 mazes'); | |
| 120 | expect(s.line).toContain('best 3'); | |
| 121 | }); | |
| 122 | ||
| 123 | test('at or above the target is a win, and the best is updated', () => { | |
| 124 | let s = newGame(1); | |
| 125 | for (let i = 0; i < TARGET; i++) s = solve(s); | |
| 126 | s = tick(s, 1000); | |
| 127 | expect(s.status).toBe('won'); | |
| 128 | expect(s.solved).toBe(TARGET); | |
| 129 | expect(s.best).toBe(TARGET); | |
| 130 | expect(s.line).toContain('You win'); | |
| 131 | }); | |
| 132 | ||
| 133 | test('a tick of nonsense does not move the bell', () => { | |
| 134 | const s = newGame(1); | |
| 135 | expect(tick(s, NaN).time).toBe(TIME_LIMIT); | |
| 136 | expect(tick(s, -5).time).toBe(TIME_LIMIT); | |
| 137 | }); | |
| 138 | ||
| 139 | test('two mazes solved reads in the plural', () => { | |
| 140 | const s = tick(solve(solve(newGame(1))), 1000); | |
| 141 | expect(s.line).toContain('2 mazes solved'); | |
| 142 | }); | |
| 143 | ||
| 144 | test('a finished game refuses moves with why "over"', () => { | |
| 145 | const s = tick(newGame(1), 1000); | |
| 146 | const r = step(s, 'north'); | |
| 147 | expect(r.ok).toBe(false); | |
| 148 | expect(r.why).toBe('over'); | |
| 149 | expect(r.state).toBe(s); | |
| 150 | }); | |
| 151 | ||
| 152 | test('inherited property names are not directions', () => { | |
| 153 | const s = newGame(1); | |
| 154 | for (const bad of ['constructor', '__proto__', 'toString', 'hasOwnProperty']) { | |
| 155 | const r = step(s, bad); | |
| 156 | expect(r.ok).toBe(false); | |
| 157 | expect(r.why).toBe('bad-direction'); | |
| 158 | expect(r.state).toBe(s); | |
| 159 | } | |
| 160 | }); | |
| 161 | ||
| 162 | test('sizeOf grows by one per maze and caps at MAX_SIZE', () => { | |
| 163 | expect(sizeOf(1)).toBe(START_SIZE); | |
| 164 | expect(sizeOf(2)).toBe(START_SIZE + 1); | |
| 165 | expect(sizeOf(1000)).toBe(MAX_SIZE); | |
| 166 | }); | |
| 167 | ||
| 168 | test('different mazes of a game get different seeds', () => { | |
| 169 | const seeds = new Set([1, 2, 3, 4, 5, 6].map(n => mazeSeed(7, n))); | |
| 170 | expect(seeds.size).toBe(6); | |
| 171 | expect(mazeSeed(7, 1)).not.toBe(mazeSeed(8, 1)); | |
| 172 | expect(mazeSeed(7, 1)).toBe(mazeSeed(7, 1)); | |
| 173 | }); | |
| 174 | ||
| 175 | test('best rises as soon as a maze is solved mid-game', () => { | |
| 176 | let s = newGame(1, 1); | |
| 177 | s = solve(s); | |
| 178 | expect(s.best).toBe(1); | |
| 179 | s = solve(s); | |
| 180 | expect(s.best).toBe(2); | |
| 181 | expect(s.status).toBe('playing'); | |
| 182 | }); |
new above
offline
Credit the original creators here: mulberry32 is by Tommy Ettinger, and the carving is the recursive backtracker, a well-known maze algorithm. Add the credit to the header comment too.