Public: anyone can read this; the crew can change it.
Migrated from github.com/amirmushichge/pixel-plays
Library Shelf rules: a tested `library-shelf/shelf.js` where you slide books along their runners to clear a gap for the returned book, within par slides, from plain data, in a two-file pull with a test file that runs in under a second #281
Check · Review · Land · Live done — Landed and live in production.
torque/pixel-plays:torque/269-library-shelf-rules-a-tested-library-she → main 2 commits fork 2 threads · 2 unresolved
2 files
changed +262
−0
library-shelf/shelf.js added +162
| @@ -0,0 +1,162 @@ | ||
| 1 | 'use strict'; | |
| 2 | // The Library Shelf rules: books of different widths sit on a two-level shelf. Each slides on one axis only, along | |
| 3 | // its level ('h') or between the levels ('v'). Clear a gap so the returned book can reach it, within par slides. | |
| 4 | // Plain data in, plain data out, no DOM, no timers, no randomness: the levels are hand-made and listed below. | |
| 5 | // A rejected call returns the very same state and says why. The page (not yet written) draws what this decides. | |
| 6 | // | |
| 7 | // Grid: x counts cells from the left, y counts levels from the top (0 = upper runner). Every book is one level | |
| 8 | // tall and `w` cells wide; (x, y) is its left cell. A slide moves a book by whole cells along its axis, one cell at | |
| 9 | // a time, and every cell it passes over or lands on must be on the grid and free. However far, it counts as one move. | |
| 10 | (function (root) { | |
| 11 | const HEIGHT = 2; // levels in every shelf | |
| 12 | const SOLVE_SCORE = 100; // points for clearing a level | |
| 13 | const PAR_BONUS = 50; // extra points when the level took no more than par moves | |
| 14 | const RETURNED = 'R'; // id of the returned book in every level | |
| 15 | ||
| 16 | // par is the fewest slides that solve the level, checked by a breadth-first search in the tests | |
| 17 | const LEVELS = [ | |
| 18 | { name: 'Easy return', width: 5, par: 2, gap: { x: 3, y: 0 }, books: [ | |
| 19 | { id: 'R', x: 0, y: 0, w: 2, axis: 'h' }, | |
| 20 | { id: 'A', x: 2, y: 0, w: 1, axis: 'v' }, | |
| 21 | ] }, | |
| 22 | { name: 'Two in the way', width: 6, par: 3, gap: { x: 4, y: 0 }, books: [ | |
| 23 | { id: 'R', x: 0, y: 0, w: 2, axis: 'h' }, | |
| 24 | { id: 'A', x: 2, y: 0, w: 2, axis: 'v' }, | |
| 25 | { id: 'B', x: 2, y: 1, w: 2, axis: 'h' }, | |
| 26 | ] }, | |
| 27 | { name: 'Lower runner', width: 6, par: 3, gap: { x: 4, y: 1 }, books: [ | |
| 28 | { id: 'R', x: 0, y: 1, w: 2, axis: 'h' }, | |
| 29 | { id: 'A', x: 3, y: 1, w: 1, axis: 'v' }, | |
| 30 | { id: 'B', x: 2, y: 0, w: 2, axis: 'h' }, | |
| 31 | ] }, | |
| 32 | ]; | |
| 33 | ||
| 34 | const copyBooks = bs => bs.map(b => ({ ...b })); | |
| 35 | const get = (s, id) => s.books.find(b => b.id === id); | |
| 36 | ||
| 37 | // free(books, book, x, y) -> true when the book, placed with its left cell at (x, y), is on the grid and clear | |
| 38 | function free(books, width, book, x, y) { | |
| 39 | if (x < 0 || y < 0 || y >= HEIGHT || x + book.w > width) return false; | |
| 40 | return !books.some(o => o.id !== book.id && o.y === y && o.x < x + book.w && x < o.x + o.w); | |
| 41 | } | |
| 42 | ||
| 43 | const reached = s => { const r = get(s, RETURNED); return r.x === s.gap.x && r.y === s.gap.y; }; | |
| 44 | ||
| 45 | const totalSlides = s => s.finished + s.spent + s.moves; | |
| 46 | ||
| 47 | function describe(s) { | |
| 48 | if (s.status === 'won') { | |
| 49 | return `Shelf cleared, you win: ${totalSlides(s)} slides against par ${s.totalPar}, ${s.score} points`; | |
| 50 | } | |
| 51 | return `Level ${s.level + 1} of ${s.levels}: ${s.moves} slides, par ${s.par}, ${s.score} points`; | |
| 52 | } | |
| 53 | ||
| 54 | function begin(level, carry) { | |
| 55 | const L = LEVELS[level]; | |
| 56 | const s = { | |
| 57 | level, levels: LEVELS.length, name: L.name, width: L.width, height: HEIGHT, gap: { ...L.gap }, par: L.par, | |
| 58 | books: copyBooks(L.books), moves: 0, history: [], solveScore: SOLVE_SCORE, parBonus: PAR_BONUS, | |
| 59 | totalPar: LEVELS.reduce((a, l) => a + l.par, 0), score: 0, finished: 0, spent: 0, status: 'playing', line: '', | |
| 60 | ...carry, | |
| 61 | }; | |
| 62 | s.line = describe(s); | |
| 63 | return s; | |
| 64 | } | |
| 65 | ||
| 66 | // start(level = 0) -> the shelf for that level (a whole number from 0); anything else gives level 0 | |
| 67 | const start = (level = 0) => begin(Number.isInteger(level) && level >= 0 && level < LEVELS.length ? level : 0); | |
| 68 | ||
| 69 | const refuse = (s, why) => ({ ok: false, why, event: '', state: s }); | |
| 70 | ||
| 71 | // slide(state, bookId, steps, axis?) -> { ok, why, event, state }: moves the book `steps` cells along its own | |
| 72 | // axis (positive is right or down, negative is left or up). Every accepted slide is one move. `axis` is optional; | |
| 73 | // naming an axis other than the book's own is refused. event is 'slid', 'solved' (the level is cleared and the next | |
| 74 | // one begins; state is the next level) or 'won' (the last level is cleared). Refused: 'over', 'no-book', | |
| 75 | // 'bad-steps' (not a whole number), 'zero', 'wrong-axis', 'off-grid', 'blocked'. | |
| 76 | function slide(s, id, steps, axis) { | |
| 77 | if (s.status !== 'playing') return refuse(s, 'over'); | |
| 78 | const book = get(s, id); | |
| 79 | if (!book) return refuse(s, 'no-book'); | |
| 80 | if (!Number.isInteger(steps)) return refuse(s, 'bad-steps'); | |
| 81 | if (steps === 0) return refuse(s, 'zero'); | |
| 82 | if (axis !== undefined && axis !== book.axis) return refuse(s, 'wrong-axis'); | |
| 83 | const dx = book.axis === 'h' ? Math.sign(steps) : 0; | |
| 84 | const dy = book.axis === 'v' ? Math.sign(steps) : 0; | |
| 85 | for (let i = 1; i <= Math.abs(steps); i++) { | |
| 86 | const x = book.x + dx * i, y = book.y + dy * i; | |
| 87 | if (x < 0 || y < 0 || y >= HEIGHT || x + book.w > s.width) return refuse(s, 'off-grid'); | |
| 88 | if (!free(s.books, s.width, book, x, y)) return refuse(s, 'blocked'); | |
| 89 | } | |
| 90 | const n = { ...s, books: copyBooks(s.books), history: s.history.concat([{ id, from: { x: book.x, y: book.y } }]) }; | |
| 91 | const b = get(n, id); | |
| 92 | b.x += dx * Math.abs(steps); b.y += dy * Math.abs(steps); | |
| 93 | n.moves += 1; | |
| 94 | if (!reached(n)) { n.line = describe(n); return { ok: true, why: '', event: 'slid', state: n }; } | |
| 95 | // solved: points, the bonus at or under par, then the next level or the win | |
| 96 | const score = n.score + SOLVE_SCORE + (n.moves <= n.par ? PAR_BONUS : 0); | |
| 97 | const finished = n.finished + n.spent + n.moves; | |
| 98 | if (s.level + 1 < LEVELS.length) { | |
| 99 | return { ok: true, why: '', event: 'solved', state: begin(s.level + 1, { score, finished }) }; | |
| 100 | } | |
| 101 | const w = { ...n, score, status: 'won' }; | |
| 102 | w.line = describe(w); | |
| 103 | return { ok: true, why: '', event: 'won', state: w }; | |
| 104 | } | |
| 105 | ||
| 106 | // undo(state) -> { ok, why, event: 'undone' }: puts the last slide back. It costs a move, so the count goes up. | |
| 107 | // Refused with 'nothing' when there is no slide to take back, and 'over' once the game is won. | |
| 108 | function undo(s) { | |
| 109 | if (s.status !== 'playing') return refuse(s, 'over'); | |
| 110 | if (!s.history.length) return refuse(s, 'nothing'); | |
| 111 | const n = { ...s, books: copyBooks(s.books), history: s.history.slice(0, -1) }; | |
| 112 | const last = s.history[s.history.length - 1]; | |
| 113 | const b = get(n, last.id); | |
| 114 | b.x = last.from.x; b.y = last.from.y; | |
| 115 | n.moves += 1; | |
| 116 | n.line = describe(n); | |
| 117 | return { ok: true, why: '', event: 'undone', state: n }; | |
| 118 | } | |
| 119 | ||
| 120 | // restart(state) -> the current level again, books back where they began. Slides already made stay in the | |
| 121 | // total (they were spent) but the level's own count, which the par bonus looks at, begins again. Never refused | |
| 122 | // while playing: there is no loss, only another go. | |
| 123 | function restart(s) { | |
| 124 | if (s.status !== 'playing') return refuse(s, 'over'); | |
| 125 | return { | |
| 126 | ok: true, why: '', event: 'restarted', | |
| 127 | state: begin(s.level, { score: s.score, finished: s.finished, spent: s.spent + s.moves }), | |
| 128 | }; | |
| 129 | } | |
| 130 | ||
| 131 | // solve(state) -> the fewest slides [[id, steps], ...] that clear the current level, by breadth-first search, or | |
| 132 | // null. Used to prove the levels, and by a hint if the page wants one. | |
| 133 | function solve(s) { | |
| 134 | const key = bs => bs.map(b => b.x + ',' + b.y).join(';'); | |
| 135 | const seen = new Set([key(s.books)]); | |
| 136 | let layer = [{ books: s.books, path: [] }]; | |
| 137 | while (layer.length) { | |
| 138 | const next = []; | |
| 139 | for (const { books, path } of layer) { | |
| 140 | for (const b of books) { | |
| 141 | for (const dir of [-1, 1]) { | |
| 142 | for (let k = 1; ; k++) { | |
| 143 | const x = b.x + (b.axis === 'h' ? dir * k : 0), y = b.y + (b.axis === 'v' ? dir * k : 0); | |
| 144 | if (!free(books, s.width, b, x, y)) break; | |
| 145 | const moved = books.map(o => (o === b ? { ...o, x, y } : o)); | |
| 146 | const p = path.concat([[b.id, dir * k]]); | |
| 147 | const r = moved.find(o => o.id === RETURNED); | |
| 148 | if (r.x === s.gap.x && r.y === s.gap.y) return p; | |
| 149 | const kk = key(moved); | |
| 150 | if (!seen.has(kk)) { seen.add(kk); next.push({ books: moved, path: p }); } | |
| 151 | } | |
| 152 | } | |
| 153 | } | |
| 154 | } | |
| 155 | layer = next; | |
| 156 | } | |
| 157 | return null; | |
| 158 | } | |
| 159 | ||
| 160 | const api = { HEIGHT, SOLVE_SCORE, PAR_BONUS, RETURNED, LEVELS, start, slide, undo, restart, solve }; | |
| 161 | if (typeof module !== 'undefined') module.exports = api; else root.LibraryShelf = api; | |
| 162 | })(typeof window !== 'undefined' ? window : globalThis); |
library-shelf/shelf.test.mjs added +100
| @@ -0,0 +1,100 @@ | ||
| 1 | import { test, expect } from 'bun:test'; | |
| 2 | import { HEIGHT, SOLVE_SCORE, PAR_BONUS, LEVELS, start, slide, undo, restart, solve } from './shelf.js'; | |
| 3 | ||
| 4 | const go = (s, ...moves) => moves.reduce((st, [id, n]) => { const r = slide(st, id, n); expect(r.ok).toBe(true); return r.state; }, s); | |
| 5 | const why = (s, ...args) => { const r = slide(s, ...args); expect(r.ok).toBe(false); expect(r.state).toBe(s); return r.why; }; | |
| 6 | ||
| 7 | test('every level has a solution, and its par is the fewest slides', () => { | |
| 8 | expect(LEVELS.length).toBeGreaterThan(2); | |
| 9 | LEVELS.forEach((L, i) => { | |
| 10 | const s = start(i); | |
| 11 | expect([s.width, s.height, s.par]).toEqual([L.width, HEIGHT, L.par]); | |
| 12 | const path = solve(s); | |
| 13 | expect(path).not.toBeNull(); | |
| 14 | expect(path.length).toBe(L.par); | |
| 15 | let r = { state: s }; | |
| 16 | for (const [id, n] of path) { r = slide(r.state, id, n); expect(r.ok).toBe(true); } | |
| 17 | expect(['solved', 'won']).toContain(r.event); | |
| 18 | }); | |
| 19 | }); | |
| 20 | ||
| 21 | test('refused slides: off the grid, through a book, wrong axis, zero, and others', () => { | |
| 22 | const s = start(1); // R(0,0 w2 h) A(2,0 w2 v) B(2,1 w2 h), width 6 | |
| 23 | expect(why(s, 'R', -1)).toBe('off-grid'); | |
| 24 | expect(why(s, 'B', 5)).toBe('off-grid'); | |
| 25 | expect(why(s, 'A', -1)).toBe('off-grid'); | |
| 26 | expect(why(s, 'R', 3)).toBe('blocked'); // A sits in the way | |
| 27 | expect(why(s, 'A', 1)).toBe('blocked'); // B sits below it | |
| 28 | expect(why(s, 'R', 1, 'v')).toBe('wrong-axis'); | |
| 29 | expect(why(s, 'A', 1, 'h')).toBe('wrong-axis'); | |
| 30 | expect(why(s, 'R', 0)).toBe('zero'); | |
| 31 | expect(why(s, 'R', 1.5)).toBe('bad-steps'); | |
| 32 | expect(why(s, 'R', '1')).toBe('bad-steps'); | |
| 33 | expect(why(s, 'Z', 1)).toBe('no-book'); | |
| 34 | expect(s.moves).toBe(0); | |
| 35 | }); | |
| 36 | ||
| 37 | test('a long slide counts as one move; an accepted slide moves the book', () => { | |
| 38 | const s = go(start(1), ['B', -2]); | |
| 39 | expect(s.moves).toBe(1); | |
| 40 | expect(s.books.find(b => b.id === 'B').x).toBe(0); | |
| 41 | expect(slide(s, 'B', 4).ok).toBe(true); | |
| 42 | const t = go(start(1), ['B', 2]); | |
| 43 | expect(t.moves).toBe(1); | |
| 44 | expect(t.books.find(b => b.id === 'B').x).toBe(4); | |
| 45 | }); | |
| 46 | ||
| 47 | test('undo puts the last slide back and costs a move', () => { | |
| 48 | const s = go(start(1), ['B', -2]); | |
| 49 | const r = undo(s); | |
| 50 | expect(r.ok).toBe(true); | |
| 51 | expect(r.event).toBe('undone'); | |
| 52 | expect(r.state.books).toEqual(start(1).books); | |
| 53 | expect(r.state.moves).toBe(2); | |
| 54 | expect(undo(start(1))).toMatchObject({ ok: false, why: 'nothing' }); | |
| 55 | expect(undo(r.state).why).toBe('nothing'); | |
| 56 | }); | |
| 57 | ||
| 58 | test('the move count, and the par bonus at or under par', () => { | |
| 59 | const s0 = start(0); // par 2 | |
| 60 | const r = slide(go(s0, ['A', 1]), 'R', 3); | |
| 61 | expect(r.event).toBe('solved'); | |
| 62 | expect(r.state.score).toBe(SOLVE_SCORE + PAR_BONUS); | |
| 63 | expect(r.state.level).toBe(1); | |
| 64 | expect(r.state.moves).toBe(0); // the next level begins fresh | |
| 65 | // over par: waste one slide first | |
| 66 | const r2 = slide(go(s0, ['A', 1], ['A', -1], ['A', 1]), 'R', 3); | |
| 67 | expect(r2.state.score).toBe(SOLVE_SCORE); | |
| 68 | // an undo is a move: slide, undo, slide again, then R is 4 moves against par 2, so no bonus | |
| 69 | const u = undo(go(s0, ['A', 1])).state; | |
This only checks that undo costs a move. Continue the case: slide R to the gap and assert the score is SOLVE_SCORE with no PAR_BONUS, so the over-par-by-undo path is covered. |
||
| 70 | expect(u.moves).toBe(2); | |
| 71 | const r3 = slide(go(u, ['A', 1]), 'R', 3); | |
| 72 | expect(r3.event).toBe('solved'); | |
| 73 | expect(r3.state.score).toBe(SOLVE_SCORE); | |
| 74 | }); | |
| 75 | ||
| 76 | test('the win line reports total slides against total par; restart replays the level', () => { | |
| 77 | let s = start(0); | |
| 78 | const mid = restart(go(s, ['A', 1])); | |
| 79 | expect(mid.event).toBe('restarted'); | |
| 80 | expect(mid.state.books).toEqual(start(0).books); | |
| 81 | expect(mid.state.moves).toBe(0); | |
| 82 | s = mid.state; // one slide already spent | |
| 83 | let last; | |
| 84 | for (let i = 0; i < LEVELS.length; i++) { | |
| 85 | for (const [id, n] of solve(s)) last = slide(s, id, n), s = last.state; | |
| 86 | } | |
| 87 | expect(last.event).toBe('won'); | |
| 88 | expect(s.status).toBe('won'); | |
| 89 | const par = LEVELS.reduce((a, l) => a + l.par, 0); | |
| 90 | expect(s.line).toBe(`Shelf cleared, you win: ${par + 1} slides against par ${par}, ${s.score} points`); | |
| 91 | expect(s.score).toBe(LEVELS.length * SOLVE_SCORE + (LEVELS.length) * PAR_BONUS); | |
| 92 | expect(slide(s, 'R', 1).why).toBe('over'); | |
| 93 | expect(undo(s).why).toBe('over'); | |
| 94 | }); | |
| 95 | ||
| 96 | test('start gives plain data and a bad level gives the first', () => { | |
| 97 | expect(start(-1)).toEqual(start(0)); | |
| 98 | expect(start('x')).toEqual(start(0)); | |
| 99 | expect(JSON.parse(JSON.stringify(start(2)))).toEqual(start(2)); | |
| 100 | }); |
new above
offline
Dead code:
finiteis never called. Remove it.