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

Migrated from github.com/amirmushichge/pixel-plays

Add Domino Run: set out a line of dominoes along a path, then tip the first #50

Closed opened this
Closed without merging

quill/pixel-plays:quill/31-add-domino-run-set-out-a-line-of-dominoe → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +744 −1
README.md +2 −1
@@ -27,6 +27,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
2727 | [Lighthouse](lighthouse/) | A 90-second night: sweep the lighthouse beam so boats drifting in towards the rocks are held in the light for a second and turn away, +1 each; three boats lost on the rocks end the night early (forged by the crew on the engine and shell above, not by the original creators) | Drag; hold left/right |
2828 | [Window Washer](window-washer/) | Five grimy windows, twelve seconds each: wipe the glass clean with a squeegee before the cradle drops a floor, bird droppings need two passes, score the percentage clean (forged by the crew on the engine and shell above, not by the original creators) | Drag; arrows + space |
2929 | [Market Scale](market-scale/) | Five customers, 15 seconds each: weigh fruit onto a hanging pan scale to match the weight on the chalk slate, exact scores 3 and within 50 g scores 1 (forged by the crew on the engine and shell above, not by the original creators) | Drag or tap fruit, tap the bell; arrows + enter, space |
30 | [Domino Run](domino-run/) | Twenty dominoes to stand along a curving chalk path in three courtyards, then tip the first: a gap too wide stops the chain, too close topples one early; ringing the bell scores 10 and each domino left over 1 more (forged by the crew on the engine and shell above, not by the original creators) | Tap the path, or arrows + space; tip first button or enter |
3031
3132 ## Run
3233 Requires [Node.js](https://nodejs.org/); nothing to install.
@@ -40,7 +41,7 @@ Then open http://127.0.0.1:5300/. `PORT` and `HOST` override the port and addres
4041 On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. The app keeps no state, so it does not need `FORGE_APP_DATA`. `bun test` checks that the server answers every game page and track.
4142
4243 ## Add a game
43 Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules })`, set `window.PP_SCENE`, load `../engine.js`, then add the game to `GAMES` in `shell.js` with a one-line `blurb`; the home page lists every `GAMES` entry (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too). The page needs a `#mute` button. Put its background track at `<id>/<id>.mp3`, or set `music: false` on its `GAMES` entry when it has none (Stone Skip, Kite Hill, Paper Route, Harbour Crane, Pizza Toss, Sled Run, Pottery Wheel, Row Home, Orchard, Lighthouse, Market Scale and Window Washer play on their own sound effects). Rules that need testing go in a plain script with a `.test.mjs` beside it, as in `kite-hill/model.js`.
44 Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules })`, set `window.PP_SCENE`, load `../engine.js`, then add the game to `GAMES` in `shell.js` with a one-line `blurb`; the home page lists every `GAMES` entry (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too). The page needs a `#mute` button. Put its background track at `<id>/<id>.mp3`, or set `music: false` on its `GAMES` entry when it has none (Stone Skip, Kite Hill, Paper Route, Harbour Crane, Pizza Toss, Sled Run, Pottery Wheel, Row Home, Orchard, Lighthouse, Market Scale, Window Washer and Domino Run play on their own sound effects). Rules that need testing go in a plain script with a `.test.mjs` beside it, as in `kite-hill/model.js`.
4445
4546 - `shell.js` provides the game menu, the Rules popup, the credits and the background music.
4647 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
domino-run/chain.js added +174
@@ -0,0 +1,174 @@
1 'use strict';
2 // Domino Run rules as plain data in, plain data out: the courtyard paths, standing a domino on a path, the gaps that
3 // make a chain stop or topple early, the chain falling in whole pixels, and the score. The page draws from this state.
4 // Distances are in "px": ten to a world unit on the page. An arc position `s` is whole px from the start of the path.
5 (function (root) {
6 const DOMINOES = 20;
7 const MIN_GAP = 6, MAX_GAP = 14; // closer than MIN_GAP falls over during setup, wider than MAX_GAP is out of reach
8 const REACH = MAX_GAP; // a falling domino's tip lands this far ahead of it
9 const SPEED = 70; // px per second the chain falls
10 const PATH_WIDTH = 18; // how far from the chalk a tap still counts: wide enough for a finger
11 const STRIDE = 10; // after one is stood, the cursor moves on to the middle of the good gap
12 const BELL_POINTS = 10, LEFT_POINTS = 1;
13 const RESULT_PAUSE = 2.2, STALL_PAUSE = .5;
14 const SQ = Math.SQRT1_2;
15 // each courtyard is a longer chalk path: a sine wave of `waves` swings across `span` px, `amp` px either side
16 const COURTYARDS = [
17 { name: 'Garden court', span: 150, amp: 18, waves: 1 },
18 { name: 'Fountain court', span: 170, amp: 18, waves: 1.5 },
19 { name: 'Bell court', span: 165, amp: 20, waves: 2 },
20 ];
21 const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
22
23 // the path of a courtyard resampled every whole px of arc: points[s] is where position s lies
24 const cache = [];
25 function pathOf(level) {
26 const index = clamp(Math.floor(level) || 0, 0, COURTYARDS.length - 1);
27 if (cache[index]) return cache[index];
28 const { span, amp, waves } = COURTYARDS[index], N = 4000, raw = [];
29 for (let k = 0; k <= N; k++) {
30 const t = k / N, u = -span / 2 + span * t, v = amp * Math.sin(2 * Math.PI * waves * t);
31 raw.push([(u + v) * SQ, (v - u) * SQ]); // screen-right/down to world axes, as the page draws them
32 }
33 const points = [raw[0]];
34 let walked = 0, want = 1;
35 for (let k = 1; k <= N; k++) {
36 const [ax, ay] = raw[k - 1], [bx, by] = raw[k], seg = Math.hypot(bx - ax, by - ay);
37 while (want <= walked + seg) {
38 const f = (want - walked) / seg;
39 points.push([ax + (bx - ax) * f, ay + (by - ay) * f]);
40 want++;
41 }
42 walked += seg;
43 }
44 return (cache[index] = { level: index, length: points.length - 1, points });
45 }
46 // x, y and the heading (radians in world axes) at arc position s
47 function pointAt(path, s) {
48 const i = clamp(Math.floor(s), 0, path.length - 1), f = clamp(s - i, 0, 1);
49 const a = path.points[i], b = path.points[i + 1] || a, back = path.points[Math.max(0, i - 1)], fwd = path.points[Math.min(path.length, i + 1)];
50 return { x: a[0] + (b[0] - a[0]) * f, y: a[1] + (b[1] - a[1]) * f, angle: Math.atan2(fwd[1] - back[1], fwd[0] - back[0]) };
51 }
52 // the whole-px position on the path closest to a world point, and how far off the chalk it is
53 function nearest(path, x, y) {
54 let best = 0, bestD = Infinity;
55 path.points.forEach(([px, py], s) => {
56 const d = Math.hypot(px - x, py - y);
57 if (d < bestD) { best = s; bestD = d; }
58 });
59 return { s: best, dist: bestD };
60 }
61
62 function newState(best = 0, level = 0) {
63 return {
64 phase: 'place', level, path: pathOf(level), hand: DOMINOES, dominoes: [],
65 front: 0, acc: 0, limit: 0, rung: false, timer: 0, points: 0, result: null,
66 score: 0, best, record: false, sel: 0,
67 };
68 }
69 const standing = s => s.dominoes.filter(d => !d.early).sort((a, b) => a.s - b.s);
70 // how a domino stood at s would sit among the ones already out: 'first', 'ok', 'close' or 'wide' (from its nearest standing neighbour)
71 function gapKind(state, s) {
72 const others = standing(state);
73 if (!others.length) return 'first';
74 let gap = Infinity;
75 for (const d of others) gap = Math.min(gap, Math.abs(d.s - s));
76 return gap < MIN_GAP ? 'close' : gap > MAX_GAP ? 'wide' : 'ok';
77 }
78 // stand a domino at s, facing along the path. Returns 'placed', 'toppled' (too close to a standing one, so it fell), or null when refused.
79 function place(state, s) {
80 if (state.phase !== 'place' || state.hand <= 0 || typeof s !== 'number' || !Number.isFinite(s)) return null;
81 s = Math.round(s);
82 if (s < 0 || s > state.path.length) return null;
83 const close = gapKind(state, s) === 'close';
84 const { x, y, angle } = pointAt(state.path, s);
85 state.dominoes.push({ s, x, y, angle, early: close });
86 state.hand--;
87 state.sel = clamp(s + STRIDE, 0, state.path.length);
88 return close ? 'toppled' : 'placed';
89 }
90 // take the last domino back, whether it stands or fell
91 function undo(state) {
92 if (state.phase !== 'place' || !state.dominoes.length) return false;
93 state.dominoes.pop();
94 state.hand++;
95 return true;
96 }
97 // slide the keyboard cursor along the path
98 function select(state, by) {
99 state.sel = clamp(Math.round(state.sel + by), 0, state.path.length);
100 return state.sel;
101 }
102 // where the chain would end: how far the falling tip gets, how many dominoes go down, and whether it reaches the bell at the path's end
103 function plan(state) {
104 const line = standing(state);
105 if (!line.length) return { limit: 0, fall: 0, reached: false };
106 let limit = line[0].s + REACH, fall = 1;
107 for (let k = 1; k < line.length; k++) {
108 if (line[k].s - line[k - 1].s > MAX_GAP) break;
109 limit = line[k].s + REACH;
110 fall++;
111 }
112 return { limit, fall, reached: limit >= state.path.length };
113 }
114 // tip the first standing domino; needs at least one
115 function start(state) {
116 if (state.phase !== 'place') return false;
117 const line = standing(state);
118 if (!line.length) return false;
119 state.phase = 'run';
120 state.front = line[0].s;
121 state.acc = 0;
122 state.limit = plan(state).limit;
123 return true;
124 }
125 // how far a domino has fallen, 0 standing to 1 flat
126 function tilt(state, d) {
127 if (d.early) return 1;
128 if (state.phase === 'place') return 0;
129 return clamp((state.front - d.s) / REACH, 0, 1);
130 }
131 function finish(state, rung) {
132 const points = rung ? BELL_POINTS + state.hand * LEFT_POINTS : 0;
133 state.rung = rung;
134 state.points = points;
135 state.score += points;
136 state.result = { rung, points, left: state.hand, fell: plan(state).fall };
137 state.phase = 'result';
138 state.timer = 0;
139 }
140 function advance(state) {
141 if (state.level + 1 >= COURTYARDS.length) {
142 state.phase = 'over';
143 state.timer = 0;
144 state.record = state.score > state.best;
145 if (state.record) state.best = state.score;
146 return;
147 }
148 const keep = { score: state.score, best: state.best };
149 Object.assign(state, newState(keep.best, state.level + 1), { score: keep.score });
150 }
151 // the chain falls at SPEED, always in whole px; a result waits a moment and moves on to the next courtyard
152 function step(state, dt) {
153 if (state.phase === 'run') {
154 state.acc += SPEED * dt;
155 const whole = Math.floor(state.acc);
156 state.acc -= whole;
157 state.front = Math.min(state.front + whole, state.limit);
158 if (state.front >= state.path.length) finish(state, true);
159 else if (state.front >= state.limit) { state.timer += dt; if (state.timer >= STALL_PAUSE) finish(state, false); }
160 } else if (state.phase === 'result') {
161 state.timer += dt;
162 if (state.timer >= RESULT_PAUSE) advance(state);
163 } else if (state.phase === 'over') state.timer += dt;
164 }
165 const skip = state => { if (state.phase === 'result') advance(state); };
166 const restart = state => Object.assign(state, newState(state.best, 0));
167
168 const api = {
169 DOMINOES, MIN_GAP, MAX_GAP, REACH, SPEED, PATH_WIDTH, STRIDE, BELL_POINTS, LEFT_POINTS, COURTYARDS,
170 pathOf, pointAt, nearest, newState, gapKind, place, undo, select, plan, start, tilt, step, skip, restart,
171 };
172 if (typeof module !== 'undefined' && module.exports) module.exports = api;
173 else root.DominoRun = api;
174 })(typeof window !== 'undefined' ? window : globalThis);
domino-run/chain.test.mjs added +154
@@ -0,0 +1,154 @@
1 import { test, expect } from 'bun:test';
2 import { createRequire } from 'node:module';
3
4 const D = createRequire(import.meta.url)('./chain.js');
5 const run = (s, seconds = 20) => { for (let i = 0; i < Math.round(seconds * 60) && s.phase === 'run'; i++) D.step(s, 1 / 60); return s; };
6 // stand dominoes at the given positions, then tip the first
7 const lay = (positions, level = 0) => { const s = D.newState(0, level); positions.forEach(p => D.place(s, p)); return s; };
8 const every = (from, gap, count) => Array.from({ length: count }, (_, i) => from + i * gap);
9
10 test('the courtyards get longer and the last is still reachable with 20 dominoes', () => {
11 const lengths = D.COURTYARDS.map((_, i) => D.pathOf(i).length);
12 expect(lengths[0]).toBeLessThan(lengths[1]);
13 expect(lengths[1]).toBeLessThan(lengths[2]);
14 expect(lengths[2]).toBeLessThanOrEqual(D.DOMINOES * D.MAX_GAP);
15 });
16
17 test('a domino stands on the path facing along it', () => {
18 const s = D.newState();
19 expect(D.place(s, 40)).toBe('placed');
20 const d = s.dominoes[0], here = D.pointAt(s.path, 40), ahead = D.pointAt(s.path, 41), back = D.pointAt(s.path, 39);
21 expect(d).toMatchObject({ s: 40, x: here.x, y: here.y, early: false });
22 expect(d.angle).toBeCloseTo(Math.atan2(ahead.y - back.y, ahead.x - back.x), 2);
23 expect(s.hand).toBe(D.DOMINOES - 1);
24 });
25
26 test('placing is refused off the path, with none left, and once the chain runs', () => {
27 const s = D.newState();
28 expect(D.place(s, -1)).toBe(null);
29 expect(D.place(s, s.path.length + 1)).toBe(null);
30 expect(D.place(s, NaN)).toBe(null);
31 expect(D.place(s, '5')).toBe(null);
32 expect(s.dominoes.length).toBe(0);
33 const full = lay(every(0, 8, D.DOMINOES));
34 expect(D.place(full, 170)).toBe(null);
35 const running = lay([10]);
36 D.start(running);
37 expect(D.place(running, 30)).toBe(null);
38 });
39
40 test('nearest finds the position of a point on the chalk and how far off it is', () => {
41 const path = D.pathOf(0), p = D.pointAt(path, 80);
42 expect(D.nearest(path, p.x, p.y)).toEqual({ s: 80, dist: expect.any(Number) });
43 expect(D.nearest(path, p.x, p.y).dist).toBeLessThan(1);
44 expect(D.nearest(path, p.x + 200, p.y + 200).dist).toBeGreaterThan(D.PATH_WIDTH);
45 });
46
47 test('evenly spaced dominoes ring the bell and score 10 plus one per domino left over', () => {
48 const s = lay(every(5, 10, 16));
49 expect(D.plan(s)).toMatchObject({ reached: true, fall: 16 });
50 expect(D.start(s)).toBe(true);
51 run(s);
52 expect(s.phase).toBe('result');
53 expect(s.result).toMatchObject({ rung: true, points: D.BELL_POINTS + 4, left: 4 });
54 expect(s.score).toBe(14);
55 });
56
57 test('one gap too wide stops the chain there and the bell stays silent', () => {
58 const s = lay([...every(5, 10, 8), ...every(5 + 7 * 10 + D.MAX_GAP + 1, 10, 6)]);
59 const stop = 5 + 7 * 10;
60 expect(D.plan(s)).toMatchObject({ reached: false, fall: 8, limit: stop + D.REACH });
61 D.start(s);
62 run(s);
63 expect(s.result).toMatchObject({ rung: false, points: 0, fell: 8 });
64 expect(s.front).toBe(stop + D.REACH);
65 expect(s.score).toBe(0);
66 const tail = s.dominoes.filter(d => d.s > stop);
67 expect(tail.every(d => D.tilt(s, d) === 0)).toBe(true);
68 });
69
70 test('a gap of exactly the reach still carries the chain', () => {
71 const s = lay(every(0, D.MAX_GAP, 12));
72 expect(D.plan(s).fall).toBe(12);
73 });
74
75 test('a domino placed too close falls during setup and is left out of the chain', () => {
76 const s = lay([20, 30]);
77 expect(D.gapKind(s, 30 + D.MIN_GAP - 1)).toBe('close');
78 expect(D.place(s, 30 + D.MIN_GAP - 1)).toBe('toppled');
79 const fallen = s.dominoes[2];
80 expect(fallen.early).toBe(true);
81 expect(D.tilt(s, fallen)).toBe(1);
82 expect(s.hand).toBe(D.DOMINOES - 3);
83 expect(D.plan(s).fall).toBe(2);
84 expect(D.place(s, 30 + D.MIN_GAP)).toBe('placed');
85 expect(D.plan(s).fall).toBe(3);
86 });
87
88 test('the gap marker reads first, ok, close and wide', () => {
89 const s = D.newState();
90 expect(D.gapKind(s, 10)).toBe('first');
91 D.place(s, 10);
92 expect(D.gapKind(s, 10 + D.MIN_GAP)).toBe('ok');
93 expect(D.gapKind(s, 10 + D.MAX_GAP)).toBe('ok');
94 expect(D.gapKind(s, 10 + D.MAX_GAP + 1)).toBe('wide');
95 expect(D.gapKind(s, 12)).toBe('close');
96 });
97
98 test('the chain falls in whole pixels and the first domino cannot start without one standing', () => {
99 const empty = D.newState();
100 expect(D.start(empty)).toBe(false);
101 const s = lay(every(5, 10, 16));
102 D.start(s);
103 const seen = new Set();
104 for (let i = 0; i < 200 && s.phase === 'run'; i++) { D.step(s, 1 / 60); seen.add(s.front); expect(Number.isInteger(s.front)).toBe(true); }
105 expect(seen.size).toBeGreaterThan(20);
106 });
107
108 test('undo takes back the last domino, even one that fell', () => {
109 const s = lay([20, 22]);
110 expect(D.undo(s)).toBe(true);
111 expect(s.hand).toBe(D.DOMINOES - 1);
112 expect(D.plan(s).fall).toBe(1);
113 expect(D.undo(D.newState())).toBe(false);
114 });
115
116 test('a result moves on to a longer courtyard, a miss scores nothing, and the third ends the round with a best', () => {
117 const s = D.newState(3);
118 const cleared = level => {
119 const n = Math.ceil(D.pathOf(level).length / 12);
120 every(0, 12, n).forEach(p => D.place(s, p));
121 D.start(s);
122 run(s);
123 };
124 cleared(0);
125 expect(s.result.rung).toBe(true);
126 D.skip(s);
127 expect(s).toMatchObject({ phase: 'place', level: 1, hand: D.DOMINOES, dominoes: [] });
128 D.place(s, 10); D.start(s); run(s);
129 expect(s.result.rung).toBe(false);
130 D.step(s, 5);
131 expect(s.level).toBe(2);
132 expect(s.score).toBe(D.BELL_POINTS + D.DOMINOES - Math.ceil(D.pathOf(0).length / 12));
133 cleared(2);
134 D.skip(s);
135 expect(s.phase).toBe('over');
136 expect(s.best).toBe(s.score);
137 expect(s.record).toBe(true);
138 D.restart(s);
139 expect(s).toMatchObject({ phase: 'place', level: 0, score: 0, best: s.best });
140 });
141
142 test('after a domino the cursor moves on to the middle of the good gap', () => {
143 const s = D.newState();
144 D.place(s, 30);
145 expect(s.sel).toBe(30 + D.STRIDE);
146 expect(D.gapKind(s, s.sel)).toBe('ok');
147 });
148
149 test('the keyboard cursor stays on the path', () => {
150 const s = D.newState();
151 expect(D.select(s, -5)).toBe(0);
152 expect(D.select(s, 3)).toBe(3);
153 expect(D.select(s, 1000)).toBe(s.path.length);
154 });
domino-run/index.html added +405
@@ -0,0 +1,405 @@
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>Domino Run</title>
7 <style>
8 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; }
9 * { box-sizing: border-box; }
10 html, body { height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
11 body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; }
12 #stage { position: fixed; inset: 0; display: grid; place-items: center; }
13 canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; outline: none; }
14 .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; gap: 16px; pointer-events: none; }
15 #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; }
16 #scores b { font-size: 16px; font-weight: 600; font-variant-numeric: tabular-nums; min-width: 5ch; }
17 #scores span { color: var(--muted); font-variant-numeric: tabular-nums; min-height: 1.35em; }
18 #bottom { bottom: max(14px, env(safe-area-inset-bottom)); align-items: flex-end; }
19 #notes { display: grid; gap: 2px; }
20 #notes span { color: var(--muted); min-height: 1.35em; }
21 #actions { display: flex; gap: 22px; align-items: flex-end; }
22 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
23 button:hover, button:focus-visible { color: var(--ink); }
24 #start { color: var(--ink); font-weight: 600; }
25 button:disabled { color: var(--muted); opacity: .45; cursor: default; }
26 </style>
27 </head>
28 <body>
29 <div id="stage"><canvas id="c" tabindex="0" aria-label="Domino Run. Tap the chalk path to stand a domino there, facing along it; or press left and right arrows to move along the path and space to stand one. Keep each gap inside the green stretch, then press the tip first button or enter to knock over the first domino and ring the bell. Twenty dominoes, three courtyards."></canvas></div>
30 <div id="scores"><b id="score">0</b><span id="meta"></span></div>
31 <div class="hud" id="bottom">
32 <div id="notes"><span id="status" role="status" aria-live="polite"></span><span>green chalk is the gap to aim for</span></div>
33 <div id="actions">
34 <button id="undo" type="button">undo</button>
35 <button id="start" type="button">tip first</button>
36 <button id="mute" type="button" aria-pressed="false">sound on</button>
37 </div>
38 </div>
39 <script src="../shell.js"></script>
40 <script>
41 PixelPlays.mount({
42 id: 'domino-run',
43 rules: [
44 'Tap the chalk path, or use arrows and space, to stand a domino facing along it. You have 20.',
45 'Keep gaps inside the green stretch: too wide stops the chain, too close and it topples early.',
46 'Press tip first to knock over the first one. Ringing the bell scores 10, plus 1 per domino left.',
47 'Three courtyards, each with a longer path.',
48 ],
49 });
50 </script>
51 <script>window.PP_SCENE = { originY: 14, shadowX: 1.1, shadowY: -.3 };</script>
52 <script src="../engine.js"></script>
53 <script src="chain.js"></script>
54 <script>
55 'use strict';
56
57 const BEST_KEY = 'pixel-plays-domino-run-best';
58 const HALF = 11, SQ = Math.SQRT1_2;
59 const TILE = [[[206, 168, 132], [214, 178, 142], [222, 188, 152], [230, 200, 164]], [[190, 156, 128], [198, 166, 138], [208, 176, 148], [216, 188, 160]]];
60 const GROUT = [164, 130, 104];
61 const CHALK = rgb(246, 242, 228), CHALK_DARK = rgb(214, 208, 190);
62 const STONE = [198, 194, 186], WATER = [92, 168, 214], WOOD = [168, 120, 78], WOOD_DARK = [112, 78, 54];
63 const TRUNK = [128, 96, 70], FROND = [54, 124, 72], FROND_LIGHT = [96, 164, 82], BRASS = [232, 178, 62], BRASS_LIGHT = [244, 204, 100];
64 const IVORY = [244, 238, 218], PIP = [40, 38, 46];
65 const GOOD = rgb(52, 196, 104), WIDE = rgb(244, 168, 40), CLOSE = rgb(228, 68, 56), FIRST = rgb(72, 140, 232);
66 const DOM_H = 1.4, DOM_W = .8; // world units; a falling domino's tip lands DOM_H ahead, as REACH says
67 const FOUNTAIN = { u: 2, v: -5.6 }, PALMS = [[-10, -3.5, 1.15], [10, -3.6, 1], [-3.8, -7.6, .9], [-10.2, 3.8, .9]];
68 // screen-axis offsets (right, down) to world axes
69 const uv = (du, dv) => [(du + dv) * SQ, (dv - du) * SQ];
70 const world = s => { const p = DominoRun.pointAt(G.path, s); return { x: p.x / 10, y: p.y / 10, angle: p.angle }; };
71
72 /* ---------- state ---------- */
73 const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })();
74 let G = DominoRun.newState(best0), time = 0, status = '', ringT = 9, lastPhase = 'place', lastFallen = 0, level = -1, kb = false, hover = false;
75 const born = new WeakMap(); // when each domino was stood, so one that topples early can be seen to fall
76 const nodes = { score: document.getElementById('score'), meta: document.getElementById('meta'), status: document.getElementById('status') };
77 const startButton = document.getElementById('start'), undoButton = document.getElementById('undo');
78
79 /* ---------- ground ---------- */
80 function stamp(mask, x, y, r, ring) { // chalk a disc (or a ring) onto the screen mask around a world point
81 const p = project(x, y, 0), rx = r * S * 1.05, ry = r * S * SIN * 1.1 + 1;
82 for (let iy = Math.max(0, Math.floor(p.sy - ry)); iy <= Math.min(H - 1, Math.ceil(p.sy + ry)); iy++) {
83 for (let ix = Math.max(0, Math.floor(p.sx - rx)); ix <= Math.min(W - 1, Math.ceil(p.sx + rx)); ix++) {
84 const g = unproject(ix + .5, iy + .5), d = Math.hypot(g.x - x, g.y - y);
85 if (ring ? d >= r * .72 && d <= r : d <= r) mask[iy * W + ix] = 1;
86 }
87 }
88 }
89 function chalkMask() {
90 const mask = new Uint8Array(W * H), path = G.path;
91 for (let s = 0; s <= path.length; s += .5) { const w = world(s); stamp(mask, w.x, w.y, .6, false); }
92 const a = world(0);
93 stamp(mask, a.x, a.y, 1.15, true);
94 return mask;
95 }
96 function groundColor(x, y, ix, iy, mask) {
97 const edge = Math.pow(Math.pow(Math.abs(x) / HALF, 4) + Math.pow(Math.abs(y) / HALF, 4), .25);
98 const rough = edge + (noise(x * 1.3, y * 1.3) - .5) * .1;
99 if (rough > 1.04) return 0;
100 if (rough > .94 && hash(ix, iy) < (rough - .94) / .1) return 0;
101 const i = iy * W + ix;
102 if (mask[i] && hash(ix * 3, iy * 7) > .1) return hash(ix, iy) > .8 ? CHALK_DARK : CHALK;
103 const tx = (x + 40) / 2.2, ty = (y + 40) / 2.2, fx = tx - Math.floor(tx), fy = ty - Math.floor(ty);
104 if (fx < .07 || fy < .07) return rgb(...GROUT);
105 const tone = TILE[(Math.floor(tx) + Math.floor(ty)) & 1];
106 const t = noise(x * .9, y * .9) * 1.1 + (hash(ix, iy) - .5) * .45 + (1 - edge) * .12 - .08;
107 return rgb(...tone[clamp(Math.floor(t * 4.2), 0, 3)]);
108 }
109
110 /* ---------- baked scenery ---------- */
111 function fountain() {
112 const [fx, fy] = uv(FOUNTAIN.u, FOUNTAIN.v), R = 1.8;
113 for (let t = -R; t <= R; t += .3) { // water, in rows
114 const half = Math.sqrt(Math.max(0, R * R - t * t)), [ax, ay] = uv(-half, t), [bx, by] = uv(half, t);
115 capsule([fx + ax, fy + ay, .3], [fx + bx, fy + by, .3], .2, .2, () => WATER, 'solid');
116 }
117 for (let k = 0; k < 36; k++) { // the stone rim
118 const a = k / 36 * Math.PI * 2, [dx, dy] = uv(Math.cos(a) * R, Math.sin(a) * R);
119 sphere(fx + dx, fy + dy, .38, .3, STONE, 'rough');
120 }
121 capsule([fx, fy, .3], [fx, fy, 1.8], .3, .2, () => STONE, 'rough');
122 sphere(fx, fy, 1.95, .5, STONE, 'rough');
123 sphere(fx, fy, 2.35, .2, WATER, 'solid');
124 castShadow(fx, fy, 2, 1.4, 1, .2);
125 for (let a = 0; a < 6.3; a += .8) castShadow(fx + Math.cos(a) * R * .9, fy + Math.sin(a) * R * .9, .5, .5, 1, .3);
126 }
127 function bellStool() {
128 const w = world(G.path.length);
129 box(w.x - .8, w.y - .8, 0, w.x + .8, w.y + .8, 1.4, WOOD, 11);
130 castShadow(w.x, w.y, 1.4, 1.2, 1, .2);
131 }
132 function growPalm(x, y, scale, seed) {
133 const lean = hash(seed, 3) * .8 - .4, top = [x + lean * scale, y - lean * .5 * scale, 4.2 * scale];
134 let prev = [x, y, 0];
135 for (let k = 1; k <= 6; k++) { // a curved ringed trunk
136 const t = k / 6, p = [x + lean * scale * t * t, y - lean * .5 * scale * t * t, 4.2 * scale * t];
137 capsule(prev, p, .3 * scale * (1.1 - t * .4), .3 * scale * (1.1 - (k / 6 + .17) * .4), () => TRUNK, 'rough');
138 prev = p;
139 }
140 for (let z = 0; z <= 4; z += .6) castShadow(x, y, z * scale, .28, 1, 0);
141 for (let f = 0; f < 8; f++) { // fronds, each a row of leaf pieces that droop outwards
142 const a = f / 8 * Math.PI * 2 + hash(seed, f) * .5, cx = Math.cos(a), cy = Math.sin(a);
143 for (let j = 1; j <= 6; j++) {
144 const out = j * .42 * scale, lift = (Math.sin(j / 6 * 2.2) * .9 - j * j * .035) * scale;
145 const px = top[0] + cx * out, py = top[1] + cy * out, pz = top[2] + .25 * scale + lift;
146 for (const side of [-1, 1]) {
147 const k = seed * 100 + f * 10 + j + (side > 0 ? 50 : 0);
148 capture = [];
149 const sx = px - cy * side * .16 * scale * Math.min(j, 3), sy = py + cx * side * .16 * scale * Math.min(j, 3);
150 sphere(sx, sy, pz - Math.min(j, 3) * .04, .22 * scale, hash(k, 5) > .5 ? FROND : FROND_LIGHT, 'rough');
151 leaves.push({ x: sx, y: sy, z: pz, k, r: .3 * scale, reach: .35 + j * .13, pixels: capture });
152 capture = null;
153 }
154 }
155 }
156 }
157 function bake() {
158 leaves.length = 0;
159 ground.fill(0); shadowMask.fill(0); staticShadow.fill(0);
160 zb.fill(-1e9);
161 pix.fill(rgb(255, 255, 255));
162 const mask = chalkMask();
163 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
164 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy, mask);
165 if (!c) continue;
166 pix[i] = c; ground[i] = 1;
167 zb[i] = (g.x + g.y) / R2 * COS;
168 }
169 groundZ.set(zb);
170 fountain();
171 bellStool();
172 PALMS.forEach(([u, v, scale], n) => { const [x, y] = uv(u, v); growPalm(x, y, scale, n + 1); });
173 bakeOcclusion();
174 staticShadow.set(shadowMask);
175 applyShadows(groundZ);
176 bakedPix.set(pix);
177 bakedZ.set(zb);
178 level = G.level;
179 }
180
181 /* ---------- hud ---------- */
182 let shown = '';
183 function renderHud() {
184 const standing = G.dominoes.some(d => !d.early);
185 const text = [G.score, G.best, G.level, G.hand, G.phase, standing].join('|');
186 if (text === shown) return;
187 shown = text;
188 nodes.score.textContent = String(G.score);
189 const parts = [];
190 if (G.best) parts.push('best ' + G.best);
191 if (G.phase !== 'over') parts.push('courtyard ' + (G.level + 1) + '/' + DominoRun.COURTYARDS.length, G.hand + ' left');
192 nodes.meta.textContent = parts.join(' · ');
193 startButton.disabled = G.phase !== 'place' || !standing;
194 undoButton.disabled = G.phase !== 'place' || !G.dominoes.length;
195 }
196 function setStatus(text) {
197 if (text === status) return;
198 status = text;
199 nodes.status.textContent = text;
200 }
201 function statusFor() {
202 const name = DominoRun.COURTYARDS[G.level].name;
203 if (G.phase === 'place') return G.hand ? name + ' · stand dominoes along the chalk, then tip first' : name + ' · all out, tip first';
204 if (G.phase === 'run') return 'falling…';
205 if (G.phase === 'result') return G.result.rung ? 'bell rung · +' + DominoRun.BELL_POINTS + ' and ' + G.result.left + ' left over = +' + G.result.points : 'the chain stopped after ' + G.result.fell + ' · +0';
206 return G.score + ' points' + (G.record ? ' · new best' : '') + ' · tap to play again';
207 }
208
209 /* ---------- actions ---------- */
210 function put(s) {
211 ensureAudio();
212 const how = DominoRun.place(G, s);
213 if (how) { born.set(G.dominoes[G.dominoes.length - 1], time); sound(how === 'toppled' ? 'topple' : 'click'); }
214 }
215 function tip() {
216 ensureAudio();
217 if (DominoRun.start(G)) lastFallen = 0;
218 }
219 function back() {
220 ensureAudio();
221 if (DominoRun.undo(G)) sound('click');
222 }
223 function next() { // tap or space outside the placing phase
224 ensureAudio();
225 if (G.phase === 'result') DominoRun.skip(G);
226 else if (G.phase === 'over' && G.timer > .8) DominoRun.restart(G);
227 }
228 function update(dt) {
229 time += dt;
230 ringT += dt;
231 DominoRun.step(G, dt);
232 if (G.level !== level) bake();
233 if (G.phase === 'run' || G.phase === 'result') {
234 const fallen = G.dominoes.filter(d => !d.early && DominoRun.tilt(G, d) > 0).length;
235 if (fallen > lastFallen) sound('clack');
236 lastFallen = fallen;
237 }
238 if (G.phase !== lastPhase) {
239 if (G.phase === 'result') { if (G.result.rung) { ringT = 0; sound('bell'); } else sound('miss'); }
240 if (G.phase === 'over' && G.record) try { localStorage.setItem(BEST_KEY, String(G.best)); } catch (e) { /* private window: keep it for this visit */ }
241 lastPhase = G.phase;
242 }
243 setStatus(statusFor());
244 renderHud();
245 }
246
247 /* ---------- drawing ---------- */
248 function drawDomino(d) {
249 const w = world(d.s), hx = Math.cos(w.angle), hy = Math.sin(w.angle), lx = -hy, ly = hx;
250 let p = DominoRun.tilt(G, d);
251 if (d.early) p = ease(clamp((time - (born.get(d) ?? -9)) / .3, 0, 1));
252 // tipping about the front foot: the base slides back and the top swings ahead along the path
253 const th = p * (Math.PI / 2 - .12), c = Math.cos(th), sn = Math.sin(th), r = .17;
254 const foot = [.15 - .15 * c, r + .15 * sn], top = [.15 - .15 * c + DOM_H * sn, r + .15 * sn + DOM_H * c];
255 const pieces = 12;
256 for (const side of [-1.5, -.5, .5, 1.5]) {
257 const off = side * DOM_W / 4;
258 for (let q = 0; q <= pieces; q++) {
259 const t = q / pieces, a = foot[0] + (top[0] - foot[0]) * t, z = foot[1] + (top[1] - foot[1]) * t;
260 sphere(w.x + hx * a + lx * off, w.y + hy * a + ly * off, z, r, Math.abs(t - .5) < .09 ? PIP : IVORY, 'solid');
261 }
262 }
263 for (let t = 0; t <= 1; t += .5) {
264 const a = foot[0] + (top[0] - foot[0]) * t;
265 castShadow(w.x + hx * a, w.y + hy * a, foot[1] + (top[1] - foot[1]) * t, .3, 1, 0);
266 }
267 }
268 function drawBell() {
269 const w = world(G.path.length), press = ringT < .4 ? .2 * Math.cos(ringT * 40) : 0;
270 sphere(w.x, w.y, 1.4 + .2 + press, .8, BRASS, 'solid');
271 capsule([w.x - .8, w.y + .8, 1.4], [w.x + .8, w.y - .8, 1.4], .13, .13, () => BRASS_LIGHT, 'solid');
272 sphere(w.x, w.y, 1.4 + 1.05 + press, .2, BRASS_LIGHT, 'solid');
273 castShadow(w.x, w.y, 1.8, .8, 1, .2);
274 }
275
276 /* ---------- 2D overlays ---------- */
277 function px(x, y, color) {
278 if (x >= 0 && y >= 0 && x < W && y < H) pix[y * W + x] = color;
279 }
280 const onScreen = s => { const w = world(s), p = project(w.x, w.y, 0); return [Math.round(p.sx), Math.round(p.sy)]; };
281 function dotsFor(from, to) {
282 const out = [];
283 for (let s = from; s <= to; s += .5) { const [x, y] = onScreen(s); out.push([x, y], [x + 1, y]); }
284 return out;
285 }
286 function drawGap() { // the stretch of path where the next domino keeps the chain going
287 const last = [...G.dominoes].reverse().find(d => !d.early);
288 if (!last) return;
289 const from = last.s + DominoRun.MIN_GAP, to = Math.min(G.path.length, last.s + DominoRun.MAX_GAP);
290 if (to < from) return;
291 const dots = dotsFor(from, to);
292 haloDots(dots);
293 drawDots(dots, GOOD);
294 }
295 function drawCursor() {
296 const kind = DominoRun.gapKind(G, G.sel), color = { first: FIRST, ok: GOOD, close: CLOSE, wide: WIDE }[kind];
297 const [x, y] = onScreen(G.sel), ring = [];
298 for (let k = 0; k < 16; k++) ring.push([Math.round(x + Math.cos(k * Math.PI / 8) * 5), Math.round(y + Math.sin(k * Math.PI / 8) * 3)]);
299 haloDots(ring);
300 drawDots(ring, color);
301 if (kb) drawArrow(x, y - 4, time);
302 }
303 function draw() {
304 pix.set(bakedPix);
305 zb.set(bakedZ);
306 const windT = STILL ? 0 : Math.floor(time * WIND_FPS) / WIND_FPS;
307 drawBell();
308 [...G.dominoes].sort((a, b) => a.s - b.s).forEach(drawDomino);
309 drawLeaves(windT);
310 applyShadows(bakedZ);
311 shadeEdges();
312 if (G.phase === 'place') { drawGap(); if (G.hand && (kb || hover)) drawCursor(); }
313 ctx.putImageData(image, 0, 0);
314 }
315
316 /* ---------- input ---------- */
317 const at = e => {
318 const box = canvas.getBoundingClientRect();
319 return { sx: (e.clientX - box.left) * W / box.width, sy: (e.clientY - box.top) * H / box.height };
320 };
321 // the path position under a screen point, or -1 when it is nowhere near the chalk
322 function pathAt(p) {
323 const g = unproject(p.sx, p.sy), hit = DominoRun.nearest(G.path, g.x * 10, g.y * 10);
324 return hit.dist <= DominoRun.PATH_WIDTH ? hit.s : -1;
325 }
326 canvas.addEventListener('pointerdown', e => {
327 canvas.focus({ preventScroll: true });
328 kb = false;
329 if (G.phase !== 'place') { next(); return; }
330 const s = pathAt(at(e));
331 if (s >= 0) put(s);
332 });
333 canvas.addEventListener('pointermove', e => {
334 if (G.phase !== 'place' || e.pointerType === 'touch') return;
335 const s = pathAt(at(e));
336 hover = s >= 0;
337 if (hover) { G.sel = s; kb = false; }
338 });
339 canvas.addEventListener('pointerleave', () => { hover = false; });
340 canvas.addEventListener('keydown', e => {
341 const by = { ArrowRight: 2, ArrowDown: 2, ArrowLeft: -2, ArrowUp: -2 }[e.key];
342 if (by) { e.preventDefault(); kb = true; if (G.phase === 'place') DominoRun.select(G, e.shiftKey ? by * 3 : by); return; }
343 if (e.key === ' ') { e.preventDefault(); if (e.repeat) return; kb = true; if (G.phase === 'place') put(G.sel); else next(); return; }
344 if (e.key === 'Enter') { e.preventDefault(); if (e.repeat) return; if (G.phase === 'place') tip(); else next(); return; }
345 if (e.key === 'Backspace' || e.key === 'z') { e.preventDefault(); back(); }
346 });
347 startButton.addEventListener('click', () => { tip(); canvas.focus({ preventScroll: true }); });
348 undoButton.addEventListener('click', () => { back(); canvas.focus({ preventScroll: true }); });
349
350 /* ---------- sound ---------- */
351 let audio = null, muted = false;
352 function ensureAudio() {
353 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
354 const AC = window.AudioContext || window.webkitAudioContext;
355 if (AC) audio = new AC();
356 }
357 function tone(type, from, to, len, vol) {
358 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
359 osc.type = type;
360 osc.frequency.setValueAtTime(from, now);
361 osc.frequency.exponentialRampToValueAtTime(to, now + len);
362 gain.gain.setValueAtTime(vol, now);
363 gain.gain.exponentialRampToValueAtTime(.0005, now + len);
364 osc.connect(gain).connect(audio.destination);
365 osc.start(now); osc.stop(now + len + .01);
366 }
367 function sound(kind) {
368 if (!audio || muted) return;
369 if (kind === 'click') tone('square', 520, 380, .05, .05);
370 else if (kind === 'clack') tone('triangle', 340 + Math.random() * 80, 160, .07, .12);
371 else if (kind === 'topple') tone('triangle', 300, 110, .16, .14);
372 else if (kind === 'bell') { tone('sine', 1320, 1300, .6, .18); tone('sine', 1980, 1960, .4, .06); }
373 else if (kind === 'miss') tone('triangle', 260, 130, .3, .14);
374 }
375 const muteButton = document.getElementById('mute');
376 muteButton.addEventListener('click', () => {
377 muted = !muted;
378 muteButton.textContent = muted ? 'sound off' : 'sound on';
379 muteButton.setAttribute('aria-pressed', String(muted));
380 });
381
382 /* ---------- boot ---------- */
383 function fit() {
384 const dpr = window.devicePixelRatio || 1;
385 const fitScale = Math.min(innerWidth / W, (innerHeight - 40) / H);
386 const scale = Math.max(1, Math.floor(fitScale * dpr)) / dpr;
387 canvas.style.width = W * scale + 'px';
388 canvas.style.height = H * scale + 'px';
389 }
390 addEventListener('resize', fit);
391 fit();
392 bake();
393 setStatus(statusFor());
394 renderHud();
395 let last = performance.now();
396 function frame(now) {
397 update(Math.min(.04, (now - last) / 1000));
398 last = now;
399 draw();
400 requestAnimationFrame(frame);
401 }
402 requestAnimationFrame(frame);
403 </script>
404 </body>
405 </html>
index.html +1
@@ -42,6 +42,7 @@ footer a { display: inline; padding: 0; font-weight: inherit; text-decoration: u
4242 <li><a href="lighthouse/">Lighthouse</a><span>Sweep the lighthouse beam to turn boats away from the rocks: hold one in the light for a second, three wrecks end the night</span><span>Game forged by the crew</span></li>
4343 <li><a href="window-washer/">Window Washer</a><span>Squeegee a grimy window clean before the cradle drops a floor: drag across it, bird droppings need two passes</span><span>Game forged by the crew</span></li>
4444 <li><a href="market-scale/">Market Scale</a><span>Weigh fruit onto a hanging pan scale to match each order: exact scores 3, within 50 g scores 1</span><span>Game forged by the crew</span></li>
45 <li><a href="domino-run/">Domino Run</a><span>Set out a line of 20 dominoes along a chalk path and tip the first: a gap too wide stops the chain, too close topples one early, ring the bell for 10 plus 1 per domino left</span><span>Game forged by the crew</span></li>
4546 </ul>
4647 <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.</footer>
4748 </main>
serve.test.mjs +7
@@ -148,3 +148,10 @@ test('Market Scale and its rules script are served without a track', async () =>
148148 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
149149 expect((await fetch(base + '/market-scale/scale.js')).status).toBe(200);
150150 });
151
152 test('Domino Run and its rules script are served without a track', async () => {
153 const page = await fetch(base + '/domino-run/');
154 expect(page.status).toBe(200);
155 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
156 expect((await fetch(base + '/domino-run/chain.js')).status).toBe(200);
157 });
shell.js +1
@@ -21,6 +21,7 @@ window.PixelPlays = (() => {
2121 { id: 'lighthouse', title: 'Lighthouse', blurb: 'Sweep the lighthouse beam to turn boats away from the rocks: hold one in the light for a second, three wrecks end the night', music: false, forged: true },
2222 { id: 'window-washer', title: 'Window Washer', blurb: 'Squeegee a grimy window clean before the cradle drops a floor: drag across it, bird droppings need two passes', music: false, forged: true },
2323 { id: 'market-scale', title: 'Market Scale', blurb: 'Weigh fruit onto a hanging pan scale to match each order: exact scores 3, within 50 g scores 1', music: false, forged: true },
24 { id: 'domino-run', title: 'Domino Run', blurb: 'Set out a line of 20 dominoes along a chalk path and tip the first: a gap too wide stops the chain, too close topples one early, ring the bell for 10 plus 1 per domino left', music: false, forged: true },
2425 ];
2526 const MUSIC_VOLUME = .4;
2627 const CREDITS = [

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs