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

Migrated from github.com/amirmushichge/pixel-plays

Open the home page on the isometric town: tap a building to play its game #153

Merged opened this

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

Merged

vesper/pixel-plays:vesper/133-open-the-home-page-on-the-isometric-town → main 3 commits fork 3 threads · 3 unresolved

  • Merged. vesper/133-open-the-home-page-on-the-isometric-town was merged into main as c4f9ad3.

Review

Sign in to review this change.
7 files changed +358 −0
README.md +3
@@ -116,3 +116,6 @@ The code is under the [MIT License](LICENSE). The music is not: see [MUSIC.md](M
116116 `playtest.mjs` boots a game page for real (its inline scripts, `shell.js`, `engine.js`) in a `vm` with a small DOM stand-in, then `playtest.test.mjs` plays every game folder with a seeded stand-in for a person: taps, holds, drags (one pointer move per frame) and key presses. Each game must boot without errors, paint a real picture, idle without failing, and, played, differ from an untouched twin of the same seed advanced by the same frame count: in its picture and in its HUD text (score, status). The keyboard alone must part the two as well. So a game that ignores its input fails. A new game folder is picked up automatically. It adds no dependency. The file took 242 seconds (147 tests) by the test runner's count in the last full run, the whole suite 322 seconds, well inside the deploy's 600-second limit for `bun test`. The page's scripts run as one strict function with the hot globals (`Math`, typed arrays, `document`) bound once, because a `vm` context looks every global name up through an interceptor, which made each frame two to three times slower. A scripted round, with its idle twin, takes a few seconds of test time, except the fixed-length timed rounds (wood-split's 60 s is about 30 seconds of test time), so a round test is allowed 120 seconds.
117117
118118 `rounds.mjs` holds one scripted round per game (a table keyed by game id: a beat of taps, drags, holds or keys, repeated until the HUD line that ends the round appears, watched after every frame). `playtest.test.mjs` plays each script, asserts the end line matches the row's `outcome` pattern (the win or loss, with its number), and that an untouched twin run for as long does not reach that outcome, and fails when a game folder has no script. A new game must add its row there.
119
120 ## The town
121 The home page opens on a small isometric town above the list: one building per game in its accent colour, laid out by `town.js` (pure data, tested) and drawn by `plaza.js` with the colour ramp and dither of the engine (a small copy in `ramp.js`, so the home page loads no renderer; `ramp.test.mjs` fails if the two drift). The look follows the engine and shawn.'s [Small plays](https://x.com/zzzzshawn/status/2111546123546661289) reference, as the footer credits. Tap or click a building to play its game; hover it, or hover or focus its card, to lift it and see its name. Search and the kind filter grey out the buildings that no longer match, and those cannot be tapped. The list underneath is the same as ever and remains the way in without scripts and from the keyboard; the canvas is `aria-hidden`, hidden without JavaScript, has its space reserved with `aspect-ratio` (and on a phone is at least 600px wide and scrolls sideways inside the page, so a building stays about thumb-sized), and redraws only when something changes. `plaza.test.mjs` runs the real scripts against a stand-in canvas.
index.html +15
@@ -41,6 +41,9 @@ 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; }
45 .js #town { display: block; overflow-x: auto; max-width: 44rem; margin: 0 auto 1.5rem; }
46 .js #c { display: block; width: 100%; min-width: 600px; aspect-ratio: 2 / 1; image-rendering: pixelated; touch-action: pan-x pan-y; }
4447 #status { margin: 0 0 1rem; min-height: 1.5em; }
4548 #status { visibility: hidden; }
4649 .js #status { visibility: visible; }
@@ -53,6 +56,7 @@ footer a::after { content: none; }
5356 <main>
5457 <h1>Pixel Plays</h1>
5558 <p>Small browser games. Pick one.</p>
59 <div id="town" aria-hidden="true"><canvas id="c"></canvas></div>
5660 <form class="tools" method="get" action="./">
5761 <input id="q" name="q" type="search" placeholder="Search games" aria-label="Search games" autocomplete="off">
5862 <div id="kinds" role="group" aria-label="Filter by kind"></div>
@@ -107,13 +111,19 @@ footer a::after { content: none; }
107111 <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>
outdated

engine.js is a full renderer that allocates its 360x280 buffers on load and is not needed here; three sync scripts delay the first paint. Extract the ramp/dither or defer.

108112 </main>
109113 <script src="shell.js"></script>
114 <script src="ramp.js"></script>
115 <script src="town.js"></script>
116 <script src="plaza.js"></script>
110117 <script>
111118 // 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
112119 (() => {
113120 const ul = document.getElementById('games'), q = document.getElementById('q'), kinds = document.getElementById('kinds');
114121 const status = document.getElementById('status');
122 const plaza = PixelPlaza.mount(document.getElementById('c'), PixelPlays.GAMES.filter(g => !g.soon));
115123 let { query, kind } = PixelPlays.parseBrowse(location.search);
116124 q.value = query;
125 const town = document.getElementById('town');
126 town.scrollLeft = (town.scrollWidth - town.clientWidth) / 2; // a phone sees the middle of the town first
117127 const card = g => {
118128 const li = document.createElement('li'), a = document.createElement('a'), d = document.createElement('span'), t = document.createElement('span');
119129 li.style.setProperty('--accent', g.accent);
@@ -132,6 +142,7 @@ footer a::after { content: none; }
132142 const found = PixelPlays.filterGames(PixelPlays.GAMES, { query, kind });
133143 ul.replaceChildren(...found.map(card));
134144 status.textContent = found.length ? found.length + (found.length === 1 ? ' game' : ' games') : 'No game matches.';
145 plaza.setMatching(found.map(g => g.id));
135146 history.replaceState(null, '', PixelPlays.browseUrl({ query, kind }));
136147 for (const b of kinds.children) b.setAttribute('aria-pressed', String(b.dataset.kind === kind));
137148 };
@@ -142,6 +153,10 @@ footer a::after { content: none; }
142153 kinds.append(b);
143154 }
144155 kinds.addEventListener('click', e => { if (e.target.closest('button')) e.preventDefault(); });
156 // a card under the pointer or holding focus lifts its building
157 const lift = e => { const a = e.target.closest && e.target.closest('li') && e.target.closest('li').querySelector('a'); plaza.setHover(a ? a.getAttribute('href').replace(/\/$/, '') : null); };
158 ul.addEventListener('pointerover', lift); ul.addEventListener('focusin', lift);
159 ul.addEventListener('pointerleave', () => plaza.setHover(null)); ul.addEventListener('focusout', () => plaza.setHover(null));
145160 q.addEventListener('input', render);
146161 document.querySelector('.tools').addEventListener('submit', e => { e.preventDefault(); render(); });
147162 render();
plaza.js added +154
@@ -0,0 +1,154 @@
1 'use strict';
2 // The town on the home page: draws town.js's layout with the shared colour ramps and dither (ramp.js), and turns a tap on a building into its game.
3 // Needs ramp.js and town.js loaded first. Sets window.PixelPlaza.
4 (() => {
5 const Town = window.PixelTown, { rgb, rampOf, bayerAt } = window.PixelRamp;
6 const MIN_CSS_WIDTH = 600; // the canvas is never drawn narrower than this in CSS pixels (a phone scrolls it sideways), so a building stays about thumb-sized
7 const BUF_W = 640, BUF_H = 320; // the canvas's pixel size; CSS reserves the same aspect ratio, so the town fits it rather than the other way round
8 const PAD = 12, LIFT = 7; // buffer margin around the town; how far a hovered building rises, world units
9 const GRASS = [[52, 88, 52], [82, 118, 54], [34, 62, 50]];
10 const GREYED = [176, 174, 168], INK = '#1c1b19';
11 const TREES = [[58, 96, 62], [76, 112, 66], [96, 124, 70]], TRUNK = [96, 76, 58];
12
13 const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
14 const colours = new Map(); // accent string -> the array ramp.js keys its ramps on
15 function colourOf(accent) {
16 let c = colours.get(accent);
17 if (!c) {
18 const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(accent);
19 c = m ? [parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16)] : [136, 136, 136];
20 colours.set(accent, c);
21 }
22 return c;
23 }
24
25 // games: [{ id, title, accent }]. opts.open(id) is called for a tap on a building (default: go to its page).
26 function mount(canvas, games, opts = {}) {
27 const town = Town.layout(games);
28 const titles = new Map(games.map(g => [g.id, g.title]));
29 const open = opts.open || (id => { location.href = id + '/'; });
30 canvas.width = BUF_W; canvas.height = BUF_H;
31 const ctx = canvas.getContext('2d');
32 const image = ctx.createImageData(BUF_W, BUF_H);
33 const pix = new Uint32Array(image.data.buffer);
34 const white = rgb(255, 255, 255);
35
36 // fit the town's extent into the buffer, centred
37 let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
38 for (const t of [...town.buildings, ...town.trees]) {
39 x0 = Math.min(x0, t.x - town.tile.halfWidth); x1 = Math.max(x1, t.x + town.tile.halfWidth);
40 y0 = Math.min(y0, t.y - t.height - LIFT - town.tile.halfHeight); y1 = Math.max(y1, t.y + town.tile.halfHeight);
outdated

Scale is derived only from the town extent; with many games this shrinks buildings below a finger on a 360px screen. Enforce a minimum hit size or adapt the canvas to narrow widths.

41 }
42 const scale = town.buildings.length ? Math.min((BUF_W - 2 * PAD) / (x1 - x0), (BUF_H - 2 * PAD) / (y1 - y0)) : 1;
43 const ox = (BUF_W - (x1 - x0) * scale) / 2 - x0 * scale, oy = (BUF_H - (y1 - y0) * scale) / 2 - y0 * scale;
outdated

draws and its getter are only a counter nobody reads: dead code, remove.

44
45 let matching = null, hover = null, dirty = false, queued = false;
46 const shown = id => !matching || matching.has(id);
47
48 // a convex polygon of world points, filled scanline by scanline with a ramp level (0 to 4) dithered by the Bayer matrix
49 function fill(pts, ramp, level) {
50 const p = pts.map(([x, y]) => [x * scale + ox, y * scale + oy]);
51 const top = Math.max(0, Math.ceil(Math.min(...p.map(q => q[1])) - .5)), bottom = Math.min(BUF_H - 1, Math.floor(Math.max(...p.map(q => q[1])) - .5));
52 for (let iy = top; iy <= bottom; iy++) {
53 const y = iy + .5;
54 let l = Infinity, r = -Infinity;
55 for (let i = 0; i < p.length; i++) {
56 const a = p[i], b = p[(i + 1) % p.length];
57 if ((a[1] <= y) === (b[1] <= y)) continue;
58 const x = a[0] + (y - a[1]) / (b[1] - a[1]) * (b[0] - a[0]);
59 if (x < l) l = x;
60 if (x > r) r = x;
61 }
62 for (let ix = Math.max(0, Math.ceil(l - .5)); ix <= Math.min(BUF_W - 1, Math.floor(r - .5)); ix++) {
63 pix[iy * BUF_W + ix] = ramp[clamp(Math.floor(level + (bayerAt(ix, iy) - .5) * .7 + .5), 0, 4)];
64 }
65 }
66 }
67 const diamond = (x, y, w, h) => [[x, y - h], [x + w, y], [x, y + h], [x - w, y]];
68
69 function drawBuilding(b) {
70 const lit = shown(b.id), c = lit ? colourOf(b.accent) : GREYED, ramp = rampOf(c);
71 const y = b.y - (hover === b.id && lit ? LIFT : 0);
72 const w = town.tile.halfWidth * .8, h = town.tile.halfHeight * .8, H = b.height;
73 if (y !== b.y) fill(diamond(b.x + 6, b.y + 2, w, h), rampOf(GRASS_DARK), 1.2); // the gap it left on the ground, in shade
74 fill([[b.x - w, y], [b.x, y + h], [b.x, y + h - H], [b.x - w, y - H]], ramp, 2.4);
75 fill([[b.x, y + h], [b.x + w, y], [b.x + w, y - H], [b.x, y + h - H]], ramp, 1.2);
76 fill(diamond(b.x, y - H, w, h), ramp, 3.6);
77 // a door on the right face
78 fill([[b.x + w * .3, y + h * .7 - 2], [b.x + w * .6, y + h * .4 - 2], [b.x + w * .6, y + h * .4 - 14], [b.x + w * .3, y + h * .7 - 14]], rampOf(DOOR), 1);
79 }
80 const GRASS_DARK = [40, 70, 44], DOOR = [60, 52, 48];
81 function drawTree(t) {
82 const trunk = rampOf(TRUNK), crown = rampOf(TREES[t.kind]);
83 fill([[t.x - 2, t.y], [t.x + 2, t.y], [t.x + 2, t.y - t.height * .5], [t.x - 2, t.y - t.height * .5]], trunk, 1.6);
84 const r = 9 + t.kind * 2, cy = t.y - t.height * .5 - r * .5;
85 fill([[t.x, cy - r], [t.x + r * .8, cy - r * .3], [t.x + r * .8, cy + r * .3], [t.x, cy + r * .8], [t.x - r * .8, cy + r * .3], [t.x - r * .8, cy - r * .3]], crown, 2.6);
86 }
87
88 function draw() {
89 pix.fill(white);
90 const things = [...town.buildings, ...town.trees];
91 for (const t of things) {
92 const g = rampOf(GRASS[t.plot.gx + t.plot.gy & 1]);
93 fill(diamond(t.x, t.y, town.tile.halfWidth, town.tile.halfHeight), g, 2);
94 }
95 // far to near: a larger gx + gy is nearer the camera
96 things.sort((a, b) => a.depth - b.depth || a.plot.gx - b.plot.gx);
97 for (const t of things) 'id' in t ? drawBuilding(t) : drawTree(t);
98 ctx.putImageData(image, 0, 0);
99 const b = hover && town.buildings.find(q => q.id === hover);
100 if (b) {
101 const label = titles.get(b.id) || b.id, w = label.length * 7 + 12;
102 const lx = clamp(b.x * scale + ox - w / 2, 2, BUF_W - w - 2), ly = Math.max(2, (b.y - b.height - LIFT - town.tile.halfHeight) * scale + oy - 22);
103 ctx.fillStyle = '#fff'; ctx.fillRect(lx, ly, w, 18);
104 ctx.strokeStyle = INK; ctx.lineWidth = 1; ctx.strokeRect(lx + .5, ly + .5, w - 1, 17);
105 ctx.fillStyle = INK; ctx.font = '12px ui-monospace, Menlo, Consolas, monospace'; ctx.textBaseline = 'middle';
106 ctx.fillText(label, lx + 6, ly + 9.5);
107 }
108 }
109
110 // a change marks the picture stale; one frame later it is drawn once, however many changes came in between
111 function invalidate() {
112 dirty = true;
113 if (queued) return;
114 queued = true;
115 requestAnimationFrame(() => { queued = false; if (dirty) { dirty = false; draw(); } });
116 }
117
118 function setHover(id) {
119 const next = id && town.buildings.some(b => b.id === id && shown(b.id)) ? id : null;
120 if (next === hover) return;
121 hover = next;
122 canvas.style.cursor = hover ? 'pointer' : '';
123 invalidate();
124 }
125 // ids: the games that still match the search and filter, or null for all of them
126 function setMatching(ids) {
127 const next = ids ? new Set(ids) : null;
128 const same = next === matching || (next && matching && next.size === matching.size && [...next].every(i => matching.has(i)));
129 if (same) return;
130 matching = next;
131 if (hover && !shown(hover)) hover = null;
132 canvas.style.cursor = hover ? 'pointer' : '';
133 invalidate();
134 }
135
136 // client pixels to the plane town.js lays out
137 function at(e) {
138 const r = canvas.getBoundingClientRect();
139 if (!(r.width > 0 && r.height > 0)) return null;
140 return [((e.clientX - r.left) * BUF_W / r.width - ox) / scale, ((e.clientY - r.top) * BUF_H / r.height - oy) / scale];
141 }
142 const under = e => { const p = at(e); return p ? Town.pick(town, p[0], p[1], b => shown(b.id)) : null; };
143 canvas.addEventListener('pointermove', e => setHover(under(e)));
144 canvas.addEventListener('pointerleave', () => setHover(null));
145 canvas.addEventListener('click', e => { const id = under(e); if (id) open(id); });
146
147 invalidate();
148 // how big a building is on screen when the canvas is cssWidth pixels wide: its width, and the height of the shortest one's whole silhouette (wall and roof)
149 const size = cssWidth => { const k = cssWidth / BUF_W * scale; return { width: 2 * town.tile.halfWidth * .8 * k, height: (Math.min(...town.buildings.map(b => b.height)) + 2 * town.tile.halfHeight * .8) * k }; };
150 return { town, setHover, setMatching, size, get hover() { return hover; } };
151 }
152
153 window.PixelPlaza = { mount, MIN_CSS_WIDTH };
154 })();
plaza.test.mjs added +122
@@ -0,0 +1,122 @@
1 import { test, expect } from 'bun:test';
2 import { readFileSync } from 'node:fs';
3 import vm from 'node:vm';
4
5 // the real ramp.js, town.js and plaza.js in one realm (as a page loads them), against a stand-in canvas
6 function boot(list) {
7 const frames = [], calls = [], opened = [], handlers = {}, puts = [];
8 const canvas = {
9 style: {}, width: 0, height: 0,
10 addEventListener(k, f) { handlers[k] = f; },
11 getBoundingClientRect: () => ({ left: 0, top: 0, width: 640, height: 320 }),
12 getContext: () => ({
13 createImageData: (w, h) => ({ width: w, height: h, data: new Uint8ClampedArray(w * h * 4) }),
14 putImageData: img => puts.push(new Uint32Array(img.data.buffer).slice()),
15 fillRect() {}, strokeRect() {}, fillText: t => calls.push(t),
16 }),
17 };
18 const ctx = vm.createContext({
19 console, Math, Uint8Array, Uint8ClampedArray, Uint32Array, Float32Array, Object, Array, Number, String, Map, Set, WeakMap, isFinite,
20 requestAnimationFrame: f => frames.push(f),
21 });
22 ctx.window = ctx;
23 for (const f of ['ramp.js', 'town.js', 'plaza.js']) new vm.Script(readFileSync(new URL(f, import.meta.url), 'utf8'), { filename: f }).runInContext(ctx);
24 const games = ['one', 'two', 'three', 'four'].map((id, i) => ({ id, title: id.toUpperCase(), accent: ['#d9a441', '#3f8fb5', '#c8604a', '#5a9a5a'][i] }));
25 const plaza = ctx.PixelPlaza.mount(canvas, list || games, { open: id => opened.push(id) });
26 const frame = () => { for (const f of frames.splice(0)) f(); };
27 return { MIN: ctx.PixelPlaza.MIN_CSS_WIDTH, plaza, canvas, handlers, frame, calls, opened, puts, frames };
28 }
29
30 // where on the canvas a building is: search the buffer for a point town.js picks as that building
31 function pointOf(t, id) {
32 const { plaza, handlers } = t;
33 for (let y = 0; y < 320; y += 2) for (let x = 0; x < 640; x += 2) {
34 t.handlers.pointermove({ clientX: x, clientY: y });
35 if (plaza.hover === id) { handlers.pointerleave(); t.frame(); return { clientX: x, clientY: y }; }
36 }
37 throw new Error('no point on ' + id);
38 }
39
40 test('the first frame is drawn once, in colour, with a building per game', () => {
41 const t = boot();
42 expect(t.plaza.town.buildings.map(b => b.id)).toEqual(['one', 'two', 'three', 'four']);
43 expect(t.canvas.width).toBe(640);
44 expect(t.puts.length).toBe(0);
45 t.frame();
46 expect(t.puts.length).toBe(1);
47 const colours = new Set(t.puts[0]);
48 expect(colours.size).toBeGreaterThan(8);
49 t.frame(); t.frame();
50 expect(t.puts.length).toBe(1); // nothing changed: nothing redrawn
51 });
52
53 test('hovering lifts and names a building; leaving puts it back', () => {
54 const t = boot(); t.frame();
55 const p = pointOf(t, 'two');
56 const before = t.puts.length, resting = t.puts.at(-1);
57 t.handlers.pointermove(p); t.frame();
58 expect(t.plaza.hover).toBe('two');
59 expect(t.canvas.style.cursor).toBe('pointer');
60 expect(t.calls.at(-1)).toBe('TWO');
61 expect(t.puts.length).toBe(before + 1);
62 expect(t.puts.at(-1)).not.toEqual(resting);
63 t.handlers.pointermove(p); t.frame();
64 expect(t.puts.length).toBe(before + 1); // same hover, same picture
65 t.handlers.pointerleave(); t.frame();
66 expect(t.plaza.hover).toBe(null);
67 expect(t.puts.at(-1)).toEqual(resting);
68 });
69
70 test('a card can lift its building too', () => {
71 const t = boot(); t.frame();
72 t.plaza.setHover('three'); t.frame();
73 expect(t.plaza.hover).toBe('three');
74 expect(t.calls.at(-1)).toBe('THREE');
75 t.plaza.setHover('nope'); expect(t.plaza.hover).toBe(null);
76 });
77
78 test('a tap on a building opens its game; a tap on the ground opens nothing', () => {
79 const t = boot(); t.frame();
80 t.handlers.click(pointOf(t, 'four'));
81 expect(t.opened).toEqual(['four']);
82 t.handlers.click({ clientX: 1, clientY: 1 });
83 expect(t.opened).toEqual(['four']);
84 });
85
86 test('a building the filter dropped is grey, cannot be hovered, and does not open', () => {
87 const t = boot(); t.frame();
88 const p = pointOf(t, 'one');
89 const full = t.puts.at(-1);
90 t.plaza.setMatching(['two', 'three', 'four']); t.frame();
91 expect(t.puts.at(-1)).not.toEqual(full);
92 t.handlers.pointermove(p); t.frame();
93 expect(t.plaza.hover).not.toBe('one');
94 t.plaza.setHover('one'); expect(t.plaza.hover).toBe(null);
95 t.handlers.click(p);
96 expect(t.opened).not.toContain('one'); // a building in front may take the tap, never the dropped one
97 t.opened.length = 0;
98 t.plaza.setMatching(['two', 'three', 'four']); t.frame(); // same set: nothing to redraw
99 const n = t.puts.length; t.frame(); expect(t.puts.length).toBe(n);
100 t.plaza.setMatching(null); t.frame();
101 expect(t.puts.at(-1)).toEqual(full);
102 t.handlers.click(p);
103 expect(t.opened).toEqual(['one']);
104 });
105
106 test('on a 360px phone every building of the real catalogue is still thumb-sized', async () => {
107 globalThis.window = globalThis;
108 let games;
109 try { await import('./shell.js?plaza'); games = window.PixelPlays.GAMES.filter(g => !g.soon); } finally { delete globalThis.window; delete globalThis.PixelPlays; }
110 expect(games.length).toBeGreaterThan(40);
111 const t = boot(games);
112 const css = Math.max(360, t.MIN); // the canvas is never narrower than its min-width, and the town scrolls inside the page
113 const { width, height } = t.plaza.size(css);
114 expect(width).toBeGreaterThanOrEqual(40);
115 expect(height).toBeGreaterThanOrEqual(36);
116 // the stylesheet really asks for that width, and keeps the aspect so nothing shifts
117 const html = readFileSync(new URL('index.html', import.meta.url), 'utf8');
118 expect(html).toContain(`min-width: ${t.MIN}px`);
119 expect(html).toContain('aspect-ratio: 2 / 1');
120 // and a tap at the middle of a wall finds that building, at that size
121 for (const b of t.plaza.town.buildings.slice(0, 5)) expect(pointOf(t, b.id)).toBeTruthy();
122 });
ramp.js added +24
@@ -0,0 +1,24 @@
1 'use strict';
2 // Colour ramps and ordered dither for the home page's town: the same five-step, violet-shadow to warm-light ramp and 4x4 Bayer matrix as engine.js,
3 // without the renderer's buffers. (engine.js keeps its own copy: its globals are shared with every game page; ramp.test.mjs fails if the two drift.)
4 // Sets window.PixelRamp, or is the module's export under bun.
5 (() => {
6 const COOL = [46, 38, 84], WARM = [255, 232, 180];
7 const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5].map(v => (v + .5) / 16);
8 const lerp = (a, b, t) => a + (b - a) * t;
9 const rgb = (r, g, b) => (255 << 24 | Math.min(255, b | 0) << 16 | Math.min(255, g | 0) << 8 | Math.min(255, r | 0)) >>> 0;
10 const ramps = new WeakMap();
11 // five packed ABGR colours for an [r, g, b] array, darkest first; cached on the array
12 function rampOf(c) {
13 let ramp = ramps.get(c);
14 if (ramp) return ramp;
15 const mix = (m, tint, k) => rgb(lerp(c[0] * m, tint[0], k), lerp(c[1] * m, tint[1], k), lerp(c[2] * m, tint[2], k));
16 ramp = [mix(.4, COOL, .34), mix(.62, COOL, .18), mix(.84, COOL, .05), mix(1, WARM, 0), mix(1.1, WARM, .22)];
17 ramps.set(c, ramp);
18 return ramp;
19 }
20 const bayerAt = (ix, iy) => BAYER[(iy & 3) * 4 + (ix & 3)];
21 const api = { rgb, rampOf, bayerAt };
22 if (typeof module !== 'undefined' && module.exports) module.exports = api;
23 if (typeof window !== 'undefined') window.PixelRamp = api;
24 })();
ramp.test.mjs added +18
@@ -0,0 +1,18 @@
1 import { test, expect } from 'bun:test';
2 import { readFileSync } from 'node:fs';
3 import vm from 'node:vm';
4 import { rgb, rampOf, bayerAt } from './ramp.js';
5
6 // ramp.js is a copy of the colour ramp and dither in engine.js; the real engine must agree with it
7 test('ramp.js gives the same ramps and dither as engine.js', () => {
8 const canvas = { getContext: () => ({ createImageData: (w, h) => ({ data: new Uint8ClampedArray(w * h * 4) }) }) };
9 const ctx = vm.createContext({ Math, Uint8Array, Uint8ClampedArray, Uint32Array, Float32Array, WeakMap, document: { getElementById: () => canvas }, matchMedia: () => ({ matches: false }), window: {} });
10 new vm.Script(readFileSync(new URL('engine.js', import.meta.url), 'utf8') + '\nthis.probe = { rgb, rampOf, bayerAt };', { filename: 'engine.js' }).runInContext(ctx);
11 for (const c of [[217, 164, 65], [63, 143, 181], [176, 174, 168], [0, 0, 0], [255, 255, 255]]) {
12 expect(rampOf(c)).toEqual(ctx.probe.rampOf([...c]));
13 expect(rampOf(c)).toHaveLength(5);
14 }
15 expect(rgb(1, 2, 3)).toBe(ctx.probe.rgb(1, 2, 3));
16 for (let y = 0; y < 4; y++) for (let x = 0; x < 4; x++) expect(bayerAt(x, y)).toBe(ctx.probe.bayerAt(x, y));
17 expect(bayerAt(5, 6)).toBe(bayerAt(1, 2));
18 });
serve.test.mjs +22
@@ -527,3 +527,25 @@ test('Go-Kart Fete says it needs JavaScript when scripts are off', async () => {
527527 const html = await (await fetch(base + '/go-kart/')).text();
528528 expect(html).toMatch(/<noscript>\s*<p>Go-Kart Fete needs JavaScript\./);
529529 });
530
531 test('the home page loads the town: /ramp.js, /town.js and /plaza.js are served like the other assets, and the list stays without scripts', async () => {
532 const html = await (await fetch(base + '/')).text();
533 expect(html).toContain('<div id="town" aria-hidden="true"><canvas id="c"></canvas></div>');
534 expect(html).not.toContain('engine.js'); // the town borrows no renderer
535 const other = await fetch(base + '/shell.js');
536 for (const f of ['ramp.js', 'town.js', 'plaza.js']) {
537 expect(html).toContain(`<script src="${f}"></script>`);
538 const res = await fetch(base + '/' + f);
539 expect(res.status).toBe(200);
540 expect(res.headers.get('content-type')).toBe(other.headers.get('content-type'));
541 expect(res.headers.get('cache-control')).toBe(other.headers.get('cache-control'));
542 expect(res.headers.get('x-content-type-options')).toBe('nosniff');
543 }
544 // JS off: the static list is the whole catalogue, one card per game that is not "soon", each a plain link
545 globalThis.window = globalThis;
546 let games;
547 try { await import('./shell.js?homelist'); games = window.PixelPlays.GAMES.filter(g => !g.soon); } finally { delete globalThis.window; delete globalThis.PixelPlays; }
548 const list = html.slice(html.indexOf('<ul id="games">'), html.indexOf('</ul>'));
549 expect(list.split('<li ').length - 1).toBe(games.length);
550 for (const g of games) expect(list).toContain(`<a href="${g.id}/">`);
551 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs