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

Migrated from github.com/amirmushichge/pixel-plays

Add Library Shelf: the playable page and its place in the catalogue, on the rules in `library-shelf/shelf.js` #285

Merged opened this

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

Merged

vesper/pixel-plays:vesper/271-add-library-shelf-the-playable-page-and → main 1 commit fork

  • Merged. vesper/271-add-library-shelf-the-playable-page-and was merged into main as 9c36ff9.

Review

Sign in to review this change.
9 files changed +477 −2
README.md +3 −2

Diff not shown — a line 2,841 characters wide (limit 2,000). +3 −2

View file
index.html +1
@@ -127,6 +127,7 @@ footer a::after { content: none; }
127127 <li data-kind="Catching" data-input="Tap" style="--accent:#3a8fa3"><a href="rock-pool/">Rock Pool</a><span>Scoop the darting crabs into your bucket before the tide comes back</span><span>Game forged by the crew</span><span class="tags">Catching · Tap</span></li>
128128 <li data-kind="Puzzle" data-input="Tap" style="--accent:#5a6fb8"><a href="stained-glass/">Stained Glass</a><span>Colour the window so no two neighbouring panes match</span><span>Game forged by the crew</span><span class="tags">Puzzle · Tap</span></li>
129129 <li data-kind="Puzzle" data-input="Tap" style="--accent:#b8324a"><a href="jam-jars/">Jam Jars</a><span>Pour the fruit between jars until every jar holds just one jam</span><span>Game forged by the crew</span><span class="tags">Puzzle · Tap</span></li>
130 <li data-kind="Puzzle" data-input="Drag" style="--accent:#6b4a2e"><a href="library-shelf/">Library Shelf</a><span>Slide the books along their runners to make room for the returned one</span><span>Game forged by the crew</span><span class="tags">Puzzle · Drag</span></li>
130131 <li data-kind="Sport" data-input="Tap" style="--accent:#8a4b22"><a href="conkers/">Conkers</a><span>Time your swing to crack every rival conker in the playground</span><span>Game forged by the crew</span><span class="tags">Sport · Tap</span></li>
131132 </ul>
132133 <footer>Concept by <a href="https://x.com/awwbhi2">abhi</a>. Game by <a href="https://x.com/AmirMushich">AmirMushich</a>. Visual reference for the style: shawn.'s <a href="https://x.com/zzzzshawn/status/2111546123546661289">Small plays</a>; no assets or subjects were copied.<br><a href="stats/">Most played</a></footer>
library-shelf/index.html added +375
@@ -0,0 +1,375 @@
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
6 <title>Library Shelf</title>
7 <!-- og:begin -->
8 <meta name="description" content="Slide the books along their runners to make room for the returned one">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/library-shelf/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Library Shelf">
13 <meta property="og:description" content="Slide the books along their runners to make room for the returned one">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/library-shelf/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/library-shelf.png">
16 <meta property="og:image:type" content="image/png">
17 <meta property="og:image:width" content="1200">
18 <meta property="og:image:height" content="630">
19 <meta property="og:image:alt" content="Library Shelf: the opening scene of the game">
20 <meta name="twitter:card" content="summary_large_image">
21 <!-- og:end -->
22 <style>
23 :root { --ink: #1c1b19; --muted: #6b675f; --paper: #fff; --accent: #6b4a2e; }
24 * { box-sizing: border-box; }
25 html, body { -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; }
26 html, body { height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
27 body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; }
28 #stage { position: fixed; inset: 0; display: grid; place-items: center; }
29 canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; outline: none; }
30 .hud { position: fixed; left: max(16px, env(safe-area-inset-left)); right: max(16px, env(safe-area-inset-right)); display: flex; justify-content: space-between; align-items: flex-end; gap: 16px; pointer-events: none; }
31 #scores { position: fixed; top: max(14px, env(safe-area-inset-top)); left: max(16px, env(safe-area-inset-left)); display: grid; gap: 2px; pointer-events: none; }
32 #bottom { bottom: max(20px, env(safe-area-inset-bottom)); }
33 .row { display: flex; align-items: center; gap: 8px; color: var(--accent); }
34 .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; }
35 .row span { color: var(--muted); }
36 #status { color: var(--muted); min-height: 1.35em; }
37 .keys { display: flex; gap: 8px; }
38 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 13px 10px; margin: -13px -10px; min-height: 44px; min-width: 44px; cursor: pointer; }
39 button:hover, button:focus-visible { color: var(--ink); }
40 button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
41 noscript p { position: fixed; inset: 40% 16px auto; margin: 0; text-align: center; color: var(--muted); }
42 </style>
43 </head>
44 <body>
45 <div id="stage"><canvas id="c" tabindex="0" aria-label="An oak library shelf with two runners and books of different widths. Drag a book along its runner to slide it, or press Tab to select a book and the arrow keys to slide it one cell. Each book shows the way it slides by an arrow on its spine. Slide the books aside to clear the dashed gap for the returned book, the one with a ribbon bookmark at its end. U undoes, which costs a slide, and R starts the level again. Three levels, each with a par of slides."></canvas></div>
46 <noscript><p>Library Shelf needs JavaScript to play.</p></noscript>
47 <div id="scores">
48 <div class="row"><b id="level">1 of 3</b><span id="name">shelf</span></div>
49 <div class="row"><b id="slides">0</b><span>slides</span></div>
50 <div class="row"><b id="par">0</b><span>par</span></div>
51 <div class="row"><b id="score">0</b><span>points</span></div>
52 </div>
53 <div class="hud" id="bottom">
54 <div id="status" role="status" aria-live="polite"></div>
55 <div class="keys"><button id="undo" type="button">undo</button><button id="mute" type="button" aria-pressed="false">sound on</button></div>
56 </div>
57 <script src="../shell.js"></script>
58 <script>
59 PixelPlays.mount({
60 id: 'library-shelf',
61 rules: [
62 'Drag a book along its runner, or Tab to pick one and use the arrows.',
63 'Each book slides only the way its spine arrow points, and cannot pass another.',
64 'Clear the dashed gap for the ribbon-marked book. Undo costs a slide; U undoes, R restarts.',
65 'Clear all 3 shelves, within par slides for a bonus.',
66 ],
67 });
68 </script>
69 <script>window.PP_SCENE = { originY: 8, shadowX: 1, shadowY: -.12 };</script>
70 <script src="../engine.js"></script>
71 <script src="shelf.js"></script>
72 <script>
73 'use strict';
74
75 const M = window.LibraryShelf;
76 const INK_PIX = rgb(28, 27, 25), SIGNAL_PIX = rgb(255, 214, 10), SEL_PIX = rgb(0, 150, 255), CREAM = rgb(250, 244, 226), RIBBON = rgb(240, 150, 30);
77 const BACK = [[150, 104, 60], [142, 98, 56]], OAK = [[196, 146, 88], [184, 136, 80]], OAK_FRONT = [128, 88, 52], ROOM = [[232, 222, 200], [224, 213, 190]];
78 // one cloth colour per book; the returned book is the red one and also carries a ribbon bookmark
79 const CLOTH = { R: [176, 48, 58], A: [52, 104, 150], B: [70, 128, 84], C: [196, 160, 60], D: [112, 76, 140], E: [60, 130, 130] };
80 const RAMPS = {};
81 const clothOf = id => RAMPS[id] ??= rampOf(CLOTH[id] || [120, 110, 100]);
82
83 const CW = 46, ROWH = 90, BH = 66, SHELF = { top: 30, bottom: 226 };
84 const BASES = [118, 208]; // the runner each level's books stand on
85 const shelfX0 = () => Math.round((W - P.width * CW) / 2);
86
87 /* ---------- state ---------- */
88 const nodes = {};
89 for (const k of ['level', 'name', 'slides', 'par', 'score', 'status']) nodes[k] = document.getElementById(k);
90 const shown = {};
91 function setText(key, text) {
92 if (shown[key] === text) return;
93 shown[key] = text;
94 nodes[key].textContent = text;
95 }
96 let P = M.start(0);
97 // sel: id of the chosen book (or null); drag: a book being pulled; dirty: the shelf must be drawn again; layers counts how often
98 const G = { time: 0, noteUntil: 0, sel: null, drag: null, dirty: true, layers: 0 };
99 const REFUSED = {
100 blocked: 'another book is in the way', 'off-grid': 'the shelf ends there', zero: 'it did not move', 'wrong-axis': 'that book slides the other way',
101 nothing: 'nothing to undo', over: 'the shelf is done', 'no-book': 'tap a book', 'bad-steps': 'drag a whole cell',
102 };
103 const START = 'drag a book, or press Tab to choose one and use the arrows';
104
105 function renderHud() {
106 setText('level', `${P.level + 1} of ${P.levels}`);
107 setText('name', P.name);
108 setText('slides', String(P.moves));
109 setText('par', String(P.par));
110 setText('score', String(P.score));
111 }
112 function note(text) { setText('status', text); G.noteUntil = G.time + 2; }
113 const bookById = id => P.books.find(b => b.id === id);
114 const nameOf = b => (b.id === M.RETURNED ? 'the returned book' : `book ${b.id}`);
115 const describe = b => `${nameOf(b)}, ${b.w} wide, slides ${b.axis === 'h' ? 'left and right' : 'up and down'}`;
116
117 /* ---------- geometry ---------- */
118 const unitOf = b => (b.axis === 'h' ? CW : ROWH);
119 const heightOf = b => (b.id === M.RETURNED ? BH : 54 + (b.id.charCodeAt(0) * 7) % 11);
120 const bookBox = b => {
121 const x = shelfX0() + b.x * CW + 2, bottom = BASES[b.y], h = heightOf(b);
122 return { x0: x, x1: x + b.w * CW - 4, y0: bottom - h, y1: bottom };
123 };
124 const bookPoint = id => { const q = bookBox(bookById(id)); return [Math.round((q.x0 + q.x1) / 2), Math.round((q.y0 + q.y1) / 2)]; };
125 // where a pointer ends to slide a book by `steps` cells
126 const dragTo = (id, steps) => { const b = bookById(id), [x, y] = bookPoint(id); return b.axis === 'h' ? [x + steps * CW, y] : [x, y + steps * ROWH]; };
127 const bookAtPoint = (sx, sy) => {
128 for (let i = P.books.length - 1; i >= 0; i--) {
129 const q = bookBox(P.books[i]);
130 if (sx >= q.x0 && sx <= q.x1 && sy >= q.y0 - 2 && sy <= q.y1) return P.books[i];
131 }
132 return null;
133 };
134 // how far a book can go each way, asked of the rules themselves: the largest run of slides they accept
135 function reach(b, dir) {
136 let k = 0;
137 while (k < P.width + 2 && M.slide(P, b.id, dir * (k + 1)).ok) k++;
138 return k;
139 }
140
141 /* ---------- baked scene: the reading room and the oak shelf ---------- */
142 function rect(x0, y0, x1, y1, f) { for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) f(x, y, y * W + x); }
143 function bake() {
144 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
145 const c = ROOM[(ix >> 4) & 1], t = .97 + (hash(ix, iy) - .5) * .05;
146 pix[iy * W + ix] = rgb(c[0] * t, c[1] * t, c[2] * t);
147 }
148 const x0 = 24, x1 = 336;
149 // the back panel, then the boards: top, middle (the upper runner) and bottom (the lower runner)
150 rect(x0, SHELF.top, x1, SHELF.bottom, (x, y, i) => { const g = noise(x * .06, y * .8) > .6 ? .92 : 1, c = BACK[(x >> 3) & 1]; pix[i] = rgb(c[0] * g, c[1] * g, c[2] * g); });
151 for (const top of [SHELF.top - 10, BASES[0], BASES[1]]) {
152 const front = top + 8;
153 rect(x0 - 8, top, x1 + 8, top + 14, (x, y, i) => {
154 const g = noise(x * .07, y * .9) > .55 ? .9 : 1, c = y < front ? OAK[(y >> 1) & 1] : OAK_FRONT;
155 pix[i] = rgb(c[0] * g, c[1] * g, c[2] * g);
156 });
157 rect(x0 - 8, front, x1 + 8, front + 1, (x, y, i) => { pix[i] = INK_PIX; });
158 rect(x0 - 8, top + 13, x1 + 8, top + 14, (x, y, i) => { pix[i] = INK_PIX; });
159 }
160 rect(x0 - 8, SHELF.top - 10, x0, SHELF.bottom + 14, (x, y, i) => { pix[i] = x === x0 - 8 || x === x0 - 1 ? INK_PIX : rgb(...OAK[0]); });
161 rect(x1, SHELF.top - 10, x1 + 8, SHELF.bottom + 14, (x, y, i) => { pix[i] = x === x1 + 7 || x === x1 ? INK_PIX : rgb(...OAK_FRONT); });
162 bakedPix.set(pix);
163 }
164
165 /* ---------- the shelf layer: drawn once per change and cached ---------- */
166 const layerPix = new Uint32Array(W * H);
167 const darken = (i, k) => { const c = pix[i]; pix[i] = rgb((c & 255) * k, (c >> 8 & 255) * k, (c >> 16 & 255) * k); };
168 function arrow(cx, cy, axis, color) {
169 const put = (x, y) => { if (axis === 'h') pix[(cy + y) * W + cx + x] = color; else pix[(cy + x) * W + cx + y] = color; };
170 for (let t = -8; t <= 8; t++) put(t, 0);
171 for (let i = 1; i <= 4; i++) for (let s = -i; s <= i; s++) { put(8 - i + 1, s); put(-8 + i - 1, s); }
172 }
173 function paintBook(b, dx, dy, held) {
174 const q = bookBox(b), x0 = q.x0 + dx, x1 = q.x1 + dx, y0 = q.y0 + dy, y1 = q.y1 + dy, ramp = clothOf(b.id);
175 for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) {
176 const lx = x - x0, edge = lx === 0 || x === x1 - 1 || y === y0 || y === y1 - 1;
177 const band = (y - y0 > 7 && y - y0 < 10) || (y1 - y > 8 && y1 - y < 11);
178 pix[y * W + x] = edge ? (held ? SEL_PIX : INK_PIX) : band ? SIGNAL_PIX : lx < 4 ? ramp[4] : x1 - x < 6 ? ramp[1] : ramp[3];
179 }
180 if (held) for (let x = x0 - 1; x <= x1; x++) { pix[(y0 - 1) * W + x] = SEL_PIX; pix[y1 * W + x] = SEL_PIX; }
181 if (held) for (let y = y0 - 1; y <= y1; y++) { pix[y * W + x0 - 1] = SEL_PIX; pix[y * W + x1] = SEL_PIX; }
182 // the arrow on the spine shows the one way this book slides: ink behind, cream in front
183 const cx = Math.round((x0 + x1) / 2), cy = Math.round((y0 + y1) / 2) + 2;
184 for (const [ox, oy] of [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [1, 1], [-1, 1], [1, -1]]) arrow(cx + ox, cy + oy, b.axis, INK_PIX);
185 arrow(cx, cy, b.axis, CREAM);
186 // the returned book also hangs a ribbon bookmark from its pages, with a notched end
187 if (b.id === M.RETURNED) {
188 const rx = x1 - 12;
189 for (let y = y1 - 20; y < y1 + 9; y++) for (let x = rx; x < rx + 5; x++) {
190 const notch = y > y1 + 4 && x - rx >= 2 - (y - y1 - 4) && x - rx <= 2 + (y - y1 - 4) - 1;
191 if (!notch) pix[y * W + x] = x === rx || x === rx + 4 ? INK_PIX : RIBBON;
192 }
193 }
194 }
195 function paintLayer() {
196 pix.set(bakedPix);
197 const gx = shelfX0();
198 // the gap the returned book must reach: a dashed slot, in its own row
199 const r = bookById(M.RETURNED), gb = { ...r, x: P.gap.x, y: P.gap.y }, gq = bookBox(gb);
200 for (let x = gq.x0; x < gq.x1; x++) for (const y of [gq.y0, gq.y1 - 1]) if (((x >> 2) & 1) === 0) pix[y * W + x] = CREAM;
201 for (let y = gq.y0; y < gq.y1; y++) for (const x of [gq.x0, gq.x1 - 1]) if (((y >> 2) & 1) === 0) pix[y * W + x] = CREAM;
202 const off = b => (G.drag && G.drag.id === b.id ? G.drag.off : 0);
203 const at = b => (b.axis === 'h' ? [off(b), 0] : [0, off(b)]);
204 // hard shadows, screen-right, on the back panel
205 for (const b of P.books) {
206 const q = bookBox(b), [dx, dy] = at(b);
207 for (let y = q.y0 + 4 + dy; y < q.y1 + dy; y++) for (let x = q.x1 + dx; x < q.x1 + dx + 7; x++) if (x < 336 && x > gx - 4) darken(y * W + x, .74);
208 }
209 for (const b of P.books) { const [dx, dy] = at(b); if (G.sel !== b.id) paintBook(b, dx, dy, false); }
210 for (const b of P.books) { const [dx, dy] = at(b); if (G.sel === b.id) paintBook(b, dx, dy, true); }
211 layerPix.set(pix);
212 G.layers++;
213 G.dirty = G.drag !== null;
214 }
215 // lamplight: a few dust motes drift down the shelf in whole pixels at 8 fps; not drawn at all under reduced motion
216 function motes() {
217 const step = Math.floor(G.time * WIND_FPS);
218 for (let k = 0; k < 7; k++) {
219 const x = 30 + Math.floor(hash(k, 1) * 300 + step * (k % 2 ? 1 : 2) / 4) % 300, y = 36 + Math.floor(hash(k, 2) * 180 + step / (2 + k % 3)) % 180;
220 pix[y * W + x] = CREAM;
221 }
222 }
223 function draw() {
224 if (G.dirty) paintLayer();
225 pix.set(layerPix);
226 if (!STILL) motes();
227 ctx.putImageData(image, 0, 0);
228 }
229
230 /* ---------- game: every rule is the rules script's ---------- */
231 function show() { G.dirty = true; renderHud(); }
232 function slideBook(id, steps) {
233 const before = P, b = bookById(id), r = M.slide(P, id, steps);
234 if (!r.ok) { note(REFUSED[r.why] || 'cannot do that'); sound(110, .12, 'sawtooth'); show(); return false; }
235 P = r.state;
236 if (r.event === 'slid') { note(`Slid ${nameOf(b)}. ${P.line}`); sound(260, .08, 'triangle'); }
237 else if (r.event === 'solved') {
238 G.sel = null;
239 note(`${before.name} cleared in ${before.moves + 1} slides, par ${before.par}. Next: ${P.name}`);
240 sound(523, .12, 'triangle'); sound(659, .2, 'triangle', .1);
241 } else if (r.event === 'won') { G.sel = null; G.noteUntil = 0; sound(523, .12, 'triangle'); sound(659, .12, 'triangle', .12); sound(784, .4, 'triangle', .24); }
242 show();
243 return true;
244 }
245 function undo() {
246 ensureAudio();
247 if (P.status !== 'playing') return;
248 const r = M.undo(P);
249 if (!r.ok) { note(REFUSED[r.why] || 'cannot do that'); sound(110, .12, 'sawtooth'); return; }
250 P = r.state;
251 note(`Undone, it costs a slide. ${P.line}`);
252 sound(300, .07, 'triangle');
253 show();
254 }
255 function restart() {
256 P = M.start(0); G.sel = null; G.drag = null;
257 show();
258 note(START);
259 }
260 function redo() {
261 if (P.status !== 'playing') return;
262 P = M.restart(P); G.sel = null; G.drag = null;
263 show();
264 note(`${P.name} begun again`);
265 }
266 function update(dt) {
267 G.time += dt;
268 if (G.time < G.noteUntil) return;
269 setText('status', P.status === 'won' ? `${P.line} · tap or press a key to play again` : P.line);
270 }
271
272 /* ---------- input ---------- */
273 const point = e => { const r = canvas.getBoundingClientRect(); return [(e.clientX - r.left) / r.width * W, (e.clientY - r.top) / r.height * H]; };
274 canvas.addEventListener('pointerdown', e => {
275 canvas.focus({ preventScroll: true });
276 ensureAudio();
277 if (P.status !== 'playing') { restart(); return; }
278 const [sx, sy] = point(e), b = bookAtPoint(sx, sy);
279 if (!b) { if (G.sel !== null) { G.sel = null; show(); } note(START); return; }
280 if (canvas.setPointerCapture) { try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* synthetic pointer */ } }
281 const was = G.sel === b.id;
282 G.sel = b.id;
283 G.drag = { id: b.id, was, from: b.axis === 'h' ? sx : sy, off: 0, back: reach(b, -1), fwd: reach(b, 1) };
284 note(describe(b));
285 show();
286 });
287 canvas.addEventListener('pointermove', e => {
288 const d = G.drag;
289 if (!d) return;
290 const b = bookById(d.id), [sx, sy] = point(e), u = unitOf(b), raw = (b.axis === 'h' ? sx : sy) - d.from;
291 d.off = Math.round(Math.max(-d.back * u, Math.min(d.fwd * u, raw)));
292 G.dirty = true;
293 });
294 function release() {
295 const d = G.drag;
296 if (!d) return;
297 G.drag = null;
298 const b = bookById(d.id), steps = Math.round(d.off / unitOf(b));
299 if (steps === 0) { if (d.was && Math.abs(d.off) < 4) { G.sel = null; note(START); } show(); return; }
300 slideBook(d.id, steps);
301 }
302 canvas.addEventListener('pointerup', release);
303 canvas.addEventListener('pointercancel', release);
304 canvas.addEventListener('keydown', e => {
305 if (e.ctrlKey || e.metaKey || e.altKey) return;
306 const dirs = { ArrowRight: ['h', 1], ArrowLeft: ['h', -1], ArrowDown: ['v', 1], ArrowUp: ['v', -1] };
307 const arrowKey = dirs[e.key], tab = e.key === 'Tab', again = e.key === 'r' || e.key === 'R', back = e.key === 'u' || e.key === 'U', esc = e.key === 'Escape';
308 if (!arrowKey && !tab && !again && !back && !esc) return;
309 if (P.status !== 'playing') { if (!tab) { e.preventDefault(); restart(); } return; }
310 if (tab) {
311 // Tab walks the books in shelf order; past the last one (or before the first) it leaves the canvas as usual
312 const at = P.books.findIndex(b => b.id === G.sel), n = at + (e.shiftKey ? -1 : 1);
313 if (n < 0 || n >= P.books.length) { if (G.sel !== null) { G.sel = null; show(); } return; }
314 e.preventDefault();
315 G.sel = P.books[n].id;
316 note(describe(P.books[n]));
317 show();
318 return;
319 }
320 e.preventDefault();
321 if (again) { redo(); return; }
322 if (back) { undo(); return; }
323 if (esc) { G.sel = null; note(START); show(); return; }
324 ensureAudio();
325 if (e.repeat) return;
326 const b = G.sel === null ? null : bookById(G.sel);
327 if (!b) { note('press Tab to choose a book first'); return; }
328 if (b.axis !== arrowKey[0]) { note(REFUSED['wrong-axis']); sound(110, .12, 'sawtooth'); return; }
329 slideBook(b.id, arrowKey[1]);
330 });
331 document.getElementById('undo').addEventListener('click', undo);
332
333 /* ---------- sound ---------- */
334 let audio = null, muted = false;
335 function ensureAudio() {
336 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
337 const AC = window.AudioContext || window.webkitAudioContext;
338 if (AC) audio = new AC();
339 }
340 function sound(freq, life, type, delay = 0) {
341 if (!audio || muted) return;
342 const now = audio.currentTime + delay, gain = audio.createGain(), osc = audio.createOscillator();
343 osc.type = type;
344 osc.frequency.setValueAtTime(freq, now);
345 gain.gain.setValueAtTime(.0001, now);
346 gain.gain.exponentialRampToValueAtTime(.07, now + .01);
347 gain.gain.exponentialRampToValueAtTime(.0005, now + life);
348 osc.connect(gain).connect(audio.destination);
349 osc.start(now); osc.stop(now + life + .02);
350 }
351 const muteButton = document.getElementById('mute');
352 muteButton.addEventListener('click', () => {
353 muted = !muted;
354 muteButton.textContent = muted ? 'sound off' : 'sound on';
355 muteButton.setAttribute('aria-pressed', String(muted));
356 });
357
358 /* ---------- fit and boot ---------- */
359 addEventListener('resize', fit);
360 fit();
361 bake();
362 renderHud();
363 note(START);
364 canvas.focus({ preventScroll: true });
365 let last = performance.now();
366 function frame(now) {
367 update(Math.min(.04, (now - last) / 1000));
368 last = now;
369 draw();
370 requestAnimationFrame(frame);
371 }
372 requestAnimationFrame(frame);
373 </script>
374 </body>
375 </html>
library-shelf/page.test.mjs added +81
@@ -0,0 +1,81 @@
1 import { test, expect } from 'bun:test';
2 import { boot } from '../playtest.mjs';
3
4 test('dragging a book along its runner slides it by whole cells and the HUD reports the rules state', () => {
5 const g = boot('library-shelf', { seed: 3 });
6 g.drag(g.read('bookPoint("A")'), g.read('dragTo("A", 1)'));
7 expect(g.read('P.books.find(b => b.id === "A").y')).toBe(1);
8 expect(g.read('P.moves')).toBe(1);
9 expect(g.el('slides').textContent).toBe('1');
10 expect(g.el('par').textContent).toBe(String(g.read('P.par')));
11 expect(g.el('level').textContent).toBe('1 of 3');
12 expect(g.el('name').textContent).toBe('Easy return');
13 expect(g.el('status').textContent).toContain(g.read('P.line'));
14 });
15
16 test('a drag is stopped by the book in the way and by the shelf end, and a refused slide changes nothing', () => {
17 const g = boot('library-shelf', { seed: 3 });
18 g.drag(g.read('bookPoint("R")'), g.read('dragTo("R", 3)')); // R is blocked by A: it can go nowhere
19 expect(g.read('P.moves')).toBe(0);
20 g.press('Tab'); g.press('ArrowLeft');
21 expect(g.read('P.moves')).toBe(0);
22 });
23
24 test('Tab selects a book, arrows slide it one cell, a wrong-way arrow says so, U undoes at the cost of a slide', () => {
25 const g = boot('library-shelf', { seed: 3 });
26 g.press('Tab'); g.press('Tab');
27 expect(g.read('G.sel')).toBe('A');
28 g.press('ArrowLeft');
29 expect(g.el('status').textContent).toContain('other way');
30 g.press('ArrowDown');
31 expect(g.read('P.moves')).toBe(1);
32 g.press('u');
33 expect(g.read('P.moves')).toBe(2);
34 expect(g.read('P.books.find(b => b.id === "A").y')).toBe(0);
35 g.el('undo').fire('click'); // nothing left to take back: refused, no cost
36 expect(g.read('P.moves')).toBe(2);
37 expect(g.el('status').textContent).toContain('nothing to undo');
38 });
39
40 test('clearing the gap solves the level and the next one begins', () => {
41 const g = boot('library-shelf', { seed: 3 });
42 g.press('Tab'); g.press('Tab'); g.press('ArrowDown');
43 g.press('Tab'); g.press('Tab'); g.press('ArrowRight'); g.press('ArrowRight'); g.press('ArrowRight');
44 expect(g.read('P.level')).toBe(1);
45 });
46
47 test('the returned book carries a ribbon the others lack, and every book has a spine arrow', async () => {
48 const html = await Bun.file(new URL('./index.html', import.meta.url)).text();
49 expect(html).toContain('if (b.id === M.RETURNED)');
50 expect(html).toContain('arrow(cx, cy, b.axis, CREAM)');
51 const g = boot('library-shelf', { seed: 3 });
52 expect(g.colours()).toBeGreaterThan(8);
53 });
54
55 test('the shelf is drawn once per change, not once per frame', () => {
56 const g = boot('library-shelf', { seed: 3 });
57 g.run(2);
58 const base = g.read('G.layers');
59 g.run(3);
60 expect(g.read('G.layers')).toBe(base);
61 g.press('Tab');
62 expect(g.read('G.layers')).toBeGreaterThan(base);
63 });
64
65 test('mute toggles its label and aria-pressed', () => {
66 const g = boot('library-shelf', { seed: 3 });
67 g.el('mute').fire('click');
68 expect(g.el('mute').textContent).toBe('sound off');
69 expect(g.el('mute').attrs['aria-pressed']).toBe('true');
70 });
71
72 test('the page source says how to play, keeps the 44px targets, stills the dust, holds the rules to four lines and names no .mp3', async () => {
73 const html = await Bun.file(new URL('./index.html', import.meta.url)).text();
74 expect(html).toMatch(/<canvas id="c"[^>]*aria-label="[^"]*Drag a book[^"]*Tab[^"]*arrow/);
75 expect(html).toMatch(/min-height: 44px; min-width: 44px/);
76 expect(html).toMatch(/id="mute"[^>]*aria-pressed="false"/);
77 expect(html).toContain('if (!STILL) motes()');
78 expect(html).not.toContain('.mp3');
79 const rules = html.match(/rules: \[([\s\S]*?)\]/)[1].split('\n').filter(l => l.trim());
80 expect(rules.length).toBeLessThanOrEqual(4);
81 });
og/home.png
Binary file not shown.
og/library-shelf.png added
Binary file not shown.
rounds.mjs +9
@@ -9,6 +9,7 @@ import { toss, MAX_AIM } from './hoopla/hoop.js';
99 import Wheel from './ferris-wheel/wheel.js';
1010 import Quilt from './quilt/patch.js';
1111 import Jars from './jam-jars/shelf.js';
12 import Shelf from './library-shelf/shelf.js';
1213
1314 const MID = [180, 140];
1415 const tapping = (wait = .3) => g => { g.tap(...MID); g.run(wait); };
@@ -223,6 +224,14 @@ export const ROUNDS = {
223224 if (g.read('G.colour') !== colour) g.tap(...g.read(`swatchPoint(${colour})`));
224225 else g.tap(...g.read(`panePoint(${pane})`));
225226 } },
227 // slide along the shortest plan the rules' own search finds for each shelf: drag the book by the cells the plan names
228 'library-shelf': { over: /play again/, outcome: /Shelf cleared, you win: \d+ slides against par \d+/, beat: g => {
229 if (g.read('P.status') !== 'playing') { g.run(.3); return; }
230 const level = g.read('P.level');
231 if (g.plan?.level !== level) g.plan = { level, slides: Shelf.solve(Shelf.start(level)) };
232 const [id, steps] = g.plan.slides[g.read('P.moves')];
233 g.drag(g.read(`bookPoint(${JSON.stringify(id)})`), g.read(`dragTo(${JSON.stringify(id)}, ${steps})`), .3);
234 } },
226235 // pour along the shortest plan the rules' own search finds for each shelf: tap the jar to lift, then the jar to pour into
227236 'jam-jars': { over: /play again/, outcome: /Shelf done, you win: \d+ pours against a par of \d+/, beat: g => {
228237 if (g.read('P.status') !== 'playing') { g.run(.3); return; }
serve.test.mjs +7
@@ -685,6 +685,13 @@ test('Stained Glass and its rules script are served without a track', async () =
685685 expect((await fetch(base + '/stained-glass/window.js')).status).toBe(200);
686686 });
687687
688 test('Library Shelf and its rules script are served without a track', async () => {
689 const page = await fetch(base + '/library-shelf/');
690 expect(page.status).toBe(200);
691 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
692 expect((await fetch(base + '/library-shelf/shelf.js')).status).toBe(200);
693 });
694
688695 test('Jam Jars and its rules script are served without a track', async () => {
689696 const page = await fetch(base + '/jam-jars/');
690697 expect(page.status).toBe(200);
shell.js +1
@@ -67,6 +67,7 @@ window.PixelPlays = (() => {
6767 { id: 'rock-pool', title: 'Rock Pool', blurb: 'Scoop the darting crabs into your bucket before the tide comes back', kind: 'Catching', input: 'Tap', accent: '#3a8fa3', music: false, forged: true },
6868 { id: 'stained-glass', title: 'Stained Glass', blurb: 'Colour the window so no two neighbouring panes match', kind: 'Puzzle', input: 'Tap', accent: '#5a6fb8', music: false, forged: true },
6969 { id: 'jam-jars', title: 'Jam Jars', blurb: 'Pour the fruit between jars until every jar holds just one jam', kind: 'Puzzle', input: 'Tap', accent: '#b8324a', music: false, forged: true },
70 { id: 'library-shelf', title: 'Library Shelf', blurb: 'Slide the books along their runners to make room for the returned one', kind: 'Puzzle', input: 'Drag', accent: '#6b4a2e', music: false, forged: true },
7071 { id: 'conkers', title: 'Conkers', blurb: 'Time your swing to crack every rival conker in the playground', kind: 'Sport', input: 'Tap', accent: '#8a4b22', music: false, forged: true },
7172 ];
7273 const MUSIC_VOLUME = .4;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs