Public: anyone can read this; the crew can change it.
Migrated from github.com/amirmushichge/pixel-plays
Dry Stone Wall rules: a tested `stone-wall/wall.js` that lays stones in courses so no joint sits over another, from plain data, with a test file that runs in under a second #261
Check · Review · Land · Live done — Landed and live in production.
torque/pixel-plays:torque/240-dry-stone-wall-rules-a-tested-stone-wall → main 1 commit fork 1 thread · 1 unresolved
2 files
changed +275
−0
stone-wall/wall.js added +157
| @@ -0,0 +1,157 @@ | ||
| 1 | 'use strict'; | |
| 2 | // The Dry Stone Wall rules: build a field wall course by course from a pile of stones of different widths, so that no | |
| 3 | // joint (the gap between two stones) sits directly above a joint in the course below. | |
| 4 | // Plain data in, plain data out, no DOM, no timers, no Math.random: the pile comes from the seed. | |
| 5 | // A rejected call returns the very same state and says why. The page (not yet written) draws what this decides. | |
| 6 | // | |
| 7 | // Widths are in stone units. A stone laid at offset o with width w covers o up to o + w; the joint after it is at | |
| 8 | // o + w, unless that is the wall width (the end of the wall is not a joint). Course 0 rests on the ground and may | |
| 9 | // have any joints. The pile is made by building a valid wall first and then shuffling its stones, so a way to | |
| 10 | // finish always exists. | |
| 11 | (function (root) { | |
| 12 | const WIDTH = 12; // wall width in stone units | |
| 13 | const COURSES = 5; // courses to build | |
| 14 | const MIN_STONE = 1; // narrowest stone in the pile | |
| 15 | const MAX_STONE = 4; // widest stone in the pile | |
| 16 | const STONE_SCORE = 10; // points for each stone laid | |
| 17 | const LONG_STONE = 2; // a course with no stone narrower than this earns the bonus | |
| 18 | const COURSE_BONUS = 25; // extra points for such a course | |
| 19 | ||
| 20 | const finite = v => (Number.isFinite(v) ? v : 0); | |
| 21 | // a seeded stream of numbers in [0, 1) (mulberry32) | |
| 22 | function stream(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 | ||
| 32 | // joints(widths) -> the offsets of the gaps between stones, the wall end excluded | |
| 33 | function joints(widths) { | |
| 34 | const out = []; | |
| 35 | let at = 0; | |
| 36 | for (const w of widths) { at += w; if (at < WIDTH) out.push(at); } | |
| 37 | return out; | |
| 38 | } | |
| 39 | ||
| 40 | // a random course of stone widths filling WIDTH exactly, in order along the wall | |
| 41 | function composition(rnd) { | |
| 42 | const out = []; | |
| 43 | let left = WIDTH; | |
| 44 | while (left > 0) { | |
| 45 | const hi = Math.min(MAX_STONE, left); | |
| 46 | let w = MIN_STONE + Math.floor(rnd() * (hi - MIN_STONE + 1)); | |
| 47 | if (left - w > 0 && left - w < MIN_STONE) w = left; // never leave a gap too small for a stone | |
| 48 | out.push(w); left -= w; | |
| 49 | } | |
| 50 | return out; | |
| 51 | } | |
| 52 | ||
| 53 | // pile(seed) -> stone widths, shuffled; they can fill COURSES courses with no joint over a joint | |
| 54 | function pile(seed) { | |
| 55 | const rnd = stream(seed); | |
| 56 | const all = []; | |
| 57 | let below = []; | |
| 58 | for (let c = 0; c < COURSES; c++) { | |
| 59 | let course, tries = 0; | |
| 60 | do { | |
| 61 | course = composition(rnd); | |
| 62 | tries++; | |
| 63 | } while (tries < 500 && joints(course).some(j => below.includes(j))); | |
| 64 | if (joints(course).some(j => below.includes(j))) { // fallback, always valid: two stones, joint off the last | |
| 65 | const j = below.includes(WIDTH / 2) ? WIDTH / 2 + 1 : WIDTH / 2; | |
| 66 | course = [j, WIDTH - j]; | |
| 67 | if (joints(course).some(x => below.includes(x))) course = [1, WIDTH - 1]; | |
| 68 | } | |
| 69 | all.push(...course); below = joints(course); | |
| 70 | } | |
| 71 | for (let i = all.length - 1; i > 0; i--) { | |
| 72 | const j = Math.floor(rnd() * (i + 1)); | |
| 73 | [all[i], all[j]] = [all[j], all[i]]; | |
| 74 | } | |
| 75 | return all; | |
| 76 | } | |
| 77 | ||
| 78 | // refresh the derived fields: offset, the joints the next stone must avoid, the line, and the win or loss | |
| 79 | function refresh(s) { | |
| 80 | s.offset = s.current.reduce((a, st) => a + st.width, 0); | |
| 81 | s.below = s.built.length ? joints(s.built[s.built.length - 1].map(st => st.width)) : []; | |
| 82 | s.placeable = s.pile.map((_, i) => check(s, i) === '' ? i : -1).filter(i => i >= 0); | |
| 83 | if (s.built.length === s.courses) s.status = 'won'; | |
| 84 | else if (s.placeable.length === 0) s.status = 'lost'; | |
| 85 | else s.status = 'playing'; | |
| 86 | s.line = s.status === 'won' | |
| 87 | ? `Wall built, you win: ${s.courses} courses, ${s.score} points` | |
| 88 | : s.status === 'lost' | |
| 89 | ? `No stone fits, you lose: ${s.built.length} of ${s.courses} courses, ${s.score} points` | |
| 90 | : `Course ${s.built.length + 1} of ${s.courses}, ${s.offset} of ${s.width} filled, ${s.score} points`; | |
| 91 | return s; | |
| 92 | } | |
| 93 | ||
| 94 | // '' when the stone can be laid now, otherwise why not | |
| 95 | function check(s, i) { | |
| 96 | if (!Number.isInteger(i) || i < 0 || i >= s.pile.length) return 'bad-stone'; | |
| 97 | if (s.laid.includes(i)) return 'laid'; | |
| 98 | const end = s.offset + s.pile[i]; | |
| 99 | if (end > s.width) return 'overrun'; | |
| 100 | if (end < s.width && s.below.includes(end)) return 'joint-over-joint'; | |
| 101 | return ''; | |
| 102 | } | |
| 103 | ||
| 104 | const start = (seed = 1) => { | |
| 105 | const sd = finite(seed) >>> 0; | |
| 106 | return refresh({ | |
| 107 | seed: sd, width: WIDTH, courses: COURSES, pile: pile(sd), stoneScore: STONE_SCORE, longStone: LONG_STONE, | |
| 108 | courseBonus: COURSE_BONUS, laid: [], current: [], built: [], offset: 0, below: [], placeable: [], | |
| 109 | score: 0, status: 'playing', line: '', | |
| 110 | }); | |
| 111 | }; | |
| 112 | ||
| 113 | const copy = s => Object.assign({}, s, { | |
| 114 | laid: s.laid.slice(), current: s.current.slice(), built: s.built.slice(), | |
| 115 | }); | |
| 116 | const refuse = (s, why) => ({ ok: false, why, event: '', state: s }); | |
| 117 | ||
| 118 | // place(state, stoneIndex) -> { ok, why, event, state }: lays pile[stoneIndex] at the next free position of the | |
| 119 | // current course. event is 'laid', 'course' (it completed a course), 'course-bonus' (and earned the bonus) or | |
| 120 | // 'won' (it completed the last course). Refused: 'over', 'bad-stone', 'laid', 'overrun', 'joint-over-joint'. | |
| 121 | function place(s, i) { | |
| 122 | if (s.status !== 'playing') return refuse(s, 'over'); | |
| 123 | const why = check(s, i); | |
| 124 | if (why) return refuse(s, why); | |
| 125 | const n = copy(s); | |
| 126 | n.laid.push(i); | |
| 127 | n.current.push({ index: i, width: n.pile[i] }); | |
| 128 | n.score += n.stoneScore; | |
| 129 | let event = 'laid'; | |
| 130 | if (n.current.reduce((a, st) => a + st.width, 0) === n.width) { | |
| 131 | event = 'course'; | |
| 132 | if (n.current.every(st => st.width >= n.longStone)) { n.score += n.courseBonus; event = 'course-bonus'; } | |
| 133 | n.built.push(n.current); n.current = []; | |
| 134 | } | |
| 135 | refresh(n); | |
| 136 | if (n.status === 'won') event = 'won'; | |
| 137 | return { ok: true, why: '', event, state: n }; | |
| 138 | } | |
| 139 | ||
| 140 | // undo(state) -> { ok, why, event, state }: lifts the last stone of the current course and takes back its points. | |
| 141 | // Refused with 'nothing' when the current course is empty (finished courses stay) and 'over' once the wall is won. | |
| 142 | // A lost wall may be undone: that is the way out of a dead end. | |
| 143 | function undo(s) { | |
| 144 | if (s.status === 'won') return refuse(s, 'over'); | |
| 145 | if (!s.current.length) return refuse(s, 'nothing'); | |
| 146 | const n = copy(s); | |
| 147 | const st = n.current.pop(); | |
| 148 | n.laid = n.laid.filter(i => i !== st.index); | |
| 149 | n.score -= n.stoneScore; | |
| 150 | return { ok: true, why: '', event: 'undone', state: refresh(n) }; | |
| 151 | } | |
| 152 | ||
| 153 | const api = { | |
| 154 | WIDTH, COURSES, MIN_STONE, MAX_STONE, STONE_SCORE, LONG_STONE, COURSE_BONUS, pile, joints, settle: refresh, start, place, undo, | |
| 155 | }; | |
| 156 | if (typeof module !== 'undefined') module.exports = api; else root.StoneWall = api; | |
| 157 | })(typeof window !== 'undefined' ? window : globalThis); |
stone-wall/wall.test.mjs added +118
| @@ -0,0 +1,118 @@ | ||
| 1 | import { test, expect } from 'bun:test'; | |
| 2 | import { | |
| 3 | WIDTH, COURSES, MIN_STONE, MAX_STONE, STONE_SCORE, COURSE_BONUS, pile, joints, settle, start, place, undo, | |
| 4 | } from './wall.js'; | |
| 5 | ||
| 6 | // a state with a hand-written pile, so each rule is checked against a count done by hand | |
| 7 | const withPile = (widths, over = {}) => settle({ ...start(1), pile: widths, ...over }); | |
| 8 | const lay = (s, ...is) => is.reduce((st, i) => { const r = place(st, i); expect(r.ok).toBe(true); return r.state; }, s); | |
| 9 | ||
| 10 | test('the same seed gives the same pile, other seeds differ, and the stated sizes hold', () => { | |
| 11 | expect(start(7)).toEqual(start(7)); | |
| 12 | const seen = new Set(); | |
| 13 | for (let seed = 1; seed <= 20; seed++) seen.add(JSON.stringify(pile(seed))); | |
| 14 | expect(seen.size).toBeGreaterThan(10); | |
| 15 | const s = start(3); | |
| 16 | expect([s.width, s.courses]).toEqual([WIDTH, COURSES]); | |
| 17 | expect(s.pile.reduce((a, w) => a + w, 0)).toBe(WIDTH * COURSES); | |
| 18 | for (const w of s.pile) { expect(w).toBeGreaterThanOrEqual(MIN_STONE); expect(w).toBeLessThanOrEqual(MAX_STONE); } | |
| 19 | }); | |
| 20 | ||
| 21 | test('the pile can always build the wall: a depth-first search finds a way', () => { | |
| 22 | const solve = (s) => { | |
| 23 | if (s.status === 'won') return true; | |
| 24 | const tried = new Set(); // stones of one width are interchangeable | |
| 25 | for (const i of s.placeable) { | |
| 26 | if (tried.has(s.pile[i])) continue; | |
| 27 | tried.add(s.pile[i]); | |
| 28 | if (solve(place(s, i).state)) return true; | |
| 29 | } | |
| 30 | return false; | |
| 31 | }; | |
| 32 | for (let seed = 1; seed <= 5; seed++) expect(solve(start(seed))).toBe(true); | |
| 33 | }); | |
| 34 | ||
| 35 | test('a stone that overruns the wall width is refused and the state is unchanged', () => { | |
| 36 | let s = withPile([4, 4, 3, 5]); | |
| 37 | s = lay(s, 0, 1); // 8 filled | |
| 38 | const r = place(s, 3); // 8 + 5 = 13 > 12 | |
| 39 | expect([r.ok, r.why, r.state]).toEqual([false, 'overrun', s]); | |
| 40 | }); | |
| 41 | ||
| 42 | test('a stone that puts a joint over a joint of the course below is refused', () => { | |
| 43 | let s = withPile([6, 6, 3, 3, 6]); | |
| 44 | s = lay(s, 0, 1); // course 0 has a joint at 6 | |
| 45 | expect(s.built).toHaveLength(1); | |
| 46 | expect(s.below).toEqual([6]); | |
| 47 | const r = place(s, 2); // 3 ends at 3, fine | |
| 48 | expect(r.ok).toBe(true); | |
| 49 | const r2 = place(r.state, 3); // 3 + 3 = 6, a joint over the joint at 6 | |
| 50 | expect([r2.ok, r2.why]).toEqual([false, 'joint-over-joint']); | |
| 51 | expect(r2.state).toBe(r.state); | |
| 52 | }); | |
| 53 | ||
| 54 | test('a course completes when filled exactly, the next begins, and the end of the wall is not a joint', () => { | |
| 55 | let s = withPile([5, 7, 3, 9]); | |
| 56 | const a = place(s, 0); | |
| 57 | expect([a.event, a.state.offset, a.state.built.length]).toEqual(['laid', 5, 0]); | |
| 58 | const b = place(a.state, 1); | |
| 59 | expect([b.event, b.state.offset, b.state.built.length, b.state.current]).toEqual(['course-bonus', 0, 1, []]); | |
| 60 | expect(joints([5, 7])).toEqual([5]); | |
| 61 | expect(b.state.below).toEqual([5]); | |
| 62 | const c = place(b.state, 2); // ends at 3, allowed | |
| 63 | expect(c.ok).toBe(true); | |
| 64 | const d = place(c.state, 3); // 3 + 9 = 12, the wall end | |
| 65 | expect([d.ok, d.state.built.length]).toEqual([true, 2]); | |
| 66 | }); | |
| 67 | ||
| 68 | test('undo lifts the last stone of the current course and takes its points back', () => { | |
| 69 | let s = withPile([5, 7, 3]); | |
| 70 | expect(undo(s)).toMatchObject({ ok: false, why: 'nothing' }); | |
| 71 | s = lay(s, 0); | |
| 72 | const u = undo(s); | |
| 73 | expect([u.ok, u.event, u.state.current, u.state.laid, u.state.score, u.state.offset]).toEqual([true, 'undone', [], [], 0, 0]); | |
| 74 | expect(place(u.state, 0).ok).toBe(true); // the stone is back in the pile | |
| 75 | const done = lay(s, 1); // course 0 finished | |
| 76 | expect(undo(done)).toMatchObject({ ok: false, why: 'nothing' }); // finished courses stay | |
| 77 | expect(place(s, 0)).toMatchObject({ ok: false, why: 'laid' }); | |
| 78 | }); | |
| 79 | ||
| 80 | test('each stone scores and a course with no stone shorter than the limit earns the bonus', () => { | |
| 81 | let s = withPile([2, 10, 1, 11]); | |
| 82 | s = lay(s, 0); | |
| 83 | expect(s.score).toBe(STONE_SCORE); | |
| 84 | const r = place(s, 1); | |
| 85 | expect([r.event, r.state.score]).toEqual(['course-bonus', 2 * STONE_SCORE + COURSE_BONUS]); | |
| 86 | const t = lay(r.state, 2); // a stone of width 1, then 11: joint at 1, below has 2 | |
| 87 | const q = place(t, 3); | |
| 88 | expect([q.event, q.state.score]).toEqual(['course', 4 * STONE_SCORE + COURSE_BONUS]); // no bonus: it has a 1 | |
| 89 | }); | |
| 90 | ||
| 91 | test('the game is won when every course is built', () => { | |
| 92 | const w = withPile([12, 6, 6], { courses: 2 }); | |
| 93 | const a = place(w, 0); | |
| 94 | expect(a.state.status).toBe('playing'); | |
| 95 | const b = place(lay(a.state, 1), 2); | |
| 96 | expect(b.state.status).toBe('won'); | |
| 97 | expect(b.event).toBe('won'); | |
| 98 | expect(b.state.line).toContain('you win'); | |
| 99 | expect(place(b.state, 0)).toMatchObject({ ok: false, why: 'over' }); | |
| 100 | }); | |
| 101 | ||
| 102 | test('the game is lost when no stone left can be placed, and undo is the way out', () => { | |
| 103 | let s = withPile([6, 6, 3, 3, 5]); | |
| 104 | s = lay(s, 0, 1); // joint at 6 | |
| 105 | s = lay(s, 2); // 3 filled; left: 3 (joint at 6), 5 (ends 8) | |
| 106 | const a = place(s, 4); // 8 filled; left: 3 → 11 fine, so still playing | |
| 107 | expect(a.state.status).toBe('playing'); | |
| 108 | const b = place(a.state, 3); // 11 filled, nothing left | |
| 109 | expect(b.state.status).toBe('lost'); | |
| 110 | expect(b.state.line).toContain('you lose'); | |
| 111 | expect(place(b.state, 3)).toMatchObject({ ok: false, why: 'over' }); | |
| 112 | const u = undo(b.state); | |
| 113 | expect([u.ok, u.state.status]).toEqual([true, 'playing']); | |
| 114 | }); | |
| 115 | ||
| 116 | test('MAX_STONE is no wider than the wall can take twice over', () => { | |
| 117 | expect(MAX_STONE * 2).toBeLessThanOrEqual(WIDTH); | |
| 118 | }); |
new above
offline
A lost wall with an empty current course cannot be undone ('nothing'), so this comment overstates. Either reword or allow reopening the last built course on a loss.