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

Migrated from github.com/amirmushichge/pixel-plays

Add Tram Line: drive a city tram and stop each door on the yellow mark #63

Merged opened this

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

Merged

quill/pixel-plays:quill/55-add-tram-line-drive-a-city-tram-and-stop → main 3 commits fork 5 threads · 5 unresolved

  • Merged. quill/55-add-tram-line-drive-a-city-tram-and-stop was merged into main as cf817a1.

Review

Sign in to review this change.
9 files changed +662 −2
README.md +3 −2
@@ -33,6 +33,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
3333 | [Bread Oven](bread-oven/) | A 60-second shift at a brick oven with four slots: slide dough in with the peel, crusts go pale, golden, dark, burnt, and slots nearer the fire bake faster; pulling golden scores 3, dark 1, pale 0, and a burnt loaf is a strike, three end the round (forged by the crew on the engine and shell above, not by the original creators) | Tap a slot, or arrows + space to slide in, enter to pull |
3434 | [Tightrope](tightrope/) | Three crossings of a wire between two rooftops: the walker steps on alone while a lean angle falls away from centre and wind gusts (shown in the grass and the chimney flag a beat early) tip it; hold left or right to lean back, but a long hold overcorrects, and past 30 degrees you drop to the net and restart from the last of three marks; a crossing scores 10 plus 1 per second under 60, and 5 more if the lean never passed half the limit (forged by the crew on the engine and shell above, not by the original creators) | Hold left or right half of the canvas; arrows or A/D |
3535 | [Ice Fishing](ice-fishing/) | A 60-second round on a frozen lake: hold to let line out through the hole and watch the hook sink in the cut-away, a perch (1), trout (2) or pike (3) crossing the hook at its depth bites, then hold to reel and ease off to let the tension fall; full tension snaps the line and three snaps end the round (forged by the crew on the engine and shell above, not by the original creators) | Hold the canvas; hold space |
36 | [Tram Line](tram-line/) | A 120-second timetable over eight stops: hold to power, release to coast, brake so the front door lands on the yellow mark; within 0.5 m scores 3, within 2 m scores 1, overshooting the shelter scores 0 and strands the passengers, stopping between stops costs 1, and each second left at the last stop adds 1 (forged by the crew on the engine and shell above, not by the original creators) | Hold up or W (right half) to power, down or S (left half) to brake |
3637
3738 ## Run
3839 Requires [Node.js](https://nodejs.org/); nothing to install.
@@ -52,7 +53,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is
5253 Every page carries Open Graph and Twitter tags (between `og:begin` and `og:end`), and `og/<id>.png` is a 1200x630 card: the game's own opening frame, scaled 2x on white; `og/home.png` is a grid of all of them. Because the games are static, `bun scripts/og.mjs` makes them without a browser: it runs each page's scripts in a `vm` against a stub DOM, captures the canvas pixels and writes the PNG (zlib only, no dependency) and the tags. Run it after adding a game or changing a scene; `serve.test.mjs` fails when a card or its tags are missing or stale. Scenes are rendered with a seeded `Math.random`, so the cards are byte-for-byte reproducible. Absolute URLs use `ORIGIN` at the top of the script (the forge production site), so change it there if the site moves.
5354
5455 ## Add a game
55 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 as a card with its `kind`, `input` and `accent`, searchable and filterable by kind (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too, with the same `data-kind`, `data-input`, `--accent` and tags line). Then run `bun scripts/og.mjs` to make its share card and tags. 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, Domino Run, Campfire, Beekeeper, Bread Oven, Ice Fishing and Tightrope 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`.
56 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 as a card with its `kind`, `input` and `accent`, searchable and filterable by kind (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too, with the same `data-kind`, `data-input`, `--accent` and tags line). Then run `bun scripts/og.mjs` to make its share card and tags. 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, Domino Run, Campfire, Beekeeper, Bread Oven, Ice Fishing, Tightrope and Tram Line 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`.
5657
5758 - `shell.js` provides the game menu, the Rules popup, the credits and the background music.
5859 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
@@ -68,7 +69,7 @@ Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules
6869 - Depth-buffer edges: darker where an object sits in front, a warm rim on upper-left edges.
6970 - Large flat surfaces use closely spaced tones; wide steps make the dither read as a checkerboard.
7071 - Characters stay sharp: flat bands with no dither, a dark silhouette on their own pixels, patterns at least 3px wide.
71 - Ambient motion only in plants: grass and leaves sway in whole pixels at 8 fps, and stop under `prefers-reduced-motion`.
72 - Ambient motion only where the scene names it: grass and leaves sway in whole pixels at 8 fps, and Tram Line's waiting passengers shift their weight; all of it stops under `prefers-reduced-motion`.
7273
7374 ## License
7475 The code is under the [MIT License](LICENSE). The music is not: see [MUSIC.md](MUSIC.md).
index.html +1
@@ -83,6 +83,7 @@ footer a::after { content: none; }
8383 <li data-kind="Timing" data-input="Tap" style="--accent:#c0612b"><a href="bread-oven/">Bread Oven</a><span>Slide loaves into a wood-fired oven and pull each one out golden: golden 3, dark 1, a burnt loaf is a strike</span><span>Game forged by the crew</span><span class="tags">Timing · Tap</span></li>
8484 <li data-kind="Precision" data-input="Hold" style="--accent:#cf4b3a"><a href="tightrope/">Tightrope</a><span>Walk a wire between two rooftops, leaning against the wind to stay up: 10 plus 1 per second under 60, +5 for a steady crossing</span><span>Game forged by the crew</span><span class="tags">Precision · Hold</span></li>
8585 <li data-kind="Timing" data-input="Hold" style="--accent:#6fb3d2"><a href="ice-fishing/">Ice Fishing</a><span>Drop a line through the ice and reel each fish up before it snaps: hold to let out line, a fish at the hook depth bites, hold to reel but ease off as the tension rises</span><span>Game forged by the crew</span><span class="tags">Timing · Hold</span></li>
86 <li data-kind="Precision" data-input="Hold" style="--accent:#c9a227"><a href="tram-line/">Tram Line</a><span>Drive a tram along eight stops: brake so the door lands on the yellow mark, exact scores 3, overshoot scores nothing</span><span>Game forged by the crew</span><span class="tags">Precision · Hold</span></li>
8687 </ul>
8788 <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>
8889 </main>
og/home.png
Binary file not shown.
og/tram-line.png added
Binary file not shown.
serve.test.mjs +7
@@ -366,3 +366,10 @@ test('Beekeeper and its rules script are served without a track', async () => {
366366 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
367367 expect((await fetch(base + '/beekeeper/hive.js')).status).toBe(200);
368368 });
369
370 test('Tram Line and its rules script are served without a track', async () => {
371 const page = await fetch(base + '/tram-line/');
372 expect(page.status).toBe(200);
373 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
374 expect((await fetch(base + '/tram-line/line.js')).status).toBe(200);
375 });
shell.js +1
@@ -27,6 +27,7 @@ window.PixelPlays = (() => {
2727 { id: 'bread-oven', title: 'Bread Oven', blurb: 'Slide loaves into a wood-fired oven and pull each one out golden: golden 3, dark 1, a burnt loaf is a strike', kind: 'Timing', input: 'Tap', accent: '#c0612b', music: false, forged: true },
2828 { id: 'tightrope', title: 'Tightrope', blurb: 'Walk a wire between two rooftops, leaning against the wind to stay up: 10 plus 1 per second under 60, +5 for a steady crossing', kind: 'Precision', input: 'Hold', accent: '#cf4b3a', music: false, forged: true },
2929 { id: 'ice-fishing', title: 'Ice Fishing', blurb: 'Drop a line through the ice and reel each fish up before it snaps: hold to let out line, a fish at the hook depth bites, hold to reel but ease off as the tension rises', kind: 'Timing', input: 'Hold', accent: '#6fb3d2', music: false, forged: true },
30 { id: 'tram-line', title: 'Tram Line', blurb: 'Drive a tram along eight stops: brake so the door lands on the yellow mark, exact scores 3, overshoot scores nothing', kind: 'Precision', input: 'Hold', accent: '#c9a227', music: false, forged: true },
3031 ];
3132 const MUSIC_VOLUME = .4;
3233 const CREDITS = [
tram-line/index.html added +382
@@ -0,0 +1,382 @@
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>Tram Line</title>
7 <!-- og:begin -->
8 <meta name="description" content="Drive a tram along eight stops: brake so the door lands on the yellow mark, exact scores 3, overshoot scores nothing">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/tram-line/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Tram Line">
13 <meta property="og:description" content="Drive a tram along eight stops: brake so the door lands on the yellow mark, exact scores 3, overshoot scores nothing">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/tram-line/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/tram-line.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="Tram Line: 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: #8b877f; --paper: #fff; --accent: #c9a227; }
24 * { box-sizing: border-box; }
25 html, body { height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
26 body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; }
27 #stage { position: fixed; inset: 0; display: grid; place-items: center; }
28 canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; outline: none; }
29 .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; }
30 #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; }
31 #bottom { bottom: max(14px, env(safe-area-inset-bottom)); align-items: flex-end; }
32 .row { display: flex; align-items: center; gap: 8px; color: var(--accent); }
33 .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; }
34 .row span { color: var(--muted); }
35 #status { color: var(--muted); min-height: 1.35em; }
36 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
37 button:hover, button:focus-visible { color: var(--ink); }
38 </style>
39 </head>
40 <body>
41 <div id="stage"><canvas id="c" tabindex="0" aria-label="A short city tram on a cobbled street, heading for a shelter with a yellow mark painted on the kerb. Hold up or W to power, release to coast, hold down or S to brake. On a touch screen hold the right half to power and the left half to brake. Stop the front door on the yellow mark at each of eight stops: within half a metre scores 3, within two metres scores 1, overshooting the shelter scores nothing. 120 seconds, and each second left at the end adds a point."></canvas></div>
42 <div id="scores">
43 <div class="row"><b id="score">0</b><span>score</span></div>
44 <div class="row"><b id="stop">1</b><span>stop of 8</span></div>
45 <div class="row"><b id="speed">0</b><span>km/h</span></div>
46 <div class="row"><b id="clock">120</b><span>seconds left</span></div>
47 <div class="row"><b id="best">0</b><span>best</span></div>
48 </div>
49 <div class="hud" id="bottom">
50 <div id="status" role="status" aria-live="polite"></div>
51 <button id="mute" type="button" aria-pressed="false">sound on</button>
52 </div>
53 <script src="../shell.js"></script>
54 <script>
55 PixelPlays.mount({
56 id: 'tram-line',
57 rules: [
58 'Hold up or W (right half on touch) to power, release to coast, hold down or S (left half) to brake.',
59 'Stop the front door on the yellow mark: within 0.5 m scores 3, within 2 m scores 1.',
60 'Overshoot the shelter and it scores 0; a stop between stops costs 1. 120 seconds, each one left adds a point.',
61 ],
62 });
63 </script>
64 <script>window.PP_SCENE = { originY: 0, shadowX: 1.3, shadowY: -.12 };</script>
65 <script src="../engine.js"></script>
66 <script src="line.js"></script>
67 <script>
68 'use strict';
69
70 const STEP = Math.SQRT2 / 5; // one camera step moves the street exactly 2px right and 1px down
71 const CELL = STEP * 2, PHASES = 8; // the street repeats every 8 steps, so 8 baked frames of ground scroll it without a seam
72 const LEAD_STEPS = 28; // the front door sits 28 steps (about 8 m) left of the screen centre so the mark shows from far ahead
73 const BEST_KEY = 'pixel-plays-tram-line-best';
74 const ROAD = { mid: .6, half: 4.2 }, KERB_Y = 2.7, LANE = .75;
75 const CREAM = [236, 226, 200], RED = [186, 64, 52], GLASS = [58, 72, 92], STEEL = [96, 100, 112], DARK = [52, 52, 60];
76 const GOLD = [201, 162, 39], POST = [74, 78, 88], WOOD = [150, 106, 70];
77 const YELLOW = rgb(255, 214, 10), YELLOW_SOFT = rgb(244, 224, 128), YELLOW_MID = rgb(222, 178, 30), CHALK = rgb(250, 246, 232);
78 const COATS = [[200, 92, 74], [74, 120, 170], [96, 150, 104], [214, 168, 70], [140, 100, 160]];
79
80 /* ---------- state ---------- */
81 const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })();
82 let R = Line.newRound(best0, Date.now() & 0xffff);
83 const G = { time: 0, status: '', noteUntil: 0 };
84 const nodes = {};
85 for (const id of ['score', 'stop', 'speed', 'clock', 'best', 'status']) nodes[id] = document.getElementById(id);
86 function renderHud() {
87 nodes.score.textContent = R.score;
88 nodes.stop.textContent = Math.min(R.stop + 1, Line.STOPS);
89 nodes.speed.textContent = Math.round(R.v * 3.6);
90 nodes.clock.textContent = Math.ceil(Line.timeLeft(R));
91 nodes.best.textContent = Math.max(R.best, R.score);
92 }
93 function setStatus(text) {
94 if (text === G.status) return;
95 G.status = text;
96 nodes.status.textContent = text;
97 }
98 function note(text) { setStatus(text); G.noteUntil = G.time + 2.2; }
99 const HINT = 'hold up to power · release to coast · hold down to brake';
100
101 /* ---------- baked ground: the street at each of its eight scroll phases ---------- */
102 const mod = (a, n) => ((a % n) + n) % n;
103 const phases = [];
104 const baseZ = new Float32Array(W * H).fill(-1e9);
105 function streetColor(xw, y) {
outdated

ix and iy are never read. Remove them here and at the call in bakeGround.

outdated

ix and iy are never read. Remove them here and at the call in bakeGround.

106 if (Math.abs(Math.abs(y) - LANE) < .07) return rgb(...STEEL);
107 if (Math.abs(y) < 1.15 && mod(xw, STEP * 4) < .3) return rgb(118, 92, 70);
108 if (Math.abs(y - KERB_Y) < .08) return rgb(228, 224, 214);
109 if (y > KERB_Y) { // pavement slabs
110 const sx = mod(xw, STEP * 4) / (STEP * 4), sy = mod(y, 1.13) / 1.13;
111 const t = .94 + hash(Math.floor(xw / (STEP * 4)) & 1, Math.floor(y / 1.13)) * .08 - (sx < .04 || sy < .05 ? .1 : 0);
112 return rgb(214 * t, 206 * t, 190 * t);
113 }
114 const row = Math.floor((y + 9) / .5), u = xw / CELL + (row & 1) * .5, col = Math.floor(u);
115 const fu = u - col, fv = (y + 9) / .5 - row;
116 const track = Math.abs(y) < 1.3 ? .86 : 1;
117 if (fu < .1 || fv < .12) return rgb(112 * track, 106 * track, 104 * track);
118 const t = (.84 + hash(mod(col, 4), row) * .24) * track;
119 return rgb(168 * t, 160 * t, 152 * t);
120 }
121 function bakeGround() {
122 const member = new Uint8Array(W * H);
123 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
124 const g = unproject(ix + .5, iy + .5), i = iy * W + ix;
125 const e = Math.abs(g.y - ROAD.mid) / ROAD.half + (hash(ix, iy) - .5) * .1;
126 if (e > 1.04 || (e > .94 && hash(iy, ix) < (e - .94) / .1)) continue;
127 member[i] = 1; ground[i] = 1;
128 baseZ[i] = (g.x + g.y) / R2 * COS;
129 }
130 groundZ.set(baseZ);
131 for (let k = 0; k < PHASES; k++) {
132 const buf = new Uint32Array(W * H).fill(rgb(255, 255, 255));
133 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
134 const i = iy * W + ix;
135 if (!member[i]) continue;
136 const g = unproject(ix + .5, iy + .5);
137 buf[i] = streetColor(g.x + k * STEP, g.y);
138 }
139 phases.push(buf);
140 }
141 }
142
143 /* ---------- drawing ---------- */
144 // paint flat colour on the street without touching depth, so shadows and edges ignore it
145 function paint(x0, x1, y0, y1, color) {
146 for (let x = x0; x <= x1; x += .06) for (let y = y0; y <= y1; y += .06) {
147 const p = project(x, y, 0), ix = p.sx | 0, iy = p.sy | 0;
148 if (ix >= 0 && iy >= 0 && ix < W && iy < H && ground[iy * W + ix]) pix[iy * W + ix] = color;
149 }
150 }
151 const visible = (x, ahead, behind) => x > -behind && x < ahead;
152 function markings(cam) {
153 for (let n = 0; n < Line.STOPS; n++) {
154 const m = Line.markAt(n) - cam;
155 if (!visible(m, 36, 14)) continue;
156 paint(m - Line.NEAR, m + Line.NEAR, 2.05, 3.1, YELLOW_SOFT);
157 paint(m - Line.EXACT, m + Line.EXACT, 2.05, 3.1, YELLOW_MID);
158 paint(m - .2, m + .2, 1.35, 3.1, YELLOW);
159 // countdown ticks, one bar per ten metres out
160 for (let t = 1; t <= 3; t++) for (let b = 0; b < t; b++) paint(m - t * 10 - b * .6, m - t * 10 - b * .6 + .3, 1.5, 2.45, CHALK);
161 }
162 }
163 function shelter(m, i) {
164 const x0 = m - Line.SHELTER_AFTER, x1 = m + Line.SHELTER_AFTER;
165 for (const x of [x0, x1]) for (const y of [3.4, 4.7]) capsule([x, y, 0], [x, y, 3], .1, .1, () => POST, 'solid');
166 box(x0 - .3, 3.2, 3, x1 + .3, 4.9, 3.25, GOLD, 5 + i);
167 box(x0 + .6, 4.2, .45, x1 - .6, 4.7, .75, WOOD, 11);
168 // the stop sign on the mark, tall enough to read from far up the line
169 capsule([m, 2.45, 0], [m, 2.45, 5.1], .08, .08, () => POST, 'solid');
170 box(m - .55, 2.4, 3.9, m + .55, 2.55, 5.1, [255, 214, 10], 31);
171 box(m - .3, 2.4, 4.2, m + .3, 2.6, 4.8, [28, 27, 25], 33);
172 castShadow(m, 2.45, 5, .4, 1, 0);
173 for (let x = x0; x <= x1; x += .8) for (const y of [3.4, 4.7]) castShadow(x, y, 3.1, .45, 1, 0);
174 castShadow(x0, 3.4, 1.5, .25, 1, 0); castShadow(x1, 4.7, 1.5, .25, 1, 0);
175 }
176 function passenger(m, i, k, step, raised) {
177 const x = m + (k % 2 ? 1 : -1) * (.9 + (k >> 1) * 1.1), coat = COATS[(i + k) % COATS.length], j = hash(step * 3 + k, i);
178 figure(x, 3.75 + (k & 1) * .35, -Math.PI / 2, {
179 stance: .1 + j * .3, lean: (j - .5) * .12, armR: raised ? 2.7 : j * .15, armL: .08,
180 }, { shirt: coat, stripe: coat.map(v => v * .8), legs: [60, 62, 78], skin: [226, 178, 140], hair: [58, 44, 36] }, dynamicAdd);
181 }
182 function tram(door) {
183 const x1 = door + 1.6, x0 = door - 9.6;
184 for (const bx of [x0 + 1.6, x1 - 2.6]) box(bx - 1, -1.0, .1, bx + 1, 1.0, .65, DARK, 3);
185 box(x0, -1.2, .65, x1, 1.2, 2.7, CREAM, 17);
186 box(x0 + .2, -1.25, .65, x1 - .2, 1.3, 1.05, RED, 19);
187 for (let x = x0 + .8; x < x1 - 1; x += 2.3) if (Math.abs(x - door) > 1.4) box(x, -1.2, 1.5, x + 1.5, 1.32, 2.3, GLASS, 21);
188 box(door - .75, -1.2, 1.1, door + .75, 1.36, 2.45, [250, 242, 214], 23); // the front door
189 box(door - .78, -1.2, 1.1, door - .66, 1.4, 2.45, [255, 214, 10], 25); // yellow door frame: this edge lands on the mark
190 box(door + .66, -1.2, 1.1, door + .78, 1.4, 2.45, [255, 214, 10], 27);
191 box(x0 + .3, -1.0, 2.7, x1 - .3, 1.0, 2.95, DARK, 29);
192 capsule([door - 5, 0, 2.95], [door - 4.4, 0, 3.7], .06, .06, () => STEEL, 'solid');
193 capsule([door - 5.6, 0, 3.7], [door - 3.2, 0, 3.7], .06, .06, () => STEEL, 'solid');
194 for (let x = x0; x <= x1; x += .7) for (const y of [-1, 0, 1]) for (const z of [1, 2, 3]) castShadow(x, y, z, .45, 1, 0);
195 }
196 /* ---------- sprites: the tram and each shelter are drawn once, then slid across the street in whole pixels ---------- */
197 // draw() onto empty buffers and keep what it wrote: pixels with depth, and shadow strength
198 function record(drawIt) {
199 const savedPix = pix.slice(), savedZ = zb.slice();
200 zb.fill(-1e9); shadowMask.fill(0);
201 drawIt();
202 flushShadows();
203 pendingShadows.length = 0;
204 const hits = [], shade = [];
205 for (let i = 0; i < zb.length; i++) {
206 if (zb[i] > -1e8) hits.push(i, pix[i], zb[i]);
207 if (shadowMask[i]) shade.push(i, shadowMask[i]);
208 }
209 pix.set(savedPix); zb.set(savedZ); shadowMask.fill(0);
210 return { hits, shade };
211 }
212 // k camera steps from where the sprite was drawn is 2k px right and k px down, and k steps nearer the camera along x
213 function blit(sprite, k) {
214 const dx = 2 * k, dy = k, dd = k * STEP / R2 * COS, { hits, shade } = sprite;
215 for (let n = 0; n < hits.length; n += 3) {
216 const i = hits[n], ix = i % W + dx, iy = (i / W | 0) + dy;
217 if (ix < 0 || iy < 0 || ix >= W || iy >= H) continue;
218 const t = iy * W + ix, d = hits[n + 2] + dd;
219 if (d <= zb[t]) continue;
220 zb[t] = d; pix[t] = hits[n + 1];
221 }
222 for (let n = 0; n < shade.length; n += 2) {
223 const i = shade[n], ix = i % W + dx, iy = (i / W | 0) + dy;
224 if (ix < 0 || iy < 0 || ix >= W || iy >= H) continue;
225 const t = iy * W + ix;
226 if (shadowMask[t] < shade[n + 1]) shadowMask[t] = shade[n + 1];
227 }
228 }
229 const DOOR_X = -LEAD_STEPS * STEP;
230 const sprites = { tram: null, shelters: [], passengers: new Map() };
231 const baseOf = i => mod(Line.markAt(i), STEP);
232 const stepsTo = (i, n) => Math.round((Line.markAt(i) - baseOf(i)) / STEP) - n;
233 function passengerSprites(i, t, n) {
234 const raised = !!R.results[i] && R.results[i].lost > 0;
235 for (let k = 0; k < Line.waitingAt(i); k++) {
236 const step = STILL ? 0 : Math.floor(t * .7 + hash(i, k) * 5), key = `${step}:${raised}`, slot = `${i}:${k}`;
237 let held = sprites.passengers.get(slot);
238 if (!held || held.key !== key) {
239 held = { key, sprite: record(() => passenger(baseOf(i), i, k, step, raised)) };
240 sprites.passengers.set(slot, held);
241 }
242 blit(held.sprite, stepsTo(i, n));
243 }
244 }
245 function draw() {
246 const n = Math.round(R.x / STEP) + LEAD_STEPS, cam = n * STEP; // the camera moves in whole steps so the ground scrolls in whole pixels
247 pix.set(phases[mod(n, PHASES)]);
248 zb.set(baseZ);
249 markings(cam);
250 for (let i = 0; i < Line.STOPS; i++) {
251 const m = Line.markAt(i) - cam;
252 if (!visible(m, 36, 16)) continue;
253 blit(sprites.shelters[i] || (sprites.shelters[i] = record(() => shelter(baseOf(i), i))), stepsTo(i, n));
254 const result = R.results[i];
255 if (!result || result.lost) passengerSprites(i, G.time, n);
256 }
257 blit(sprites.tram || (sprites.tram = record(() => tram(DOOR_X))), 0);
258 applyShadows(groundZ);
259 shadeEdges();
260 ctx.putImageData(image, 0, 0);
261 }
262
263 /* ---------- game ---------- */
264 const ctl = { power: false, brake: false };
265 const keys = new Set(), touches = new Map();
266 function readControls() {
267 const sides = [...touches.values()];
268 ctl.power = keys.has('up') || sides.includes('power');
269 ctl.brake = keys.has('down') || sides.includes('brake');
270 }
271 function act(events) {
272 for (const e of events) {
273 if (e.type === 'stop') {
274 note(e.points === 3 ? `dead on the mark: +3` : e.points ? `${Math.abs(e.offset).toFixed(1)} m off: +1` : `${Math.abs(e.offset).toFixed(1)} m off: nothing`);
275 sound(e.points === 3 ? 'chime' : e.points ? 'thud' : 'buzz');
276 }
277 if (e.type === 'overshoot') { note(`overshot: ${e.lost} passengers left waiting`); sound('buzz'); }
278 if (e.type === 'stray') { note('stopped between stops: -1'); sound('buzz'); }
279 if (e.type === 'over') {
280 if (R.record) try { localStorage.setItem(BEST_KEY, String(R.best)); } catch (err) { /* private window: keep it for this visit */ }
281 const why = e.reason === 'line' ? `end of the line · +${e.bonus} for time` : 'out of time';
282 setStatus(`${why} · ${R.score}${R.record ? ' · new best' : ` · best ${R.best}`} · tap or press space to drive again`);
283 }
284 }
285 renderHud();
286 }
287 function restart() {
288 const next = Line.again(R);
289 if (!next) return false;
290 R = next;
291 note(HINT);
292 renderHud();
293 return true;
294 }
295 function update(dt) {
296 G.time += dt;
297 act(Line.advance(R, dt, ctl));
298 renderHud();
299 if (R.phase === 'play' && G.time >= G.noteUntil) {
300 const d = Line.distanceToMark(R);
301 setStatus(R.dwell > 0 ? 'doors open' : `stop ${R.stop + 1} · mark ${d >= 0 ? Math.round(d) + ' m ahead' : Math.round(-d) + ' m behind'}`);
302 }
303 }
304
305 /* ---------- input ---------- */
306 const KEYMAP = { ArrowUp: 'up', w: 'up', W: 'up', ArrowDown: 'down', s: 'down', S: 'down' };
307 canvas.addEventListener('keydown', e => {
308 const k = KEYMAP[e.key];
309 if (!k && e.key !== ' ') return;
310 e.preventDefault();
311 ensureAudio();
312 if (e.repeat) return;
313 if (restart()) return;
314 if (k) keys.add(k);
315 readControls();
316 });
317 canvas.addEventListener('keyup', e => {
318 const k = KEYMAP[e.key];
319 if (!k) return;
320 keys.delete(k);
321 readControls();
322 });
323 canvas.addEventListener('blur', () => { keys.clear(); touches.clear(); readControls(); });
324 canvas.addEventListener('pointerdown', e => {
325 ensureAudio();
326 canvas.focus({ preventScroll: true });
327 if (restart()) return;
328 const rect = canvas.getBoundingClientRect();
329 touches.set(e.pointerId, e.clientX - rect.left > rect.width / 2 ? 'power' : 'brake');
330 try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* synthetic pointers have nothing to capture */ }
331 readControls();
332 });
333 for (const type of ['pointerup', 'pointercancel']) canvas.addEventListener(type, e => { touches.delete(e.pointerId); readControls(); });
334
335 /* ---------- sound ---------- */
336 let audio = null, muted = false;
337 function ensureAudio() {
338 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
339 const AC = window.AudioContext || window.webkitAudioContext;
340 if (AC) audio = new AC();
341 }
342 function sound(kind) {
343 if (!audio || muted) return;
344 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
345 const spec = {
346 thud: [180, 90, .12, .08, 'sine'],
347 chime: [660, 990, .3, .07, 'sine'],
348 buzz: [150, 70, .3, .06, 'sawtooth'],
349 }[kind];
350 osc.type = spec[4];
351 osc.frequency.setValueAtTime(spec[0], now);
352 osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]);
353 gain.gain.setValueAtTime(spec[3], now);
354 gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]);
355 osc.connect(gain).connect(audio.destination);
356 osc.start(now); osc.stop(now + spec[2] + .01);
357 }
358 const muteButton = document.getElementById('mute');
359 muteButton.addEventListener('click', () => {
360 muted = !muted;
361 muteButton.textContent = muted ? 'sound off' : 'sound on';
362 muteButton.setAttribute('aria-pressed', String(muted));
363 });
364
365 /* ---------- fit and boot ---------- */
366 addEventListener('resize', fit);
367 fit();
368 bakeGround();
369 note(HINT);
370 renderHud();
371 canvas.focus({ preventScroll: true });
372 let last = performance.now();
373 function frame(now) {
374 update(Math.min(.04, (now - last) / 1000));
375 last = now;
376 draw();
377 requestAnimationFrame(frame);
378 }
379 requestAnimationFrame(frame);
380 </script>
381 </body>
382 </html>
tram-line/line.js added +105
@@ -0,0 +1,105 @@
1 'use strict';
2 // The tram line rules: a tram with weight on a straight line of eight stops, scored by how close the front door
3 // stops to the painted mark, with a 120-second timetable. Metres and seconds; plain numbers in, plain numbers out,
4 // no DOM. The page draws what this decides.
5 (function (root) {
6 const STOPS = 8, FIRST_STOP = 28, STOP_GAP = 70; // mark n sits FIRST_STOP + n * STOP_GAP metres down the line
7 const ACCEL = 2.5, FRICTION = .35, BRAKE = 3.5; // m/s^2: power, rolling drag while coasting, brake
8 const MAX_SPEED = 10;
9 const EXACT = .5, NEAR = 2, SHELTER_AFTER = 3; // door within EXACT of the mark scores 3, within NEAR scores 1; the shelter ends 3 m past the mark
10 const SCORES = { exact: 3, near: 1, far: 0, overshoot: 0 };
11 const STOP_SPEED = .12, SETTLE = .4; // under STOP_SPEED for SETTLE seconds counts as stopped
12 const MOVING_SPEED = 1, STRAY_AFTER = 1, STRAY_PENALTY = 1;
13 const DWELL = 1.2, ROUND_TIME = 120, RESTART_AFTER = .6;
14
15 const finite = v => (Number.isFinite(v) ? v : 0);
16 const isStop = n => Number.isInteger(n) && n >= 0 && n < STOPS;
17 const markAt = n => (isStop(n) ? FIRST_STOP + n * STOP_GAP : NaN);
18 const waitingAt = n => (isStop(n) ? 2 + (n * 3) % 4 : 0); // passengers at the shelter: 2 to 5
19 // metres a tram at speed v needs to stop under the brake
20 const brakingDistance = v => { v = Math.max(0, finite(v)); return v * v / (2 * BRAKE); };
21 // points for a stop this far from the mark (positive is past it)
22 function scoreFor(offset) {

finite(NaN) is 0, so a non-finite offset scores 3. Return SCORES.far when the offset is not finite.

23 if (!Number.isFinite(offset)) return SCORES.far;
24 const d = Math.abs(offset);
25 return d <= EXACT ? SCORES.exact : d <= NEAR ? SCORES.near : SCORES.far;
26 }
27
28 function newRound(best = 0, seed = 0) {
29 return {
30 phase: 'play', time: 0, timer: 0, score: 0, bonus: 0, stop: 0, x: 0, v: 0, still: 0, dwell: 0, rolling: false, judged: false,
31 strays: 0, lost: 0, results: [], best: Math.max(0, finite(best)), record: false, seed: finite(seed) >>> 0, reason: '',
32 };
33 }
34 const timeLeft = s => Math.max(0, ROUND_TIME - s.time);
35 // metres from the front door to the mark of the stop ahead (negative once past it)
36 const distanceToMark = s => (isStop(s.stop) ? markAt(s.stop) - s.x : 0);
37
38 function finish(s, reason, events) {
39 s.phase = 'over'; s.reason = reason; s.timer = 0; s.v = 0;
40 if (reason === 'line') { s.bonus = Math.floor(timeLeft(s)); s.score += s.bonus; }
41 if (s.score > s.best) { s.best = s.score; s.record = true; }
42 events.push({ type: 'over', reason, score: s.score, bonus: s.bonus, lost: s.lost, record: s.record });
43 }
44 function arrive(s, result, events) {
45 s.results.push(result);
46 s.score += result.points;
47 s.lost += result.lost;
48 s.rolling = false; s.judged = true; s.still = 0; // judged: a tram still braking from this stop is not setting off
49 events.push({ type: result.lost ? 'overshoot' : 'stop', ...result });
50 s.stop++;
51 if (s.stop >= STOPS) finish(s, 'line', events);
52 else if (!result.lost) s.dwell = DWELL;
53 }
54 // move the tram: speed and distance over dt under the given controls ({ power, brake })
55 function drive(s, dt, input) {
56 const power = !!(input && input.power), brake = !!(input && input.brake);
57 let a = 0;
58 if (brake) a = -BRAKE;
59 else if (power) a = ACCEL - (s.v > 0 ? FRICTION : 0);
60 else a = -FRICTION;
61 if (s.v >= MAX_SPEED && a > 0) a = 0;
62 let v = s.v + a * dt;
63 if (v < 0) { s.x += s.v * s.v / (2 * -a); s.v = 0; return; }
64 if (v > MAX_SPEED) v = MAX_SPEED;
65 s.x += (s.v + v) / 2 * dt;
66 s.v = v;
67 }
68 function advance(s, dt, input) {
69 const events = [];
70 dt = Math.max(0, Math.min(.1, finite(dt)));
71 if (s.phase !== 'play') { s.timer += dt; return events; }
72 s.time += dt;
73 if (s.dwell > 0) { s.dwell = Math.max(0, s.dwell - dt); s.v = 0; }
74 else drive(s, dt, input);
75 // rolling means set off from rest since the last stop was judged, so a halt after an overshoot is not also a stray
76 if (s.v <= MOVING_SPEED) s.judged = false;
77 else if (!s.judged) s.rolling = true;
78 const mark = markAt(s.stop);
79 if (s.x > mark + SHELTER_AFTER && s.v > STOP_SPEED) {
80 arrive(s, { index: s.stop, offset: s.x - mark, points: SCORES.overshoot, lost: waitingAt(s.stop) }, events);
81 } else if (s.v < STOP_SPEED && s.dwell <= 0) {
82 s.still += dt;
83 const offset = s.x - mark;
outdated

Right after an overshoot, rolling is true again because the tram is still faster than MOVING_SPEED while it brakes. When it halts just past the shelter, this branch charges −1 and replaces the overshoot message. Keep a halt that follows an overshoot from counting as a stray, and add a test that fails today.

outdated

Still fires right after an overshoot: arrive() cleared rolling, but the tram keeps braking from above MOVING_SPEED, so rolling is set again and this branch charges −1 for the same mistake. Only count a stray once the tram has started rolling again from rest after the last judged stop.

84 if (s.still >= SETTLE && offset >= -NEAR && offset <= SHELTER_AFTER) {
85 arrive(s, { index: s.stop, offset, points: scoreFor(offset), lost: 0 }, events);
86 } else if (s.rolling && s.still >= STRAY_AFTER) {
87 s.rolling = false; s.strays++;
88 s.score = Math.max(0, s.score - STRAY_PENALTY);
89 events.push({ type: 'stray', penalty: STRAY_PENALTY });
90 }
91 } else s.still = 0;
92 if (s.phase === 'play' && s.time >= ROUND_TIME) { s.time = ROUND_TIME; finish(s, 'time', events); }
93 return events;
94 }
95 // a tap after the round has been over for a moment starts the next one; otherwise null
96 function again(s) {
97 return s.phase === 'over' && s.timer > RESTART_AFTER ? newRound(s.best, s.seed + 1) : null;
98 }
99
100 const api = {
101 STOPS, FIRST_STOP, STOP_GAP, ACCEL, FRICTION, BRAKE, MAX_SPEED, EXACT, NEAR, SHELTER_AFTER, SCORES, STRAY_AFTER, STRAY_PENALTY,
102 DWELL, ROUND_TIME, RESTART_AFTER, markAt, waitingAt, brakingDistance, scoreFor, newRound, timeLeft, distanceToMark, advance, again,
103 };
104 if (typeof module !== 'undefined') module.exports = api; else root.Line = api;
105 })(typeof window !== 'undefined' ? window : globalThis);
tram-line/line.test.mjs added +163
@@ -0,0 +1,163 @@
1 import { test, expect } from 'bun:test';
2 import { STOPS, MAX_SPEED, BRAKE, DWELL, ROUND_TIME, EXACT, NEAR, SHELTER_AFTER, markAt, waitingAt, brakingDistance, scoreFor, newRound, timeLeft, distanceToMark, advance, again } from './line.js';
3
4 const run = (s, seconds, input) => { const out = []; for (let t = 0; t < seconds - 1e-9; t += 1 / 60) out.push(...advance(s, 1 / 60, input)); return out; };
5 // a tram that has stopped this far from the next mark, ready to be judged
6 function stopAt(s, offset) {
7 s.x = markAt(s.stop) + offset; s.v = 0; s.rolling = true;
8 return run(s, .6);
9 }
10 const power = { power: true }, brake = { brake: true };
11
12 test('holding power accelerates up to the top speed and no further', () => {
13 const s = newRound();
14 run(s, 1, power);
15 expect(s.v).toBeGreaterThan(2);
16 run(s, 10, power);
17 expect(s.v).toBe(MAX_SPEED);
18 });
19
20 test('coasting slows the tram but it keeps rolling', () => {
21 const s = newRound();
22 run(s, 6, power);
23 const v = s.v, x = s.x;
24 run(s, 3, {});
25 expect(s.v).toBeLessThan(v);
26 expect(s.v).toBeGreaterThan(v / 2);
27 expect(s.x).toBeGreaterThan(x + 15);
28 });
29
30 test('braking from top speed stops the tram within the known distance', () => {
31 const s = newRound();
32 s.v = MAX_SPEED;
33 const x = s.x;
34 run(s, 5, brake);
35 expect(s.v).toBe(0);
36 expect(s.x - x).toBeCloseTo(brakingDistance(MAX_SPEED), 1);
37 expect(brakingDistance(MAX_SPEED)).toBeCloseTo(100 / (2 * BRAKE), 6);
38 expect(s.x - x).toBeLessThan(15);
39 });
40
41 test('the brake beats the power and the tram never reverses', () => {
42 const s = newRound();
43 s.v = 3;
44 run(s, 3, { power: true, brake: true });
45 expect(s.v).toBe(0);
46 run(s, 2, brake);
47 expect(s.x).toBeGreaterThan(0);
48 });
49
50 test('stop scoring: 0.3 m scores 3, 1.5 m scores 1, 2.5 m scores 0', () => {
51 expect(scoreFor(.3)).toBe(3);
52 expect(scoreFor(-.5)).toBe(3);
53 expect(scoreFor(1.5)).toBe(1);
54 expect(scoreFor(-2)).toBe(1);
55 expect(scoreFor(2.5)).toBe(0);

This makes a NaN offset score a perfect 3. Bad input should score SCORES.far (0). Fix scoreFor and change this expectation to 0.

56 expect(scoreFor(NaN)).toBe(0);
outdated

This asserts the bug. It should be toBe(0).

57 expect(scoreFor(Infinity)).toBe(0);
58 let s = newRound(); let ev = stopAt(s, .3);
59 expect(ev[0]).toMatchObject({ type: 'stop', index: 0, points: 3 });
60 expect(s.score).toBe(3); expect(s.stop).toBe(1);
61 s = newRound(); stopAt(s, -1.5);
62 expect(s.score).toBe(1);
63 s = newRound(); ev = stopAt(s, SHELTER_AFTER - .5);
64 expect(ev[0]).toMatchObject({ type: 'stop', points: 0, lost: 0 });
65 });
66
67 test('overshooting the shelter scores 0 and loses the waiting passengers', () => {
68 const s = newRound();
69 s.x = markAt(0) + SHELTER_AFTER - .05; s.v = 5;
70 const ev = run(s, .5, {});
71 expect(ev[0]).toMatchObject({ type: 'overshoot', index: 0, points: 0, lost: waitingAt(0) });
72 expect(s.score).toBe(0);
73 expect(s.lost).toBe(waitingAt(0));
74 expect(s.stop).toBe(1);
75 expect(distanceToMark(s)).toBeGreaterThan(0);
76 });
77
78 test('an overshoot braked to rest past the shelter is one mistake, not also a stray', () => {
79 const s = newRound();
80 s.score = 4; s.x = markAt(0) - 2; s.v = 6.5;
81 const ev = run(s, 8, brake);
82 expect(ev.map(e => e.type)).toEqual(['overshoot']);
83 expect(s.score).toBe(4);
84 expect(s.strays).toBe(0);
85 expect(s.v).toBe(0);
86 run(s, 6, power); run(s, 8, brake); // setting off again and halting short of the next stop is a stray
87 expect(s.strays).toBe(1);
88 });
89
90 test('stopping well short of a stop for over a second is a 1-point penalty, once', () => {
91 const s = newRound();
92 s.score = 4; s.x = 20; s.v = 5; s.rolling = true;
93 const ev = run(s, 8, brake);
94 expect(ev.filter(e => e.type === 'stray').length).toBe(1);
95 expect(s.score).toBe(3);
96 expect(s.stop).toBe(0);
97 run(s, 3, {});
98 expect(s.score).toBe(3);
99 });
100
101 test('a tram that has not moved yet is not penalised, and the score never goes below 0', () => {
102 const s = newRound();
103 run(s, 5, {});
104 expect(s.score).toBe(0);
105 expect(s.strays).toBe(0);
106 s.x = 20; s.v = 5; s.rolling = true;
107 run(s, 8, brake);
108 expect(s.score).toBe(0);
109 });
110
111 test('the doors hold the tram for a moment after a stop', () => {
112 const s = newRound();
113 stopAt(s, 0);
114 expect(s.dwell).toBeGreaterThan(0);
115 run(s, .3, power);
116 expect(s.v).toBe(0);
117 run(s, DWELL, power);
118 expect(s.v).toBeGreaterThan(0);
119 });
120
121 test('the eighth stop ends the round and adds a point for each second left', () => {
122 const s = newRound();
123 s.score = 10; s.time = 80; s.stop = STOPS - 1;
124 const ev = stopAt(s, 0);
125 expect(s.phase).toBe('over');
126 const over = ev.find(e => e.type === 'over');
127 expect(over).toMatchObject({ reason: 'line', bonus: Math.floor(ROUND_TIME - s.time) });
128 expect(s.score).toBe(10 + 3 + s.bonus);
129 expect(s.bonus).toBeGreaterThanOrEqual(38);
130 expect(s.record).toBe(true);
131 });
132
133 test('the timetable ends the round without a bonus', () => {
134 const s = newRound(0, 1);
135 s.time = ROUND_TIME - .05;
136 const ev = run(s, .2, {});
137 expect(s.phase).toBe('over');
138 expect(ev.find(e => e.type === 'over')).toMatchObject({ reason: 'time', bonus: 0 });
139 expect(timeLeft(s)).toBe(0);
140 });
141
142 test('a tap after the round has settled starts the next with the best kept', () => {
143 const s = newRound(5, 1);
144 s.score = 9; s.time = ROUND_TIME - .01;
145 run(s, .1, {});
146 expect(again(s)).toBeNull();
147 run(s, 1, {});
148 const next = again(s);
149 expect(next.phase).toBe('play');
150 expect(next.best).toBe(9);
151 expect(again(next)).toBeNull();
152 });
153
154 test('marks are eight, evenly spaced, and bad input is ignored', () => {
155 expect(Array.from({ length: STOPS }, (_, i) => markAt(i)).every((m, i, a) => !i || m - a[i - 1] === 70)).toBe(true);
156 expect(markAt(8)).toBeNaN();
157 const s = newRound(NaN, NaN);
158 advance(s, NaN, null);
159 advance(s, -1, { power: 1 });
160 expect(s.x).toBe(0);
161 expect(s.best).toBe(0);
162 expect(EXACT).toBeLessThan(NEAR);
163 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs