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

Migrated from github.com/amirmushichge/pixel-plays

I love the isometric 3D spaces. bring them into the app itself so the entire… #111

Parked opened this in answer to
Closed without merging

quill/pixel-plays:quill/99-i-love-the-isometric-3d-spaces-bring-the → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +290 −0
README.md +3
@@ -55,6 +55,9 @@ Then open http://127.0.0.1:5300/. `PORT` and `HOST` override the port and addres
5555
5656 On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is only the play counts, under `FORGE_APP_DATA`. `bun test` checks that the server answers every game page and track.
5757
58 ## The town
59 With scripts on, the home page opens on an isometric town drawn by the same engine as the games: one building per game in its accent colour on a paved square, trees in the spare plots. Tap or click a building to play it; hover, or focus a card in the list, to lift it and name it below the picture. Searching or filtering the list greys out the buildings that no longer match. The list underneath stays the way in without scripts and from the keyboard, so the picture is `aria-hidden`. `town.js` holds the layout and the nearest-building pick (plain data, tested in `town.test.mjs`); `plaza.js` draws it and is exercised against a stand-in canvas in `plaza.test.mjs`. It redraws only when something changes, so there is no motion to reduce, and it adds no dependency.
60
5861 ## Plays
5962 `/stats/` ranks the games by how much they are played, and `/api/stats` returns the same rows as JSON. Each game page reports three anonymous events to `POST /api/play` (an Origin check against browser cross-site posts, which a script can still forge, so the endpoint is also limited as below): the page opened, the first tap or key press (a play), and the seconds the page stayed visible after that. Only totals per game are kept, with no ids or cookies, in `plays.json` under `FORGE_APP_DATA` (in memory when it is unset). `stats.mjs` holds the counting; it needs no dependency, so the file is plain JSON rather than SQLite, which would tie the server to Bun. Limits: 60 events a minute per client address (the socket address, never a header) and 600 a minute per game, answered with 429; a play is refused unless an open is ahead of it and time unless plays can account for it (at most 3600 s each), so forged events cannot show a ratio real ones never could. They cannot stop someone slowly inflating a game within those bounds, so treat the numbers as a guide. Counts are flushed to disk on SIGTERM. Not recorded yet: a finished round, since each game ends in its own way.
6063
index.html +22
@@ -41,6 +41,11 @@ a:focus-visible { outline: 2px solid #1c1b19; outline-offset: 2px; }
4141 li span { color: #8b877f; font-size: .9375rem; }
4242 li .tags { order: -1; font-size: .75rem; letter-spacing: .06em; text-transform: uppercase; color: #1c1b19; }
4343 li a { order: 0; }
44 .town { display: none; margin: 0 0 1.5rem; max-width: 45rem; }
45 .js .town { display: block; }
46 .town canvas { display: block; width: 100%; aspect-ratio: 360 / 280; image-rendering: pixelated; touch-action: manipulation; }
47 #place { min-height: 3em; font-size: .9375rem; color: #8b877f; }
48 #place b { color: #1c1b19; }
4449 #status { margin: 0 0 1rem; min-height: 1.5em; }
4550 #status { visibility: hidden; }
4651 .js #status { visibility: visible; }
@@ -53,6 +58,7 @@ footer a::after { content: none; }
5358 <main>
5459 <h1>Pixel Plays</h1>
5560 <p>Small browser games. Pick one.</p>
61 <div class="town" aria-hidden="true"><canvas id="c" width="360" height="280"></canvas><div id="place">Tap a building to play.</div></div>
5662 <form class="tools" method="get" action="./">
5763 <input id="q" name="q" type="search" placeholder="Search games" aria-label="Search games" autocomplete="off">
5864 <div id="kinds" role="group" aria-label="Filter by kind"></div>
@@ -97,6 +103,9 @@ footer a::after { content: none; }
97103 <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>
98104 </main>
99105 <script src="shell.js"></script>
106 <script src="engine.js"></script>
107 <script src="town.js"></script>
108 <script src="plaza.js"></script>
100109 <script>
101110 // the list above works without scripts and must list the same games (serve.test.mjs checks); with scripts it is rebuilt from GAMES, with search and a kind filter
102111 (() => {
@@ -123,6 +132,7 @@ footer a::after { content: none; }
123132 ul.replaceChildren(...found.map(card));
124133 status.textContent = found.length ? found.length + (found.length === 1 ? ' game' : ' games') : 'No game matches.';
125134 history.replaceState(null, '', PixelPlays.browseUrl({ query, kind }));
135 Plaza.set({ ids: found.map(g => g.id) });
126136 for (const b of kinds.children) b.setAttribute('aria-pressed', String(b.dataset.kind === kind));
127137 };
128138 for (const k of ['', ...PixelPlays.kindsOf(PixelPlays.GAMES)]) {
@@ -133,6 +143,18 @@ footer a::after { content: none; }
133143 }
134144 kinds.addEventListener('click', e => { if (e.target.closest('button')) e.preventDefault(); });
135145 q.addEventListener('input', render);
146 // the town and the list are one thing: a building lifts when its card is focused or hovered, and the other way round
147 const place = document.getElementById('place');
148 Plaza.onchange = g => {
149 place.replaceChildren();
150 if (!g) return place.append('Tap a building to play.');
151 const b = document.createElement('b');
152 b.textContent = g.title;
153 place.append(b, ' · ' + g.blurb);
154 };
155 const lift = e => { const li = e.target.closest && e.target.closest('li'); Plaza.set({ active: li ? li.firstChild.getAttribute('href').slice(0, -1) : '' }); };
156 ul.addEventListener('focusin', lift); ul.addEventListener('focusout', () => Plaza.set({ active: '' }));
157 ul.addEventListener('pointerover', lift); ul.addEventListener('pointerleave', () => Plaza.set({ active: '' }));
136158 document.querySelector('.tools').addEventListener('submit', e => { e.preventDefault(); render(); });
137159 render();
138160 })();
plaza.js added +114
@@ -0,0 +1,114 @@
1 'use strict';
2 // Draws the home page as an isometric town with the engine every game uses: one building per game in its accent
3 // colour, a paved square, trees in the spare plots. Still on purpose (it redraws only when something changes), so
4 // there is no motion to reduce. Needs engine.js, town.js and shell.js loaded first, and <canvas id="c">.
5 window.Plaza = (() => {
6 const GAMES = PixelPlays.GAMES.filter(g => !g.soon);
7 const town = Town.layout(GAMES.map(g => g.id));
8 const byId = Object.fromEntries(GAMES.map(g => [g.id, g]));
9 const rgbOf = hex => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16));
10 const STONE = [[196, 190, 178], [182, 176, 166], [168, 162, 154]], GREY = [214, 212, 206], ROOF = [58, 54, 62];
11 const REACH = 20; // canvas pixels: generous, so a fingertip lands on a building
12 let shown = new Set(GAMES.map(g => g.id)), active = '';
13
14 // the plaza is a rounded square of paving, grass and a path of lighter stones between the plots
15 const half = Math.max(town.cols, town.rows) * Town.PITCH / 2 + 1.2;
16 function groundColor(x, y, ix, iy, i) {
17 const edge = Math.pow(Math.pow(Math.abs(x) / half, 5) + Math.pow(Math.abs(y) / half, 5), .2);
18 const rough = edge + (noise(x * 1.3, y * 1.3) - .5) * .08;
19 if (rough > 1.06) return 0;
20 if (rough > .96 && hash(ix, iy) < (rough - .96) / .1) return 0;
21 if (rough > .9) { kinds[i] = KIND_GRASS; return rgb(...GRASS[clamp(Math.floor(noise(x * .9, y * .9) * 4), 0, 3)]); }
22 const lane = (Math.abs(((x / Town.PITCH + 1000.5) % 1) - .5) < .17 || Math.abs(((y / Town.PITCH + 1000.5) % 1) - .5) < .17) ? 0 : 1;
23 const tile = (Math.floor(x * 1.2) + Math.floor(y * 1.2)) & 1;
24 return rgb(...STONE[clamp(lane + tile + (hash(ix, iy) > .93 ? 1 : 0), 0, 2)]);
25 }
26 function paveGround() {
27 zb.fill(-1e9);
28 pix.fill(rgb(255, 255, 255));
29 ground.fill(0);
30 kinds.fill(0);
31 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
32 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy, i);
33 if (!c) continue;
34 pix[i] = c; ground[i] = 1;
35 zb[i] = (g.x + g.y) / R2 * COS;
36 }
37 groundZ.set(zb);
38 bakedPix.set(pix);
39 bakedZ.set(zb);
40 }
41
42 const targets = town.plots.map(p => {
43 const mid = project(p.x, p.y, p.h * .6), top = project(p.x, p.y, p.h + 1.2);
44 return { id: p.id, sx: mid.sx, sy: mid.sy, top: top.sy };
45 });
46
47 // one building, in its own colour; `glow` is the hover: the same shape a hair higher in a lighter paint, so only its pixels change
48 function building(p, glow) {
49 const g = byId[p.id], on = shown.has(p.id), w = .95, z0 = glow ? .02 : 0;
50 const h = on ? p.h : 1.2, accent = rgbOf(g.accent);
51 const body = !on ? GREY : glow ? accent.map(c => c + (255 - c) * .35) : accent;
52 box(p.x - w, p.y - w, z0, p.x + w, p.y + w, h + z0, body, p.x * 7 + p.y);
53 box(p.x - w - .15, p.y - w - .15, h + z0, p.x + w + .15, p.y + w + .15, h + z0 + .3, on ? (glow ? [120, 112, 128] : ROOF) : GREY, 3);
54 if (!glow) for (const z of [.5, h * .5, h]) castShadow(p.x, p.y, z, w * .9, 1, .3);
55 }
56 function tree(p) {
57 capsule([p.x, p.y, 0], [p.x, p.y, 1.6], .2, .14, () => BARK, 'rough');
58 for (const [dx, dy, z, r] of [[0, 0, 2.3, 1], [.5, .3, 2.9, .7], [-.5, -.2, 2.8, .7]]) sphere(p.x + dx, p.y + dy, z, r, LEAF_MID, 'rough');
59 for (const z of [.6, 1.6, 2.6]) castShadow(p.x, p.y, z, .7, 1, .3);
60 }
61
62 // the street and every building, with their shadows, kept until the set of games shown changes
63 const townPix = new Uint32Array(W * H), townZ = new Float32Array(W * H);
64 function bakeTown() {
65 pix.set(bakedPix);
66 zb.set(bakedZ);
67 for (const p of town.plots) building(p, false);
68 for (const p of town.free) tree(p);
69 applyShadows(groundZ);
70 townPix.set(pix);
71 townZ.set(zb);
72 }
73 function paint() {
74 pix.set(townPix);
75 zb.set(townZ);
76 const lit = active && town.plots.find(p => p.id === active);
77 if (lit && shown.has(active)) building(lit, true);
78 shadeEdges();
79 const t = lit && targets.find(x => x.id === active);
80 if (t && shown.has(active)) drawArrow(t.sx, t.top, 0);
81 ctx.putImageData(image, 0, 0);
82 }
83 let stale = true, timer = 0;
84 function flush() {
85 clearTimeout(timer); timer = 0;
86 if (stale) { bakeTown(); stale = false; }
87 paint();
88 }
89 // a search can change many buildings per keystroke: wait for a pause. A pointer moving between buildings paints at once.
90 const later = ms => { clearTimeout(timer); timer = setTimeout(flush, ms); };
91
92 const at = e => {
93 const rect = canvas.getBoundingClientRect(), k = W / rect.width;
94 return Town.pick(targets.filter(t => shown.has(t.id)), (e.clientX - rect.left) * k, (e.clientY - rect.top) * k, REACH);
95 };
96 function set(next) {
97 const same = a => a.size === shown.size && [...a].every(id => shown.has(id));
98 const ids = next.ids ? new Set(next.ids) : shown, id = next.active == null ? active : next.active;
99 if (id === active && same(ids)) return;
100 const moved = id !== active;
101 if (!same(ids)) { shown = ids; stale = true; }
102 active = id;
103 if (stale) later(120); else flush();
104 if (moved && api.onchange) api.onchange(active && byId[active]);
105 }
106 canvas.addEventListener('pointermove', e => set({ active: at(e) || '' }));
107 canvas.addEventListener('pointerleave', () => set({ active: '' }));
108 canvas.addEventListener('pointerdown', e => { const id = at(e); if (id) { set({ active: id }); location.href = id + '/'; } });
109 canvas.style.cursor = 'pointer';
110 const api = { set, flush, onchange: null, targets, town };
111 paveGround();
112 later(0);
113 return api;
114 })();
plaza.test.mjs added +64
@@ -0,0 +1,64 @@
1 import { test, expect } from 'bun:test';
2 import { readFileSync } from 'node:fs';
3
4 // run the real engine, shell, town and plaza against a stand-in canvas, then look at the pixels it painted
5 function boot() {
6 const listeners = {}, puts = [];
7 const canvas = {
8 style: {}, getBoundingClientRect: () => ({ left: 0, top: 0, width: 360, height: 280 }),
9 addEventListener: (type, fn) => { listeners[type] = fn; },
10 getContext: () => ({ createImageData: (w, h) => ({ data: new Uint8ClampedArray(w * h * 4) }), putImageData: (img) => puts.push(img) }),
11 };
12 const win = { devicePixelRatio: 1, innerWidth: 800, innerHeight: 600, location: { href: '/' } };
13 win.window = win;
14 const src = ['shell.js', 'engine.js', 'town.js', 'plaza.js'].map(f => readFileSync(new URL('./' + f, import.meta.url), 'utf8').replace("'use strict';", ''));
15 const run = new Function('window', 'document', 'matchMedia', 'location', 'localStorage', `${src[0]}\nconst PixelPlays = window.PixelPlays;\n${src[1]}\n${src[2]}\nconst Town = window.Town;\n${src[3]}\nreturn { Plaza: window.Plaza, pix, W, H };`);
16 const out = run(win, { getElementById: () => canvas, addEventListener() {}, documentElement: {} }, () => ({ matches: false, addEventListener() {} }), win.location, {});
17 out.Plaza.flush();
18 return { ...out, listeners, puts, win };
19 }
20 const painted = pix => { let n = 0; for (const c of pix) if (c !== 0xffffffff && c !== 0) n++; return n; };
21
22 test('the town paints a frame with a building for every game', () => {
23 const { Plaza, pix, puts } = boot();
24 expect(puts.length).toBe(1); // the first frame, painted once the page has settled
25 expect(painted(pix)).toBeGreaterThan(pix.length / 4);
26 expect(Plaza.targets.length).toBe(Plaza.town.plots.length);
27 for (const t of Plaza.targets) { expect(t.sx).toBeGreaterThan(0); expect(t.sx).toBeLessThan(360); expect(t.sy).toBeGreaterThan(0); expect(t.sy).toBeLessThan(280); }
28 });
29
30 test('pointing at a building lifts it and names it, leaving clears it', () => {
31 const { Plaza, listeners, puts } = boot();
32 const t = Plaza.targets[3], seen = [];
33 Plaza.onchange = g => seen.push(g && g.id);
34 listeners.pointermove({ clientX: t.sx, clientY: t.sy });
35 expect(seen).toEqual([t.id]);
36 expect(puts.length).toBe(2);
37 listeners.pointerleave();
38 expect(seen).toEqual([t.id, '']);
39 });
40
41 test('tapping a building opens its game and tapping the grass does not', () => {
42 const { Plaza, listeners, win } = boot();
43 listeners.pointerdown({ clientX: 0, clientY: 0 });
44 expect(win.location.href).toBe('/');
45 const t = Plaza.targets[0];
46 listeners.pointerdown({ clientX: t.sx + 2, clientY: t.sy - 2 });
47 expect(win.location.href).toBe(t.id + '/');
48 });
49
50 test('a search that drops a game makes its building unreachable', () => {
51 const { Plaza, listeners, win } = boot();
52 const t = Plaza.targets[0];
53 Plaza.set({ ids: Plaza.targets.slice(1).map(x => x.id) });
54 Plaza.flush();
55 listeners.pointerdown({ clientX: t.sx, clientY: t.sy });
56 expect(win.location.href).toBe('/');
57 });
58
59 test('a redraw is quick enough to follow a pointer', () => {
60 const { Plaza } = boot();
61 const t0 = performance.now();
62 for (let n = 0; n < 5; n++) Plaza.set({ active: Plaza.targets[n].id });
63 expect((performance.now() - t0) / 5).toBeLessThan(120);
64 });
rounds.mjs +24
@@ -87,6 +87,30 @@ export const ROUNDS = {
8787 const k = d <= g.read(`Line.brakingDistance(${v})`) + .2 ? 'ArrowDown' : 'ArrowUp';
8888 g.keyDown(k); g.step(1); g.keyUp(k);
8989 } },
90 // pour while the fill, plus what the stream still delivers after release, is short of the painted line
91 'espresso-bar': { over: /pour again/, outcome: /twenty cups poured · \d+/, beat: g => {
92 const hold = g.read('R.phase') === 'play' && !g.read('R.done') && g.read('R.fill') + .55 * .25 < g.read('Pour.lineOf(R.cup)');
93 if (hold) g.keyDown(' ');
94 g.step(1);
95 if (hold) g.keyUp(' ');
96 } },
97 // tap what glows and every moth, so the night is survived
98 'firefly-jar': { over: /another night/, outcome: /the night is survived · \d+ in the jar/, beat: g => {
99 const hits = g.read(`Night.targets(R).filter(t => t.kind === 'moth' || Night.glow(R.flies.find(f => f.id === t.id)).on).map(t => { const p = scr(t.u, t.v, t.z); return [p.sx, p.sy]; })`);
100 if (hits.length) g.tap(hits[0][0], hits[0][1]); else g.step(1);
101 } },
102 // read the lamp's sequence off the page and pull the levers back in order; a win takes over 100 s of watching, so this round jams three trains and takes the loss
103 'signal-box': { over: /run again/, outcome: /\d+ trains routed · the junction needs 8/, beat: g => {
104 if (g.read("P.phase") === 'input') g.press(String((g.read('P.seq[P.got]') + 1) % 5 + 1), .05);
105 g.run(.1);
106 } },
107 // steer for the middle of the next gate's gap, early enough for the cart's lag
108 'soapbox-derby': { over: /roll again/, outcome: /banner! [\d.]+ s/, beat: g => {
109 const gap = g.read('(() => { for (let n = 0; n < Cart.GATES; n++) { const q = Cart.gateAt(n, R.seed); if (R.x < q.x + Cart.GATE_DEPTH + 1.5) return [q.x - R.x, q.centre]; } return null; })()');
110 const lane = gap && gap[0] < 24 ? gap[1] : 0, steer = Math.max(-1, Math.min(1, lane / g.read('Cart.LANE_MAX')));
111 g.down(180, 140); g.move(180 + (steer - g.read('G.steer')) * 100, 140); g.up(180, 140);
112 g.step(1);
113 } },
90114 'archery': { over: /play again/, outcome: /\d+ points · (new best|best)/, beat: g => { g.drag([180, 100], [120, 160], .4); g.run(3); } },
91115 'tie-break': { over: /play again/, outcome: /(you win|rival wins) \d+–\d+/, beat: tapping() },
92116 // lean against the lean, and against its speed
town.js added +27
@@ -0,0 +1,27 @@
1 'use strict';
2 // The town on the home page: where each game stands and which one a pointer is on.
3 // Plain data in, plain data out, no DOM; plaza.js draws what this decides.
4 (function (root) {
5 const PITCH = 4; // world units between neighbouring plots
6 const hash = s => { let h = 2166136261; for (const c of s) h = Math.imul(h ^ c.charCodeAt(0), 16777619); return (h >>> 0) / 4294967296; };
7 // a square-ish grid centred on the origin, one building per game in list order; the plots left over stay empty
8 function layout(ids) {
9 const cols = Math.max(1, Math.ceil(Math.sqrt(ids.length))), rows = Math.max(1, Math.ceil(ids.length / cols));
10 const at = (c, r) => ({ x: (c - (cols - 1) / 2) * PITCH, y: (r - (rows - 1) / 2) * PITCH });
11 const plots = ids.map((id, n) => ({ id, ...at(n % cols, Math.floor(n / cols)), h: 1.6 + Math.round(hash(id) * 4) / 4 }));
12 const free = [];
13 for (let n = ids.length; n < cols * rows; n++) free.push(at(n % cols, Math.floor(n / cols)));
14 return { plots, free, cols, rows };
15 }
16 // the nearest point within reach, or null; points are { id, sx, sy } in canvas pixels
17 function pick(points, sx, sy, reach) {
18 let best = null, bestD = reach;
19 for (const p of points) {
20 const d = Math.hypot(p.sx - sx, p.sy - sy);
21 if (d < bestD) { bestD = d; best = p.id; }
22 }
23 return best;
24 }
25 const api = { PITCH, layout, pick };
26 if (typeof module !== 'undefined') module.exports = api; else root.Town = api;
27 })(typeof window !== 'undefined' ? window : globalThis);
town.test.mjs added +36
@@ -0,0 +1,36 @@
1 import { test, expect } from 'bun:test';
2 import { layout, pick, PITCH } from './town.js';
3
4 const ids = Array.from({ length: 34 }, (_, n) => 'game-' + n);
5
6 test('every game gets its own plot and the spare plots are free', () => {
7 const t = layout(ids);
8 expect(t.plots.map(p => p.id)).toEqual(ids);
9 expect(t.plots.length + t.free.length).toBe(t.cols * t.rows);
10 const cells = [...t.plots, ...t.free].map(p => p.x + ',' + p.y);
11 expect(new Set(cells).size).toBe(cells.length);
12 });
13
14 test('plots keep a street between them and the town is centred', () => {
15 const t = layout(ids), all = [...t.plots, ...t.free];
16 for (const a of all) for (const b of all) if (a !== b) expect(Math.hypot(a.x - b.x, a.y - b.y)).toBeGreaterThanOrEqual(PITCH - 1e-9);
17 expect(Math.abs(all.reduce((s, p) => s + p.x, 0))).toBeLessThan(1e-9);
18 });
19
20 test('the layout is the same every time and heights stay in range', () => {
21 expect(layout(ids)).toEqual(layout(ids));
22 for (const p of layout(ids).plots) { expect(p.h).toBeGreaterThanOrEqual(1.6); expect(p.h).toBeLessThanOrEqual(2.6); }
23 });
24
25 test('a short or empty list still lays out', () => {
26 expect(layout([]).plots).toEqual([]);
27 expect(layout(['a']).plots.length).toBe(1);
28 });
29
30 test('pick takes the nearest point within reach and nothing beyond it', () => {
31 const pts = [{ id: 'a', sx: 10, sy: 10 }, { id: 'b', sx: 30, sy: 10 }];
32 expect(pick(pts, 14, 10, 18)).toBe('a');
33 expect(pick(pts, 26, 10, 18)).toBe('b');
34 expect(pick(pts, 100, 100, 18)).toBe(null);
35 expect(pick([], 0, 0, 18)).toBe(null);
36 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs