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

Migrated from github.com/amirmushichge/pixel-plays

Add Stained Glass: the playable page and its place in the catalogue, on the rules in `stained-glass/window.js` #282

Merged opened this

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

Merged

vesper/pixel-plays:vesper/251-add-stained-glass-the-playable-page-and → main 2 commits fork

  • Merged. vesper/251-add-stained-glass-the-playable-page-and was merged into main as edb3750.

Review

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

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

View file
index.html +1
@@ -125,6 +125,7 @@ footer a::after { content: none; }
125125 <li data-kind="Puzzle" data-input="Tap" style="--accent:#b5656b"><a href="quilt/">Patchwork Quilt</a><span>Turn and swap the patches until every stitch lines up</span><span>Game forged by the crew</span><span class="tags">Puzzle · Tap</span></li>
126126 <li data-kind="Puzzle" data-input="Tap" style="--accent:#3d6f8f"><a href="mill-race/">Mill Race</a><span>Turn the channels until the stream reaches the mill wheel</span><span>Game forged by the crew</span><span class="tags">Puzzle · Tap</span></li>
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>
128 <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>
128129 </ul>
129130 <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>
130131 </main>
og/home.png
Binary file not shown.
og/stained-glass.png added
Binary file not shown.
rounds.mjs +23
@@ -13,6 +13,20 @@ const MID = [180, 140];
1313 const tapping = (wait = .3) => g => { g.tap(...MID); g.run(wait); };
1414 const idling = seconds => g => g.run(seconds);
1515
16 // colour every pane not fixed so that no pair matches (backtracking), as [pane, colour] paints in pane order
17 function glassPlan({ panes, pairs, fixed, colours, palette }) {
18 const set = { ...colours }, free = panes.filter(p => !fixed.includes(p));
19 const ok = p => pairs.every(([a, b]) => (a !== p && b !== p) || set[a] === null || set[b] === null || set[a] !== set[b]);
20 const go = k => {
21 if (k === free.length) return true;
22 for (let c = 1; c <= palette; c++) { set[free[k]] = c; if (ok(free[k]) && go(k + 1)) return true; }
23 set[free[k]] = null;
24 return false;
25 };
26 go(0);
27 return free.map(p => [p, set[p]]);
28 }
29
1630 // the operations of a shortest win from a round state: a breadth-first search over the rules' own `apply`
1731 function solve(start) {
1832 const ops = [];
@@ -182,6 +196,15 @@ export const ROUNDS = {
182196 const at = g.plan.turns[g.read('P.moves')];
183197 g.tap(...g.read(`centre(${at[0]}, ${at[1]})`));
184198 } },
199 // solve each window by backtracking over the rules' own panes, pairs and fixed panes, then paint it one tap per beat: the colour, then the pane
200 'stained-glass': { over: /play again/, outcome: /The window is whole: \d+ strokes against par \d+/, beat: g => {
201 if (g.read('P.status') !== 'playing') { g.run(.3); return; }
202 const level = g.read('P.level');
203 if (g.plan?.level !== level) g.plan = { level, paints: glassPlan(g.read('({ panes: P.panes, pairs: P.pairs, fixed: P.fixed, colours: P.colours, palette: P.palette })')) };
204 const [pane, colour] = g.plan.paints[g.read('P.levelStrokes')];
205 if (g.read('G.colour') !== colour) g.tap(...g.read(`swatchPoint(${colour})`));
206 else g.tap(...g.read(`panePoint(${pane})`));
207 } },
185208 // hop along the route the rules planned for this pond, one arrow key per pad
186209 'lily-pond': { over: /play again/, outcome: /Pond cleared: 6 levels, \d+ retries?/, beat: g => {
187210 const [a, b] = g.read('[P.route[P.hops], P.route[P.hops + 1]]');
serve.test.mjs +7
@@ -677,3 +677,10 @@ test('Mill Race and its rules script are served without a track', async () => {
677677 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
678678 expect((await fetch(base + '/mill-race/race.js')).status).toBe(200);
679679 });
680
681 test('Stained Glass and its rules script are served without a track', async () => {
682 const page = await fetch(base + '/stained-glass/');
683 expect(page.status).toBe(200);
684 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
685 expect((await fetch(base + '/stained-glass/window.js')).status).toBe(200);
686 });
shell.js +1
@@ -65,6 +65,7 @@ window.PixelPlays = (() => {
6565 { id: 'quilt', title: 'Patchwork Quilt', blurb: 'Turn and swap the patches until every stitch lines up', kind: 'Puzzle', input: 'Tap', accent: '#b5656b', music: false, forged: true },
6666 { id: 'mill-race', title: 'Mill Race', blurb: 'Turn the channels until the stream reaches the mill wheel', kind: 'Puzzle', input: 'Tap', accent: '#3d6f8f', music: false, forged: true },
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 },
68 { 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 },
6869 ];
6970 const MUSIC_VOLUME = .4;
7071 const CREDITS = [
stained-glass/index.html added +439
@@ -0,0 +1,439 @@
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>Stained Glass</title>
7 <!-- og:begin -->
8 <meta name="description" content="Colour the window so no two neighbouring panes match">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/stained-glass/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Stained Glass">
13 <meta property="og:description" content="Colour the window so no two neighbouring panes match">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/stained-glass/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/stained-glass.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="Stained Glass: 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: #5a6fb8; }
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 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; }
38 button:hover, button:focus-visible { color: var(--ink); }
39 button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
40 noscript p { position: fixed; inset: 40% 16px auto; margin: 0; text-align: center; color: var(--muted); }
41 </style>
42 </head>
43 <body>
44 <div id="stage"><canvas id="c" tabindex="0" aria-label="A church window of leaded glass panes in a stone frame, with a row of colours below it. Tap a colour, then a pane, to paint it; tap a painted pane again to clear it. Arrow keys move between panes, 1 to 4 pick a colour, Space paints, R starts the window again. No two panes that share a lead line may match: a thick dashed lead line marks a clash. Each colour has its own pattern (stripes, dots, cross-hatch, checks) and a rivet marks a pane that is fixed. Three windows, par strokes each."></canvas></div>
45 <noscript><p>Stained Glass needs JavaScript to play.</p></noscript>
46 <div id="scores">
47 <div class="row"><b id="level">1 of 3</b><span id="name">window</span></div>
48 <div class="row"><b id="strokes">0</b><span>strokes</span></div>
49 <div class="row"><b id="par">0</b><span>par</span></div>
50 <div class="row"><b id="score">0</b><span>points</span></div>
51 </div>
52 <div class="hud" id="bottom">
53 <div id="status" role="status" aria-live="polite"></div>
54 <button id="mute" type="button" aria-pressed="false">sound on</button>
55 </div>
56 <script src="../shell.js"></script>
57 <script>
58 PixelPlays.mount({
59 id: 'stained-glass',
60 rules: [
61 'Tap a colour, then a pane, to paint it; tap a painted pane again to clear it.',
62 'Panes that share a lead line must not match: a thick dashed lead line is a clash.',
63 'Every paint is a stroke; stay at or under par for a bonus. Arrows, 1-4, Space, R.',
64 'Colour all 3 windows to finish.',
65 ],
66 });
67 </script>
68 <script>window.PP_SCENE = { originY: 8, shadowX: 1, shadowY: -.12 };</script>
69 <script src="../engine.js"></script>
70 <script src="window.js"></script>
71 <script>
72 'use strict';
73
74 const M = window.StainedGlass;
75 const HS = 1.1; // height of the stone slab's top face, world units
76 const GX = -7.5, GY = -8.5, GW = 15, GH = 11; // the glass, in world units
77 const STONE = [180, 174, 162], STONE_DARK = [128, 122, 114], WOOD = [150, 112, 76], FLOOR = [[134, 150, 112], [126, 142, 106]];
78 const GLASS_BARE = [[198, 202, 206], [214, 218, 220], [232, 234, 234]];
79 const INK_PIX = rgb(28, 27, 25), SIGNAL_PIX = rgb(255, 214, 10), LEAD_PIX = rgb(44, 46, 62), RIVET_PIX = rgb(236, 236, 228), TRAY_PIX = rgb(112, 84, 58);
80 const COLOURS = [[200, 74, 78], [72, 108, 206], [232, 190, 74], [74, 164, 104]];
81 const NAMES = ['red stripes', 'blue dots', 'gold cross-hatch', 'green checks'];
82 const RAMPS = COLOURS.map(rampOf), BARE = GLASS_BARE.map(c => rgb(...c));
83
84 /* ---------- the panes: polygons in the glass's unit square, drawn only; the rules own who neighbours whom ---------- */
85 const wedges = (n, rin) => {
86 // n wedges round a middle, as polygons: ray k leaves the middle at angle 60k - 90 and ends on the glass's edge
87 const at = a => [.5 + Math.cos(a) * rin, .5 + Math.sin(a) * rin];
88 const edge = a => { const c = Math.cos(a), s = Math.sin(a), t = .5 / Math.max(Math.abs(c), Math.abs(s)); return [.5 + c * t, .5 + s * t]; };
89 const polys = {};
90 for (let k = 0; k < n; k++) {
91 const a0 = (k * 360 / n - 90) * Math.PI / 180, a1 = ((k + 1) * 360 / n - 90) * Math.PI / 180, poly = [at(a0), edge(a0)];
92 for (const [cx, cy] of [[1, -1], [1, 1], [-1, 1], [-1, -1]]) {
93 let ac = Math.atan2(cy, cx); while (ac < a0) ac += Math.PI * 2;
94 if (ac > a0 + 1e-9 && ac < a1 - 1e-9) poly.push([.5 + cx * .5, .5 + cy * .5]);
95 }
96 poly.push(edge(a1), at(a1));
97 polys[k + 1] = poly;
98 }
99 return polys;
100 };
101 const flip = polys => Object.fromEntries(Object.entries(polys).map(([k, p]) => [k, p.map(([a, b]) => [b, a])]));
102 const LAYOUT = [
103 { 1: [[0, 0], [1, 0], [.6, .4], [.5, .3], [.4, .4]], 2: [[1, 0], [1, 1], [.6, .6], [.7, .5], [.6, .4]],
104 3: [[1, 1], [0, 1], [.4, .6], [.5, .7], [.6, .6]], 4: [[0, 1], [0, 0], [.4, .4], [.3, .5], [.4, .6]],
105 5: [[.5, .3], [.7, .5], [.5, .7], [.3, .5]] },
106 (() => { const w = wedges(6, .13); return { ...w, 7: [1, 2, 3, 4, 5, 6].map(k => w[k][0]) }; })(),
107 flip({ 5: [[0, .34], [1, .34], [1, .5], [0, .5]], 6: [[0, .16], [.5, .16], [.5, .34], [0, .34]],
108 7: [[0, 0], [1, 0], [1, .16], [0, .16]], 8: [[.5, .16], [1, .16], [1, .34], [.5, .34]],
109 4: [[0, .5], [1, .5], [1, .76], [.62, .76], [.5, .62], [.38, .76], [0, .76]],
110 2: [[0, .76], [.38, .76], [.5, .9], [.5, 1], [0, 1]], 3: [[.62, .76], [1, .76], [1, 1], [.5, 1], [.5, .9]],
111 1: [[.5, .62], [.62, .76], [.5, .9], [.38, .76]] }),
112 ];
113 const inside = (poly, x, y) => {
114 let in_ = false;
115 for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
116 const [xi, yi] = poly[i], [xj, yj] = poly[j];
117 if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) in_ = !in_;
118 }
119 return in_;
120 };
121
122 /* ---------- state ---------- */
123 const nodes = {};
124 for (const k of ['level', 'name', 'strokes', 'par', 'score', 'status']) nodes[k] = document.getElementById(k);
125 const shown = {};
126 function setText(key, text) {
127 if (shown[key] === text) return;
128 shown[key] = text;
129 nodes[key].textContent = text;
130 }
131 let P = M.start(0);
132 // colour: the paint in hand; cursor: a pane id; keyed: the keys are in use; dirty: the glass must be drawn again; layers counts how often
133 const G = { time: 0, noteUntil: 0, colour: 1, cursor: P.panes[0], keyed: false, dirty: true, layers: 0, laid: -1 };
134 const REFUSED = { fixed: 'that pane is fixed: its colour is set', 'no-pane': 'tap a pane or a colour', 'already-bare': 'that pane is already bare', over: 'the window is whole' };
135
136 function renderHud() {
137 setText('level', `${P.level + 1} of ${P.levels}`);
138 setText('name', P.name);
139 setText('strokes', String(P.levelStrokes));
140 setText('par', String(P.par));
141 setText('score', String(P.score));
142 }
143 function note(text) { setText('status', text); G.noteUntil = G.time + 2; }
144 const describe = p => {
145 const c = P.colours[p];
146 return `Pane ${p}: ${c === null ? 'bare' : NAMES[c - 1]}${P.fixed.includes(p) ? ', fixed' : ''}`;
147 };
148
149 /* ---------- geometry: which pane or colour is under each canvas pixel, laid once per window ---------- */
150 const HZ = HS * COS * S;
151 let paneOf = new Uint8Array(W * H), swatchOf = new Uint8Array(W * H), swatchEdge = new Uint8Array(W * H);
152 let glass = new Int32Array(0), lead = new Int32Array(0), leadPair = new Int32Array(0), thick = new Int32Array(0), thickPair = new Int32Array(0), tray = new Int32Array(0);
153 let anchors = {}, edges = {};
154 const SW = { size: 3, gap: 4, y: 5.6 };
155 const swatchX = (c, n) => (c - 1 - (n - 1) / 2) * SW.gap;
156 const glassAt = (ix, iy) => unproject(ix + .5, iy + .5 + HZ);
157 function lay() {
158 const polys = LAYOUT[P.level], n = P.palette;
159 paneOf = new Uint8Array(W * H); swatchOf = new Uint8Array(W * H); swatchEdge = new Uint8Array(W * H);
160 const sums = {}, trayList = [];
161 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
162 const g = glassAt(ix, iy), i = iy * W + ix, u = (g.x - GX) / GW, v = (g.y - GY) / GH;
163 if (u >= 0 && u < 1 && v >= 0 && v < 1) {
164 for (const p of P.panes) if (inside(polys[p], u, v)) { paneOf[i] = p; (sums[p] ??= [0, 0, 0]); sums[p][0] += ix; sums[p][1] += iy; sums[p][2]++; break; }
165 continue;
166 }
167 if (Math.abs(g.x) < 7.4 && g.y > 3.9 && g.y < 7.3) {
168 trayList.push(i);
169 for (let c = 1; c <= n; c++) if (Math.abs(g.x - swatchX(c, n)) < SW.size / 2 && Math.abs(g.y - SW.y) < SW.size / 2) swatchOf[i] = c;
170 }
171 }
172 tray = Int32Array.from(trayList);
173 const glassList = [], leadList = [], leadPairs = [], thickList = [], thickPairs = [];
174 const at = (ix, iy) => ix < 0 || iy < 0 || ix >= W || iy >= H ? 0 : paneOf[iy * W + ix];
175 const DIRS = [[1, 0], [-1, 0], [0, 1], [0, -1]];
176 edges = {};
177 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
178 const i = iy * W + ix, a = paneOf[i];
179 if (swatchOf[i] && DIRS.some(([dx, dy]) => (ix + dx < 0 || ix + dx >= W || iy + dy < 0 || iy + dy >= H ? 0 : swatchOf[(iy + dy) * W + ix + dx]) !== swatchOf[i])) swatchEdge[i] = 1;
180 if (!a) continue;
181 glassList.push(i);
182 let pair = -1, other = false;
183 for (const [dx, dy] of DIRS) {
184 const b = at(ix + dx, iy + dy);
185 if (b === a) continue;
186 other = true;
187 if (b && pair < 0) pair = a * 16 + b;
188 }
189 if (other) {
190 leadList.push(i); leadPairs.push(Math.max(pair, 0));
191 (edges[a] ??= []).push(i);
192 if (pair >= 0) for (const [dx, dy] of DIRS) {
193 const b = at(ix + dx, iy + dy);
194 if (b === a) { const j = (iy + dy) * W + ix + dx; thickList.push(j); thickPairs.push(pair); }
195 }
196 }
197 }
198 glass = Int32Array.from(glassList); lead = Int32Array.from(leadList); leadPair = Int32Array.from(leadPairs);
199 // the thick part of a clashing line lies beside it, never on another lead line
200 const onLead = new Set(leadList), keep = thickList.map((j, k) => k).filter(k => !onLead.has(thickList[k]));
201 thick = Int32Array.from(keep.map(k => thickList[k])); thickPair = Int32Array.from(keep.map(k => thickPairs[k]));
202 // a pane's anchor: its pixel nearest the middle of its pixels, where a rivet sits and a tap is aimed in tests
203 anchors = {};
204 for (const p of P.panes) {
205 const [sx, sy, c] = sums[p], mx = sx / c, my = sy / c;
206 let best = 1e9;
207 for (const i of glassList) if (paneOf[i] === p) {
208 const d = Math.hypot(i % W - mx, Math.floor(i / W) - my);
209 if (d < best) { best = d; anchors[p] = [i % W, Math.floor(i / W)]; }
210 }
211 }
212 G.laid = P.level;
213 }
214 const paneAtPoint = (sx, sy) => paneOf[clamp(Math.floor(sy), 0, H - 1) * W + clamp(Math.floor(sx), 0, W - 1)] || null;
215 const swatchAtPoint = (sx, sy) => swatchOf[clamp(Math.floor(sy), 0, H - 1) * W + clamp(Math.floor(sx), 0, W - 1)] || null;
216 const swatchPoint = c => { const p = project(swatchX(c, P.palette), SW.y, HS); return [Math.round(p.sx), Math.round(p.sy)]; };
217 const panePoint = p => anchors[p];
218
219 /* ---------- baked scene: meadow, stone slab, buttresses ---------- */
220 function floorColor(x, y, ix, iy) {
221 const edge = Math.pow(Math.abs(x) / 11.6, 6) + Math.pow(Math.abs(y + .2) / 11, 6);
222 const rough = Math.pow(edge, 1 / 6) + (noise(x * 1.3, y * 1.3) - .5) * .06;
223 if (rough > 1) return 0;
224 if (rough > .95 && hash(ix, iy) < (rough - .95) / .05) return 0;
225 const t = .97 + (hash(ix, iy) - .5) * .06, c = FLOOR[Math.floor((x + 12) / 1.4) & 1];
226 return rgb(c[0] * t, c[1] * t, c[2] * t);
227 }
228 const shade = (x, y, z, r) => castShadow(x, y, z, r, 1, 0);
229 function bake() {
230 ground.fill(0); shadowMask.fill(0); staticShadow.fill(0); kinds.fill(0);
231 tufts.length = 0; leaves.length = 0;
232 zb.fill(-1e9);
233 pix.fill(rgb(255, 255, 255));
234 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
235 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = floorColor(g.x, g.y, ix, iy);
236 if (!c) continue;
237 pix[i] = c; ground[i] = 1;
238 zb[i] = (g.x + g.y) / R2 * COS;
239 }
240 groundZ.set(zb);
241 box(-8.2, -9.2, 0, 8.2, 7.6, HS, STONE, 4);
242 box(-8.9, -9.2, 0, -8.2, 3.2, 2.6, STONE_DARK, 6);
243 box(8.2, -9.2, 0, 8.9, 3.2, 2.6, STONE_DARK, 8);
244 bakeOcclusion();
245 for (let t = -9.2; t <= 7.6; t += .5) shade(8.2, t, HS, .5);
246 for (let t = -8.2; t <= 8.2; t += .5) shade(t, 7.6, HS, .5);
247 for (let z = 0; z <= 2.6; z += .5) { shade(8.9, -9.2, z, .45); shade(8.9, 3.2, z, .45); }
248 staticShadow.set(shadowMask);
249 applyShadows(groundZ);
250 bakedPix.set(pix);
251 bakedZ.set(zb);
252 }
253
254 /* ---------- the glass layer: drawn once per change and cached ---------- */
255 const layerPix = new Uint32Array(W * H);
256 const MARKS = [
257 (ix, iy) => (ix + iy) % 8 < 3,
258 (ix, iy) => iy % 6 < 2 && (ix + (Math.floor(iy / 6) % 2) * 3) % 6 < 2,
259 (ix, iy) => (ix + iy) % 8 === 0 || (ix - iy + 800) % 8 === 0,
260 (ix, iy) => ((ix >> 1) + (iy >> 1)) % 2 === 0,
261 ];
262 function fillColour(c, ix, iy) {
263 const ramp = RAMPS[c - 1];
264 return MARKS[c - 1](ix, iy) ? ramp[0] : bayerAt(ix, iy) < .3 && (ix + iy) & 1 ? ramp[3] : ramp[2];
265 }
266 function rivet(p) {
267 const [x, y] = anchors[p];
268 for (const [dx, dy] of [[-1, -1], [0, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [0, 1], [1, 1]]) pix[(y + dy) * W + x + dx] = INK_PIX;
269 pix[y * W + x] = RIVET_PIX;
270 }
271 const dash = i => (i % W + Math.floor(i / W)) % 8 < 5 ? SIGNAL_PIX : INK_PIX;
272 function paintLayer() {
273 pix.set(bakedPix);
274 for (const i of tray) pix[i] = TRAY_PIX;
275 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
276 const i = iy * W + ix, c = swatchOf[i];
277 if (!c) continue;
278 pix[i] = swatchEdge[i] ? (c === G.colour ? SIGNAL_PIX : INK_PIX) : fillColour(c, ix, iy);
279 }
280 for (const i of glass) {
281 const p = paneOf[i], c = P.colours[p], ix = i % W, iy = (i - ix) / W;
282 pix[i] = c === null ? BARE[(ix + iy >> 1 & 1) && bayerAt(ix, iy) > .5 ? 1 : 2] : fillColour(c, ix, iy);
283 }
284 const clash = new Set(P.clashes.flatMap(([a, b]) => [a * 16 + b, b * 16 + a]));
285 for (let k = 0; k < lead.length; k++) pix[lead[k]] = clash.has(leadPair[k]) ? dash(lead[k]) : LEAD_PIX;
286 for (let k = 0; k < thick.length; k++) if (clash.has(thickPair[k])) pix[thick[k]] = dash(thick[k]);
287 for (const p of P.fixed) rivet(p);
288 if (G.keyed && P.status === 'playing') {
289 const ring = new Set(edges[G.cursor]);
290 for (const i of ring) pix[i] = SIGNAL_PIX;
291 for (const i of glass) if (paneOf[i] === G.cursor && !ring.has(i) && [1, -1, W, -W].some(d => ring.has(i + d))) pix[i] = INK_PIX;
292 }
293 layerPix.set(pix);
294 G.layers++;
295 G.dirty = false;
296 }
297 // sunlight: a pale diagonal band creeping across the glass, stepped at 8 fps; not drawn at all under reduced motion
298 function glint() {
299 const step = Math.floor(G.time * WIND_FPS), at = step % 90;
300 for (let k = 0; k < glass.length; k++) {
301 const i = glass[k], ix = i % W, iy = (i - ix) / W;
302 if (((ix + iy * 2) % 90 + 90 - at) % 90 < 4) {
303 const c = pix[i];
304 pix[i] = rgb((c & 255) * .7 + 76, (c >> 8 & 255) * .7 + 76, (c >> 16 & 255) * .7 + 76);
305 }
306 }
307 }
308 function draw() {
309 if (G.laid !== P.level) lay();
310 if (G.dirty) paintLayer();
311 pix.set(layerPix);
312 if (!STILL) glint();
313 ctx.putImageData(image, 0, 0);
314 }
315
316 /* ---------- game: every rule is the rules script's ---------- */
317 function show() { G.dirty = true; renderHud(); }
318 function apply(pane) {
319 ensureAudio();
320 if (P.status !== 'playing') return;
321 const before = P, same = before.colours[pane] === G.colour && !before.fixed.includes(pane);
322 const r = same ? M.clear(P, pane) : M.paint(P, pane, G.colour);
323 if (!r.ok) { note(REFUSED[r.why] || 'cannot do that'); sound(110, .12, 'sawtooth'); return; }
324 P = r.state;
325 if (r.event === 'cleared') { note(`Pane ${pane} cleared; ${P.line}`); sound(260, .07, 'triangle'); }
326 else if (r.event === 'painted') { note(`${describe(pane)}. ${P.line}`); sound(300 + pane * 40, .07, 'triangle'); }
327 else if (r.event === 'solved') {
328 const s = P.solved[P.solved.length - 1];
329 note(`${s.name} solved in ${s.strokes} strokes, par ${s.par}${s.underPar ? '' : ': over par'}. Next: ${P.name}`);
330 G.cursor = P.panes[0];
331 sound(523, .12, 'triangle'); sound(659, .2, 'triangle', .1);
332 } else if (r.event === 'won') { G.noteUntil = 0; sound(523, .12, 'triangle'); sound(659, .12, 'triangle', .12); sound(784, .4, 'triangle', .24); }
333 show();
334 }
335 function pick(c) {
336 ensureAudio();
337 if (c < 1 || c > P.palette || G.colour === c) return;
338 G.colour = c;
339 G.dirty = true;
340 note(`${NAMES[c - 1]} in hand`);
341 sound(440, .05, 'sine');
342 }
343 function restart() {
344 P = M.start(0); G.colour = 1; G.cursor = P.panes[0]; G.keyed = false;
345 show();
346 note(START);
347 }
348 function redo() {
349 if (P.status !== 'playing') return;
350 P = M.restart(P);
351 show();
352 note(`${P.name} begun again`);
353 }
354 const START = 'tap a colour, then a pane';
355 function update(dt) {
356 G.time += dt;
357 if (G.time < G.noteUntil) return;
358 setText('status', P.status === 'won' ? `${P.line} · tap or press a key to play again` : P.line);
359 }
360
361 /* ---------- input ---------- */
362 const point = e => { const r = canvas.getBoundingClientRect(); return [(e.clientX - r.left) / r.width * W, (e.clientY - r.top) / r.height * H]; };
363 canvas.addEventListener('pointerdown', e => {
364 canvas.focus({ preventScroll: true });
365 ensureAudio();
366 if (P.status !== 'playing') { restart(); return; }
367 const [sx, sy] = point(e), c = swatchAtPoint(sx, sy), p = paneAtPoint(sx, sy);
368 G.keyed = false;
369 G.dirty = true;
370 if (c) { pick(c); return; }
371 if (!p) { note(START); return; }
372 G.cursor = p;
373 apply(p);
374 });
375 canvas.addEventListener('keydown', e => {
376 if (e.ctrlKey || e.metaKey || e.altKey || e.key === 'Tab') return;
377 const next = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? -1 : 0;
378 const act = e.key === ' ' || e.key === 'Enter', digit = /^[1-9]$/.test(e.key), again = e.key === 'r' || e.key === 'R';
379 if (!next && !act && !digit && !again) return;
380 e.preventDefault();
381 if (e.repeat && !next) return;
382 if (P.status !== 'playing') { restart(); return; }
383 G.keyed = true;
384 G.dirty = true;
385 if (digit) { if (Number(e.key) <= P.palette) pick(Number(e.key)); return; }
386 if (again) { redo(); return; }
387 if (next) {
388 const at = P.panes.indexOf(G.cursor);
389 G.cursor = P.panes[(at + next + P.panes.length) % P.panes.length];
390 note(describe(G.cursor));
391 return;
392 }
393 apply(G.cursor);
394 });
395
396 /* ---------- sound ---------- */
397 let audio = null, muted = false;
398 function ensureAudio() {
399 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
400 const AC = window.AudioContext || window.webkitAudioContext;
401 if (AC) audio = new AC();
402 }
403 function sound(freq, life, type, delay = 0) {
404 if (!audio || muted) return;
405 const now = audio.currentTime + delay, gain = audio.createGain(), osc = audio.createOscillator();
406 osc.type = type;
407 osc.frequency.setValueAtTime(freq, now);
408 gain.gain.setValueAtTime(.0001, now);
409 gain.gain.exponentialRampToValueAtTime(.07, now + .01);
410 gain.gain.exponentialRampToValueAtTime(.0005, now + life);
411 osc.connect(gain).connect(audio.destination);
412 osc.start(now); osc.stop(now + life + .02);
413 }
414 const muteButton = document.getElementById('mute');
415 muteButton.addEventListener('click', () => {
416 muted = !muted;
417 muteButton.textContent = muted ? 'sound off' : 'sound on';
418 muteButton.setAttribute('aria-pressed', String(muted));
419 });
420
421 /* ---------- fit and boot ---------- */
422 addEventListener('resize', fit);
423 fit();
424 bake();
425 lay();
426 renderHud();
427 note(START);
428 canvas.focus({ preventScroll: true });
429 let last = performance.now();
430 function frame(now) {
431 update(Math.min(.04, (now - last) / 1000));
432 last = now;
433 draw();
434 requestAnimationFrame(frame);
435 }
436 requestAnimationFrame(frame);
437 </script>
438 </body>
439 </html>
stained-glass/page.test.mjs added +124
@@ -0,0 +1,124 @@
1 import { test, expect } from 'bun:test';
2 import { boot } from '../playtest.mjs';
3
4 const tapColour = (g, c) => g.tap(...g.read(`swatchPoint(${c})`));
5 const tapPane = (g, p) => g.tap(...g.read(`panePoint(${p})`));
6
7 test('a tap on a colour and then a pane paints it once, counts the stroke and the HUD reports the rules state', () => {
8 const g = boot('stained-glass', { seed: 3 });
9 tapColour(g, 2);
10 tapPane(g, 1);
11 expect(g.read('P.colours[1]')).toBe(2);
12 expect(g.read('P.levelStrokes')).toBe(1);
13 expect(g.el('strokes').textContent).toBe('1');
14 expect(g.el('par').textContent).toBe(String(g.read('P.par')));
15 expect(g.el('level').textContent).toBe('1 of 3');
16 expect(g.el('name').textContent).toBe('Rose');
17 expect(g.el('status').textContent).toContain(g.read('P.line'));
18 });
19
20 test('a painted pane tapped again with the same colour is cleared, and clearing is not a stroke', () => {
21 const g = boot('stained-glass', { seed: 3 });
22 tapPane(g, 1);
23 tapPane(g, 1);
24 expect(g.read('P.colours[1]')).toBe(null);
25 expect(g.read('P.levelStrokes')).toBe(1);
26 });
27
28 test('a fixed pane refuses the paint, says so, and shows a rivet', () => {
29 const g = boot('stained-glass', { seed: 3 });
30 tapPane(g, 5);
31 expect(g.read('P.levelStrokes')).toBe(0);
32 expect(g.el('status').textContent).toContain('fixed');
33 const [x, y] = g.read('panePoint(5)');
34 g.run(.1);
35 expect(g.read(`layerPix[${y} * W + ${x}]`)).toBe(g.read('RIVET_PIX'));
36 });
37
38 test('the panes drawn touch exactly the panes the rules pair, in every window', () => {
39 const g = boot('stained-glass', { seed: 3 });
40 for (let level = 0; level < 3; level++) {
41 g.read(`P = StainedGlass.start(${level}); G.dirty = true`);
42 g.run(.1);
43 const seen = g.read(`(() => { const s = new Set(); for (let i = 0; i < W * H; i++) { const a = paneOf[i]; if (!a) continue; for (const d of [1, W]) { const b = paneOf[i + d]; if (b && b !== a) s.add(Math.min(a, b) * 16 + Math.max(a, b)); } } return [...s].sort((a, b) => a - b); })()`);
44 const want = g.read('P.pairs.map(([a, b]) => Math.min(a, b) * 16 + Math.max(a, b)).sort((a, b) => a - b)');
45 expect(seen).toEqual(want);
46 }
47 });
48
49 test('a clash is marked on its lead line by a dashed stroke and only that line', () => {
50 const g = boot('stained-glass', { seed: 3 });
51 tapColour(g, 2);
52 tapPane(g, 1);
53 tapPane(g, 2);
54 g.run(.1);
55 expect(g.read('P.clashes')).toEqual([[1, 2]]);
56 const marked = g.read(`(() => { const out = { dash: 0, plain: 0, other: 0 };
57 for (let k = 0; k < lead.length; k++) { const c = layerPix[lead[k]], clash = leadPair[k] === 1 * 16 + 2 || leadPair[k] === 2 * 16 + 1;
58 if (c === SIGNAL_PIX || c === INK_PIX) clash ? out.dash++ : out.other++; else if (clash) out.plain++; }
59 return out; })()`);
60 expect(marked.dash).toBeGreaterThan(8);
61 expect(marked.plain).toBe(0);
62 expect(marked.other).toBe(0);
63 tapPane(g, 2); // clear it: the mark goes with the clash
64 g.run(.1);
65 expect(g.read('P.clashes')).toEqual([]);
66 expect(g.read(`lead.every((i, k) => layerPix[i] === LEAD_PIX)`)).toBe(true);
67 });
68
69 test('every colour carries its own pattern, so colour is never the only cue', () => {
70 const g = boot('stained-glass', { seed: 3 });
71 const grids = [0, 1, 2, 3].map(c => g.read(`(() => { let s = ''; for (let iy = 0; iy < 24; iy++) for (let ix = 0; ix < 24; ix++) s += MARKS[${c}](ix, iy) ? 1 : 0; return s; })()`));
72 expect(new Set(grids).size).toBe(4);
73 for (const s of grids) { const on = [...s].filter(c => c === '1').length; expect(on).toBeGreaterThan(30); expect(on).toBeLessThan(400); }
74 });
75
76 test('the glass is drawn once per change, not once per frame', () => {
77 const g = boot('stained-glass', { seed: 3 });
78 g.run(2);
79 const base = g.read('G.layers');
80 g.run(3);
81 expect(g.read('G.layers')).toBe(base);
82 tapPane(g, 1);
83 g.run(1);
84 expect(g.read('G.layers')).toBe(base + 1);
85 });
86
87 test('arrows move between panes, digits pick the colour and Space paints', () => {
88 const g = boot('stained-glass', { seed: 3 });
89 g.press('ArrowRight');
90 expect(g.read('G.cursor')).toBe(2);
91 expect(g.el('status').textContent).toContain('Pane 2');
92 g.press('3');
93 g.press(' ');
94 expect(g.read('P.colours[2]')).toBe(3);
95 g.press('4'); // the first window has only three colours
96 expect(g.read('G.colour')).toBe(3);
97 });
98
99 test('solving the first window moves on to the next and a full round ends on the rules\' win line', () => {
100 const g = boot('stained-glass', { seed: 3 });
101 const plan = [[1, 2], [2, 3], [3, 2], [4, 3]]; // the hub (5) is fixed to 1
102 for (const [p, c] of plan) { tapColour(g, c); tapPane(g, p); }
103 expect(g.el('level').textContent).toBe('2 of 3');
104 expect(g.el('score').textContent).toBe('150');
105 expect(g.el('status').textContent).toContain('Rose solved in 4 strokes, par 4');
106 });
107
108 test('mute toggles its label and aria-pressed', () => {
109 const g = boot('stained-glass', { seed: 3 });
110 g.el('mute').fire('click');
111 expect(g.el('mute').textContent).toBe('sound off');
112 expect(g.el('mute').attrs['aria-pressed']).toBe('true');
113 });
114
115 test('the page source says how to play, keeps the 44px mute target, stills the sunlight, holds the rules to four lines and names no .mp3', async () => {
116 const html = await Bun.file(new URL('./index.html', import.meta.url)).text();
117 expect(html).toMatch(/<canvas id="c"[^>]*aria-label="[^"]*Tap a colour, then a pane[^"]*Arrow keys[^"]*Space/);
118 expect(html).toMatch(/min-height: 44px; min-width: 44px/);
119 expect(html).toMatch(/id="mute"[^>]*aria-pressed="false"/);
120 expect(html).toContain('if (!STILL) glint()');
121 expect(html).not.toContain('.mp3');
122 const rules = html.match(/rules: \[([\s\S]*?)\]/)[1].split('\n').filter(l => l.trim());
123 expect(rules.length).toBeLessThanOrEqual(4);
124 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs