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

Migrated from github.com/amirmushichge/pixel-plays

Add Paper Route: throw newspapers onto porches from a passing bike #15

Merged opened this

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

Merged

quill/pixel-plays:quill/6-add-paper-route-throw-newspapers-onto-po → main 3 commits fork

  • Merged. quill/6-add-paper-route-throw-newspapers-onto-po was merged into main as c3cdcca.

Review

Sign in to review this change.
7 files changed +644 −2
README.md +2 −1
@@ -10,6 +10,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
1010 | Game | What you do | Input |
1111 |------|-------------|-------|
1212 | [Balote](balote/) | Bocce against a bot, first to 5 | Drag back and release; arrows + space |
13 | [Paper Route](paper-route/) | Ten newspapers thrown from a passing bike: porch 3, lawn 1, a window costs 2 (forged by the crew on the engine and shell above, not by the original creators) | Tap; space |
1314 | [Stari Most](stari-most/) | Five dives off the old bridge, flip and enter the water vertically | Hold and release |
1415 | [Rooftop Laundry](laundry/) | Get the washing into the basket before the storm | Drag; space |
1516 | [Tie-Break](tie-break/) | Clay-court tie-break against a bot, the moment you hit decides where the ball lands | Tap; space |
@@ -29,7 +30,7 @@ Then open http://127.0.0.1:5300/. `PORT` and `HOST` override the port and addres
2930 On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. The app keeps no state, so it does not need `FORGE_APP_DATA`. `bun test` checks that the server answers every game page and track.
3031
3132 ## Add a game
32 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`. 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 and Kite Hill 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`.
33 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`. 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 and Paper Route 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`.
3334
3435 - `shell.js` provides the game menu, the Rules popup, the credits and the background music.
3536 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
engine.js +1 −1
@@ -184,7 +184,7 @@ function drawTufts(t) {
184184 }
185185 function drawLeaves(t) {
186186 for (const leaf of leaves) {
187 const reach = clamp((leaf.z - 2.5) / 3, .3, 1);
187 const reach = leaf.reach || clamp((leaf.z - 2.5) / 3, .3, 1); // low hedges set their own
188188 const swayX = (Math.sin(t * .9 + leaf.x * .5 + leaf.z * .7) + .55 * Math.sin(t * 2.3 + leaf.k * 1.7)) * reach;
189189 const dx = Math.round(swayX * .9), dy = Math.round(Math.sin(t * 1.3 + leaf.y + leaf.k) * reach * .45);
190190 const px = leaf.pixels;
paper-route/index.html added +379
@@ -0,0 +1,379 @@
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>Paper Route</title>
7 <style>
8 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; --accent: #c4503c; }
9 * { box-sizing: border-box; }
10 html, body { height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
11 body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; }
12 #stage { position: fixed; inset: 0; display: grid; place-items: center; }
13 canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; outline: none; }
14 .hud { position: fixed; left: max(16px, env(safe-area-inset-left)); right: max(16px, env(safe-area-inset-right)); display: flex; justify-content: space-between; gap: 16px; pointer-events: none; }
15 #scores { position: fixed; top: max(14px, env(safe-area-inset-top)); left: max(16px, env(safe-area-inset-left)); display: grid; gap: 2px; pointer-events: none; }
16 #bottom { bottom: max(14px, env(safe-area-inset-bottom)); align-items: flex-end; }
17 .row { display: flex; align-items: center; gap: 8px; color: var(--accent); }
18 .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; }
19 .row span { color: var(--muted); }
20 .dots { display: flex; gap: 3px; }
21 .dots i { width: 6px; height: 6px; background: var(--accent); }
22 .dots i.off { opacity: .16; }
23 #status { color: var(--muted); }
24 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
25 button:hover, button:focus-visible { color: var(--ink); }
26 </style>
27 </head>
28 <body>
29 <div id="stage"><canvas id="c" tabindex="0" aria-label="A street of four houses with a cyclist riding past. Tap the picture or press space to throw a paper: porch scores 3, lawn 1, a window costs 2."></canvas></div>
30 <div id="scores">
31 <div class="row"><b id="score">0</b><span>score</span></div>
32 <div class="row"><b id="best">0</b><span>best</span><span class="dots" id="papers"></span></div>
33 </div>
34 <div class="hud" id="bottom">
35 <div id="status" role="status" aria-live="polite"></div>
36 <button id="mute" type="button" aria-pressed="false">sound on</button>
37 </div>
38 <script src="../shell.js"></script>
39 <script>
40 PixelPlays.mount({
41 id: 'paper-route',
42 rules: [
43 'Ten papers, one cyclist riding past at a steady pace. Tap or press space to throw.',
44 'The moment you tap decides where the paper lands: the bike\'s speed carries it ahead.',
45 'Porch 3 points, lawn 1, a window breaks and costs 2. A paper that flies past the end of the street scores nothing.',
46 ],
47 });
48 </script>
49 <script>window.PP_SCENE = { originY: 24, shadowX: 1.3, shadowY: -.12 };</script>
50 <script src="../engine.js"></script>
51 <script src="route.js"></script>
52 <script>
53 'use strict';
54
55 const ROUTE = window.PaperRoute;
56 const KIND_ROAD = 6;
57 const ROAD = [[92, 94, 108], [97, 99, 113], [103, 105, 118]], WALK = [[204, 200, 192], [212, 208, 200], [219, 215, 207]];
58 const LANE = rgb(226, 214, 168), JOINT = rgb(176, 172, 166);
59 const HOUSE_WALLS = [[228, 198, 160], [166, 196, 210], [216, 164, 150], [196, 208, 158]];
60 const HOUSE_ROOFS = [[150, 84, 72], [92, 100, 130], [128, 92, 70], [84, 112, 98]];
61 const DOORS = [[122, 66, 54], [64, 88, 120], [88, 112, 78], [150, 100, 52]];
62 const SLAB = [204, 196, 184], PAPER_C = [250, 248, 238], TIRE = [38, 38, 50], FRAME = [200, 62, 50], METAL = [206, 206, 212];
63 const RIDER = { shirt: [214, 70, 56], stripe: [244, 236, 218], legs: [52, 62, 88], hair: [58, 40, 30], skin: [222, 170, 132] };
64 const GLASS = [150, 200, 222], WOOD = [236, 228, 210];
65 const BUSH_TONES = [LEAF_DEEP, LEAF_MID, LEAF_MID, LEAF_SILVER], BLOOM = [214, 92, 112];
66 const WALL_H = 3.4, BACK_Y = -5.2, WALL_Y = ROUTE.WALL_Y, BIKE_Y = ROUTE.ROAD_Y;
67 const WINDOW_BOTTOM = ROUTE.WINDOW_Z[0], WINDOW_TOP = ROUTE.WINDOW_Z[1];
68 const COLORS = c => rampOf(c);
69
70 function groundColor(x, y, ix, iy, i) {
71 const edge = Math.pow(Math.pow(Math.abs(x) / 17, 4) + Math.pow(Math.abs(y + 1.4) / 6.2, 4), .25);
72 const rough = edge + (noise(x * 1.3, y * 1.3) - .5) * .13;
73 if (rough > 1.04) return 0;
74 if (rough > .93 && hash(ix, iy) < (rough - .93) / .11) return 0;
75 const fine = hash(ix, iy);
76 if (y > .45 && y < 2.75) {
77 kinds[i] = KIND_ROAD;
78 if (Math.abs(y - BIKE_Y) < .09 && ((x % 2.4) + 2.4) % 2.4 < 1.2) return LANE;
79 return rgb(...ROAD[clamp(Math.floor(noise(x * .7, y * .9) * 3 + (bayerAt(ix, iy) - .5) * .4), 0, 2)]);
80 }
81 if (y > -.35 && y <= .45) {
82 kinds[i] = KIND_ROAD;
83 if (((x % 1.6) + 1.6) % 1.6 < .06) return JOINT;
84 return rgb(...WALK[clamp(Math.floor(noise(x * .6, y * 1.4) * 3 + (bayerAt(ix, iy) - .5) * .4), 0, 2)]);
85 }
86 kinds[i] = KIND_GRASS;
87 const t = noise(x * .9, y * .9) * 1.15 + (fine - .5) * .55 - .08;
88 return rgb(...GRASS[clamp(Math.floor(t * 4.2), 0, 3)]);
89 }
90
91 // flat patch on the wall plane, `lift` in front of it so it wins the depth test against the wall's grain
92 function wallRect(x0, x1, z0, z1, lift, colorAt) {
93 for (let a = x0; a <= x1; a += .05) for (let b = z0; b <= z1; b += .05) {
94 const c = colorAt(a, b);
95 if (c) plot(a, WALL_Y + lift, b, c);
96 }
97 }
98 const LIFT = .14;
99 function houseBox(k) {
100 const sp = ROUTE.spans(k), wall = HOUSE_WALLS[k], roof = HOUSE_ROOFS[k];
101 box(sp.left, BACK_Y, 0, sp.right, WALL_Y, WALL_H, wall, k * 3);
102 box(sp.left - .3, BACK_Y - .2, WALL_H, sp.right + .3, WALL_Y + .35, WALL_H + .4, roof, k * 5 + 1);
103 box(sp.left + .6, BACK_Y + .4, WALL_H + .4, sp.right - .6, WALL_Y - .5, WALL_H + .9, roof, k * 5 + 2);
104 const chimneyX = k % 2 ? sp.left + 1 : sp.right - 1.6;
105 box(chimneyX, BACK_Y + .7, WALL_H + .4, chimneyX + .6, BACK_Y + 1.3, WALL_H + 1.6, [150, 118, 104], k);
106 const [d0, d1] = sp.door, ramp = COLORS(DOORS[k]);
107 box(d0 - .35, WALL_Y, 0, d1 + .35, WALL_Y + 1.35, ROUTE.PORCH_Z, SLAB, k + 20);
108 wallRect(d0 + .2, d1 - .2, ROUTE.PORCH_Z, 2.35, LIFT, (a, b) => {
109 const edge = a < d0 + .3 || a > d1 - .3 || b > 2.25, panel = (a - d0) % .8 < .06 || b > 1.1 && b < 1.15;
110 return ramp[edge || panel ? 1 : 2];
111 });
112 wallRect(d1 - .55, d1 - .45, 1.1, 1.2, LIFT + .02, () => ramp[4]);
113 }
114 function glassAt(sp, a, b) {
115 const [w0, w1] = sp.window, u = (a - w0) / (w1 - w0), v = (b - WINDOW_BOTTOM) / (WINDOW_TOP - WINDOW_BOTTOM);
116 const ramp = COLORS(GLASS), frame = COLORS(WOOD);
117 if (u < .09 || u > .91 || v < .08 || v > .92 || Math.abs(u - .5) < .035 || Math.abs(v - .5) < .045) return frame[3];
118 const glint = u + v > .7 && u + v < .95;
119 return ramp[glint ? 4 : v > .5 ? 3 : 2];
120 }
121 // a shattered pane: dark where glass fell out, pale cracks fanning from the strike
122 function brokenAt(sp, a, b) {
123 const base = glassAt(sp, a, b), [w0, w1] = sp.window;
124 const u = (a - w0) / (w1 - w0), v = (b - WINDOW_BOTTOM) / (WINDOW_TOP - WINDOW_BOTTOM);
125 if (base === COLORS(WOOD)[3]) return base;
126 const dx = u - .55, dy = (v - .5) * .9, ang = Math.atan2(dy, dx), r = Math.hypot(dx, dy);
127 const ray = Math.abs(((ang + Math.PI) / (Math.PI / 3.5)) % 1 - .5) < .04 + .02 * r;
128 if (ray) return rgb(236, 244, 250);
129 return r < .22 || hash(Math.floor(a * 9), Math.floor(b * 9)) < .35 ? rgb(34, 30, 52) : COLORS(GLASS)[1];
130 }
131
132 // a leafy clump of the tree's own leaves: hedges and flowerbeds sway in the same wind, a little less
133 function growBush(x0, x1, y0, y1, z1, count, seed) {
134 for (let n = 0; n < count; n++) {
135 const k = n + seed, x = lerp(x0, x1, hash(k, 3)), y = lerp(y0, y1, hash(k, 4)), z = .12 + hash(k, 5) * (z1 - .12);
136 const bloom = hash(k, 6) < .09;
137 const color = bloom ? BLOOM : BUSH_TONES[Math.min(3, Math.floor(hash(k, 7) * 4 + (z - .3) * .5))];
138 capture = [];
139 sphere(x, y, z, bloom ? .13 : .16 + hash(k, 8) * .12, color, 'rough');
140 leaves.push({ x, y, z, k, r: .3, reach: 1.5, pixels: capture });
141 capture = null;
142 }
143 }
144 function houseShadow(sp) {
145 for (let x = sp.left; x <= sp.right; x += .45) for (let z = 0; z <= WALL_H + .9; z += .6) for (let y = BACK_Y; y <= WALL_Y; y += .6) {
146 castShadow(x, y, z, .5, 1, 0);
147 }
148 }
149
150 function bake() {
151 zb.fill(-1e9);
152 pix.fill(rgb(255, 255, 255));
153 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
154 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy, i);
155 if (!c) continue;
156 pix[i] = c; ground[i] = 1;
157 zb[i] = (g.x + g.y) / R2 * COS;
158 }
159 growGrass();
160 groundZ.set(zb);
161
162 for (let k = 0; k < ROUTE.HOUSES; k++) {
163 houseBox(k);
164 const sp = ROUTE.spans(k);
165 houseShadow(sp);
166 growBush(sp.window[0] - .1, sp.window[1] + .1, WALL_Y + .1, WALL_Y + .6, .95, 45, k * 211);
167 if (k < ROUTE.HOUSES - 1) growTree(sp.right + (ROUTE.PITCH - ROUTE.WIDTH) / 2, WALL_Y - .5, .55, 140, 40 + k * 97);
168 }
169 growTree(15.2, -4, .7, 170, 5);
170 bakeOcclusion();
171 staticShadow.set(shadowMask);
172 applyShadows(groundZ);
173 bakedPix.set(pix);
174 bakedZ.set(zb);
175 }
176
177 /* ---------- game state ---------- */
178 const nodes = {
179 score: document.getElementById('score'), best: document.getElementById('best'),
180 papers: document.getElementById('papers'), status: document.getElementById('status'),
181 };
182 const G = { time: 0, bikeX: -ROUTE.TRACK, throwT: 9, shards: [], status: '' };
183 let R = ROUTE.newRound(0);
184 function renderHud() {
185 nodes.score.textContent = R.score;
186 nodes.best.textContent = R.best;
187 if (nodes.papers.children.length !== ROUTE.PAPERS) nodes.papers.innerHTML = '<i></i>'.repeat(ROUTE.PAPERS);
188 [...nodes.papers.children].forEach((el, k) => el.classList.toggle('off', k >= R.left));
189 }
190 function setStatus(text) {
191 if (text === G.status) return;
192 G.status = text;
193 nodes.status.textContent = text;
194 }
195 function tap() {
196 const next = ROUTE.again(R);
197 if (next) {
198 R = next; G.shards = [];
199 setStatus('tap or press space to throw');
200 renderHud();
201 return;
202 }
203 if (!ROUTE.throwPaper(R, G.bikeX)) return;
204 G.throwT = 0;
205 sound('whoosh');
206 renderHud();
207 }
208 function shatter(p) {
209 for (let n = 0; n < 18; n++) {
210 G.shards.push({
211 x: p.x, y: WALL_Y + .2, z: p.z, age: 0,
212 vx: (hash(n, G.time * 7) - .5) * 3, vy: 1.5 + hash(n, 5) * 3, vz: (hash(n, 9) - .2) * 3.5,
213 color: n % 3 ? rgb(236, 244, 250) : rgb(150, 200, 222),
214 });
215 }
216 }
217 function settle({ zone, paper: p }) {
218 if (zone === 'window') {
219 shatter(p); sound('crash');
220 setStatus('crash, a window · −2');
221 } else if (zone === 'miss') {
222 setStatus('missed the street · 0');
223 } else {
224 sound(zone === 'porch' ? 'thud' : 'plink');
225 setStatus(zone === 'porch' ? 'on the porch · +3' : 'on the lawn · +1');
226 }
227 }
228 function update(dt) {
229 G.time += dt; G.throwT += dt;
230 G.bikeX += ROUTE.BIKE_SPEED * dt;
231 if (G.bikeX > ROUTE.TRACK) G.bikeX = -ROUTE.TRACK;
232 const was = R.phase, settled = ROUTE.advance(R, dt);
233 settled.forEach(settle);
234 if (settled.length) renderHud();
235 for (const s of G.shards) {
236 s.age += dt; s.vz -= 12 * dt;
237 s.x += s.vx * dt; s.y += s.vy * dt; s.z = Math.max(0, s.z + s.vz * dt);
238 }
239 G.shards = G.shards.filter(s => s.age < .9);
240 if (was === 'play' && R.phase === 'over') setStatus(`${R.score} points · best ${R.best} · tap to play again`);
241 }
242
243 /* ---------- drawing ---------- */
244 function drawWindows() {
245 for (let k = 0; k < ROUTE.HOUSES; k++) {
246 const sp = ROUTE.spans(k), pane = R.broken.includes(k) ? brokenAt : glassAt;
247 wallRect(sp.window[0], sp.window[1], WINDOW_BOTTOM, WINDOW_TOP, LIFT, (a, b) => pane(sp, a, b));
248 }
249 }
250 function tube(a, b, r, color) { dynamicAdd(a, b, r, r, () => color); }
251 function drawBike(x, y) {
252 const rot = x * 1.6, R = .6, wheels = [x - .78, x + .78];
253 for (const cx of wheels) {
254 for (let n = 0; n < 14; n++) {
255 const a0 = n / 14 * Math.PI * 2, a1 = (n + 1) / 14 * Math.PI * 2;
256 tube([cx + Math.cos(a0) * R, y, R + Math.sin(a0) * R], [cx + Math.cos(a1) * R, y, R + Math.sin(a1) * R], .06, TIRE);
257 }
258 for (let s = 0; s < 2; s++) {
259 const a = rot + s * Math.PI / 2;
260 tube([cx - Math.cos(a) * R * .9, y, R - Math.sin(a) * R * .9], [cx + Math.cos(a) * R * .9, y, R + Math.sin(a) * R * .9], .025, METAL);
261 }
262 }
263 const f = FRAME;
264 const rear = [wheels[0], y, R], front = [wheels[1], y, R], bb = [x - .02, y, .5], seat = [x - .4, y, 1.3], head = [x + .52, y, 1.38];
265 tube(rear, bb, .05, f); tube(bb, seat, .05, f); tube(seat, head, .05, f); tube(bb, head, .05, f);
266 tube(seat, rear, .045, f); tube(head, front, .045, METAL);
267 tube([x + .46, y - .32, 1.52], [x + .46, y + .32, 1.52], .045, TIRE);
268 tube([x - .55, y, 1.36], [x - .25, y, 1.36], .07, TIRE);
269 }
270 function poseFor() {
271 const pedal = Math.floor(G.time * 6) % 2, swing = clamp(G.throwT / .3, 0, 1);
272 const armL = swing < 1 ? lerp(-.9, 1.25, ease(swing)) : 1.1;
273 return { z: .3, crouch: .5, lean: .5, stance: pedal ? .32 : .12, armR: 1.1, armL: G.throwT < .3 ? armL : 1.1 };
274 }
275 function drawPaper(p) {
276 sphere(p.x, p.y, p.z, .15, PAPER_C, 'solid');
277 castShadow(p.x, p.y, Math.max(0, p.z - .15), .16, 1, 0);
278 }
279 function drawShards() {
280 for (const s of G.shards) {
281 const q = project(s.x, s.y, s.z), ix = q.sx | 0, iy = q.sy | 0;
282 if (ix < 0 || iy < 0 || ix >= W - 1 || iy >= H || (s.age > .5 && bayerAt(ix, iy) < (s.age - .5) / .4)) continue;
283 pix[iy * W + ix] = s.color;
284 if (s.z > .05) pix[iy * W + ix + 1] = s.color;
285 }
286 }
287 function draw() {
288 pix.set(bakedPix);
289 zb.set(bakedZ);
290 pendingShadows.length = 0;
291 drawWindows();
292 for (const p of R.landed) { sphere(p.x, p.y, p.z, .14, PAPER_C, 'solid'); castShadow(p.x, p.y, 0, .15, 1, 0); }
293 drawBike(G.bikeX, BIKE_Y);
294 figure(G.bikeX - .3, BIKE_Y, 0, poseFor(), RIDER, dynamicAdd);
295 for (const p of R.flying) drawPaper(p);
296 const windT = STILL ? 0 : Math.floor(G.time * WIND_FPS) / WIND_FPS;
297 drawLeaves(windT);
298 drawTufts(windT);
299 flushShadows();
300 applyShadows(bakedZ);
301 shadeEdges();
302 drawShards();
303 ctx.putImageData(image, 0, 0);
304 }
305
306 /* ---------- input ---------- */
307 canvas.addEventListener('pointerdown', () => {
308 ensureAudio();
309 canvas.focus({ preventScroll: true });
310 tap();
311 });
312 canvas.addEventListener('keydown', e => {
313 if (e.key !== ' ' && e.key !== 'Enter') return;
314 e.preventDefault();
315 if (e.repeat) return;
316 ensureAudio();
317 tap();
318 });
319
320 /* ---------- sound ---------- */
321 let audio = null, muted = false;
322 function ensureAudio() {
323 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
324 const AC = window.AudioContext || window.webkitAudioContext;
325 if (AC) audio = new AC();
326 }
327 function sound(kind) {
328 if (!audio || muted) return;
329 const now = audio.currentTime, gain = audio.createGain();
330 if (kind === 'crash') {
331 const length = Math.floor(audio.sampleRate * .3), buffer = audio.createBuffer(1, length, audio.sampleRate), data = buffer.getChannelData(0);
332 for (let n = 0; n < length; n++) data[n] = (hash(n, 1) * 2 - 1) * (1 - n / length);
333 const src = audio.createBufferSource();
334 src.buffer = buffer;
335 gain.gain.setValueAtTime(.12, now);
336 gain.gain.exponentialRampToValueAtTime(.0005, now + .3);
337 src.connect(gain).connect(audio.destination);
338 src.start(now);
339 return;
340 }
341 const osc = audio.createOscillator();
342 const spec = {
343 whoosh: [420, 200, .1, .03, 'triangle'],
344 thud: [170, 80, .09, .2, 'sine'],
345 plink: [520, 380, .07, .1, 'sine'],
346 }[kind];
347 osc.type = spec[4];
348 osc.frequency.setValueAtTime(spec[0], now);
349 osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]);
350 gain.gain.setValueAtTime(spec[3], now);
351 gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]);
352 osc.connect(gain).connect(audio.destination);
353 osc.start(now); osc.stop(now + spec[2] + .01);
354 }
355 const muteButton = document.getElementById('mute');
356 muteButton.addEventListener('click', () => {
357 muted = !muted;
358 muteButton.textContent = muted ? 'sound off' : 'sound on';
359 muteButton.setAttribute('aria-pressed', String(muted));
360 });
361
362 /* ---------- fit and boot ---------- */
363 addEventListener('resize', fit);
364 fit();
365 bake();
366 setStatus('tap or press space to throw');
367 renderHud();
368 canvas.focus({ preventScroll: true });
369 let last = performance.now();
370 function frame(now) {
371 update(Math.min(.04, (now - last) / 1000));
372 last = now;
373 draw();
374 requestAnimationFrame(frame);
375 }
376 requestAnimationFrame(frame);
377 </script>
378 </body>
379 </html>
paper-route/route.js added +107
@@ -0,0 +1,107 @@
1 'use strict';
2 // The street and one thrown paper: plain numbers in, plain numbers out, no DOM. The page draws what this decides.
3 (function (root) {
4 const GRAVITY = 14, WALL_Y = -3, ROAD_Y = 1.6, BIKE_SPEED = 4.6, TRACK = 15.8;
5 const HOUSES = 4, PITCH = 7.5, WIDTH = 5.6, FIRST_X = -14.05; // house k spans FIRST_X + k * PITCH, WIDTH wide
6 const WINDOW = [.5, 1.8], DOOR = [2.8, 4.6]; // along the facade, from its left edge (mirrored on odd houses)
7 const PORCH_Z = .22, WINDOW_Z = [1.4, 2.6], HIT_Z = 2; // the arc reaches the wall at HIT_Z, inside the window's height
8 const THROW_VY = -8.5, HAND = [.2, -.45, 1.6]; // paper leaves the hand at bike x + .2, 1.6 high, towards the houses
9 const POINTS = { porch: 3, lawn: 1, window: -2, miss: 0 };
10 const PAPERS = 10, RESTART_AFTER = .6, SUBSTEPS = 4;
11
12 const finite = v => (Number.isFinite(v) ? v : 0);
13 // where along the street a paper that reaches the wall at x ends up: { zone, house, mirror }
14 function zoneAt(x) {
15 x = finite(x);
16 if (x < FIRST_X || x > FIRST_X + (HOUSES - 1) * PITCH + WIDTH) return { zone: 'miss', house: -1 }; // no ground out there
17 for (let k = 0; k < HOUSES; k++) {
18 const left = FIRST_X + k * PITCH, local = x - left;
19 if (local < 0 || local > WIDTH) continue;
20 const rel = k % 2 ? WIDTH - local : local;
21 const zone = rel >= WINDOW[0] && rel <= WINDOW[1] ? 'window' : rel >= DOOR[0] && rel <= DOOR[1] ? 'porch' : 'lawn';
22 return { zone, house: k };
23 }
24 return { zone: 'lawn', house: -1 }; // between houses the paper drops into a tree or the grass
25 }
26 // x extents of a house's window and porch, honouring the mirroring
27 function spans(k) {
28 const left = FIRST_X + k * PITCH, flip = k % 2;
29 const at = ([a, b]) => flip ? [left + WIDTH - b, left + WIDTH - a] : [left + a, left + b];
30 return { left, right: left + WIDTH, window: at(WINDOW), door: at(DOOR) };
31 }
32 // a paper leaves the bike at bikeX and carries its speed along the street
33 function launch(bikeX) {
34 const y = ROAD_Y + HAND[1], x = finite(bikeX) + HAND[0], z = HAND[2];
35 const t = (y - WALL_Y) / -THROW_VY;
36 return { x, y, z, vx: BIKE_SPEED, vy: THROW_VY, vz: (HIT_Z - z + .5 * GRAVITY * t * t) / t, state: 'air', outcome: null };
37 }
38 // advance by dt seconds; returns 'window', 'porch' or 'lawn' on the step the paper settles, otherwise ''.
39 // It flies to the wall, then drops from where it struck, onto the porch or the lawn at the foot of the wall.
40 function step(p, dt) {
41 if (p.state === 'done' || p.state === 'broke') return '';
42 p.vz -= GRAVITY * dt;
43 p.z += p.vz * dt;
44 if (p.state === 'air') {
45 p.x += p.vx * dt; p.y += p.vy * dt;
46 if (p.y > WALL_Y) return '';
47 const hit = zoneAt(p.x);
48 p.y = WALL_Y; p.outcome = hit;
49 if (hit.zone === 'window') { p.state = 'broke'; return 'window'; }
50 p.state = 'drop'; p.vx = 0; p.vy = 0; p.vz = Math.min(p.vz, 0);
51 p.y = WALL_Y + .3;
52 return '';
53 }
54 const floor = p.outcome.zone === 'porch' ? PORCH_Z : 0;
55 if (p.z > floor + .08) return '';
56 p.z = floor + .08; p.state = 'done';
57 return p.outcome.zone;
58 }
59 // fly one paper from a bike at bikeX to where it settles
60 function simulate(bikeX) {
61 const p = launch(bikeX);
62 for (let t = 0; t < 10 && p.state !== 'done' && p.state !== 'broke'; t += 1 / 240) {
63 const e = step(p, 1 / 240);
64 if (e) return { zone: e, house: p.outcome.house, x: p.x, points: POINTS[e] };
65 }
66 return null;
67 }
68 // ---- the round: ten papers, thrown one at a time, scored as each lands ----
69 function newRound(best = 0) {
70 return { phase: 'play', left: PAPERS, score: 0, best: finite(best), record: false, timer: 0, flying: [], landed: [], broken: [] };
71 }
72 // throw one paper from a bike at bikeX; null when the round is over or the bag is empty
73 function throwPaper(s, bikeX) {
74 if (s.phase !== 'play' || s.left <= 0) return null;
75 s.left--;
76 const p = launch(bikeX);
77 s.flying.push(p);
78 return p;
79 }
80 // advance every paper by dt seconds; returns what settled: [{ zone, house, points, paper }]
81 function advance(s, dt) {
82 const settled = [];
83 for (const p of s.flying) {
84 for (let k = 0; k < SUBSTEPS; k++) {
85 const zone = step(p, dt / SUBSTEPS);
86 if (!zone) continue;
87 const points = POINTS[zone];
88 s.score += points;
89 if (s.score > s.best) { s.best = s.score; s.record = true; }
90 if (zone === 'window') s.broken.push(p.outcome.house);
91 else if (zone !== 'miss') s.landed.push({ x: p.x, y: p.y, z: p.z });
92 settled.push({ zone, house: p.outcome.house, points, paper: p });
93 break;
94 }
95 }
96 s.flying = s.flying.filter(p => p.state === 'air' || p.state === 'drop');
97 if (s.phase === 'play' && s.left === 0 && !s.flying.length) { s.phase = 'over'; s.timer = 0; }
98 else if (s.phase === 'over') s.timer += dt;
99 return settled;
100 }
101 // a tap after the round has been over for a moment starts the next one; otherwise null
102 function again(s) {
103 return s.phase === 'over' && s.timer > RESTART_AFTER ? newRound(s.best) : null;
104 }
105 const api = { RESTART_AFTER, newRound, throwPaper, advance, again, GRAVITY, WALL_Y, ROAD_Y, BIKE_SPEED, TRACK, HOUSES, PITCH, WIDTH, FIRST_X, WINDOW_Z, PORCH_Z, POINTS, PAPERS, zoneAt, spans, launch, step, simulate };
106 if (typeof module !== 'undefined') module.exports = api; else root.PaperRoute = api;
107 })(typeof window !== 'undefined' ? window : globalThis);
paper-route/route.test.mjs added +147
@@ -0,0 +1,147 @@
1 import { test, expect } from 'bun:test';
2 import { zoneAt, spans, launch, step, simulate, newRound, throwPaper, advance, again, PAPERS, RESTART_AFTER, POINTS, WINDOW_Z, BIKE_SPEED, FIRST_X, WIDTH } from './route.js';
3
4 const mid = ([a, b]) => (a + b) / 2;
5
6 test('a paper aimed at a window, a door and a patch of lawn scores minus 2, 3 and 1', () => {
7 const s = spans(0);
8 expect(zoneAt(mid(s.window)).zone).toBe('window');
9 expect(zoneAt(mid(s.door)).zone).toBe('porch');
10 expect(zoneAt(s.left + .1).zone).toBe('lawn');
11 expect(POINTS).toEqual({ porch: 3, lawn: 1, window: -2, miss: 0 });
12 });
13
14 test('odd houses are mirrored, so the window and the door swap sides', () => {
15 const a = spans(0), b = spans(1);
16 expect(mid(a.window)).toBeLessThan(mid(a.door));
17 expect(mid(b.window)).toBeGreaterThan(mid(b.door));
18 expect(zoneAt(mid(b.window)).zone).toBe('window');
19 expect(zoneAt(mid(b.door)).zone).toBe('porch');
20 });
21
22 test('between houses is lawn, beyond the ends of the street is a miss worth nothing', () => {
23 expect(zoneAt(FIRST_X + WIDTH + .9)).toEqual({ zone: 'lawn', house: -1 });
24 expect(zoneAt(-40)).toEqual({ zone: 'miss', house: -1 });
25 expect(zoneAt(40).zone).toBe('miss');
26 expect(zoneAt(NaN).zone).toBe('lawn');
27 expect(POINTS.miss).toBe(0);
28 expect(simulate(15.5).zone).toBe('miss');
29 });
30
31 test('the moment of the throw decides: sweeping the bike along the street finds every outcome', () => {
32 const seen = new Set();
33 for (let x = -16; x < 16; x += .05) seen.add(simulate(x).zone);
34 expect([...seen].sort()).toEqual(['lawn', 'miss', 'porch', 'window']);
35 });
36
37 test('the paper carries the bike speed, so it lands ahead of where it was thrown', () => {
38 const p = launch(0);
39 expect(p.vx).toBe(BIKE_SPEED);
40 const r = simulate(-10);
41 expect(r.x).toBeGreaterThan(-10 + .2 + 1);
42 });
43
44 test('the same moment always lands the same way', () => {
45 expect(simulate(-3.3)).toEqual(simulate(-3.3));
46 });
47
48 test('the arc meets the wall at window height, a window stops the paper there', () => {
49 const s = spans(2), p = launch(mid(s.window) - 2.5);
50 let event = '';
51 while (!event && p.state === 'air') event = step(p, 1 / 240);
52 expect(event).toBe('window');
53 expect(p.z).toBeGreaterThan(WINDOW_Z[0]);
54 expect(p.z).toBeLessThan(WINDOW_Z[1]);
55 expect(step(p, 1 / 240)).toBe('');
56 });
57
58 test('a porch paper comes to rest on the slab, a lawn paper on the grass', () => {
59 const porch = launch(mid(spans(3).door) - 2.5), lawn = launch(spans(3).left - 2.5 + .1);
60 for (const p of [porch, lawn]) for (let k = 0; k < 2400 && p.state !== 'done'; k++) step(p, 1 / 240);
61 expect(porch.outcome.zone).toBe('porch');
62 expect(porch.z).toBeGreaterThan(lawn.z);
63 expect(lawn.outcome.zone).toBe('lawn');
64 });
65
66 test('hostile input stays finite', () => {
67 for (const x of [NaN, Infinity, -Infinity, undefined]) expect(Number.isFinite(launch(x).x)).toBe(true);
68 });
69
70 // ---- the round ----
71 const aimed = k => mid(spans(k).door) - 2.5; // bike x that lands a paper on house k's porch
72 const windowAt = k => mid(spans(k).window) - 2.5;
73 const lawnAt = k => spans(k).left - 2.5 + .1;
74 const run = (s, secs = 6) => { const out = []; for (let t = 0; t < secs; t += 1 / 60) out.push(...advance(s, 1 / 60)); return out; };
75
76 test('a round holds ten papers and refuses an eleventh throw', () => {
77 const s = newRound(0);
78 for (let n = 0; n < PAPERS; n++) expect(throwPaper(s, 0)).not.toBeNull();
79 expect(s.left).toBe(0);
80 expect(throwPaper(s, 0)).toBeNull();
81 expect(s.flying.length).toBe(PAPERS);
82 });
83
84 test('three porches and a window score 7', () => {
85 const s = newRound(0);
86 for (const x of [aimed(0), aimed(1), aimed(2), windowAt(3)]) { throwPaper(s, x); run(s, 3); }
87 expect(s.score).toBe(7);
88 expect(s.broken).toEqual([3]);
89 expect(s.landed.length).toBe(3);
90 });
91
92 test('a miss scores nothing and leaves no paper on the ground', () => {
93 const s = newRound(0);
94 throwPaper(s, 15.5);
95 const settled = run(s, 3);
96 expect(settled.map(e => e.zone)).toEqual(['miss']);
97 expect(s.score).toBe(0);
98 expect(s.landed).toEqual([]);
99 });
100
101 test('the round is not over while a paper is still in the air', () => {
102 const s = newRound(0);
103 for (let n = 0; n < PAPERS; n++) throwPaper(s, aimed(0));
104 advance(s, 1 / 60);
105 expect(s.left).toBe(0);
106 expect(s.phase).toBe('play');
107 run(s, 4);
108 expect(s.phase).toBe('over');
109 expect(s.flying.length).toBe(0);
110 expect(throwPaper(s, 0)).toBeNull();
111 });
112
113 test('best only rises, and record says so', () => {
114 const s = newRound(10);
115 throwPaper(s, aimed(0)); run(s, 3);
116 expect(s.score).toBe(3);
117 expect(s.best).toBe(10);
118 expect(s.record).toBe(false);
119 for (let n = 0; n < 3; n++) { throwPaper(s, aimed(0)); run(s, 3); }
120 expect(s.best).toBe(12);
121 expect(s.record).toBe(true);
122 throwPaper(s, windowAt(1)); run(s, 3);
123 expect(s.score).toBe(10);
124 expect(s.best).toBe(12);
125 });
126
127 test('a tap within 0.6 s of the end does not restart; after it, a new round keeps best', () => {
128 const s = newRound(0);
129 for (let n = 0; n < PAPERS; n++) { throwPaper(s, aimed(0)); run(s, 3); }
130 s.timer = 0; // the round ended just now
131 expect(s.phase).toBe('over');
132 expect(again(s)).toBeNull();
133 advance(s, RESTART_AFTER - .1);
134 expect(again(s)).toBeNull();
135 advance(s, .2);
136 const next = again(s);
137 expect(next.phase).toBe('play');
138 expect(next.left).toBe(PAPERS);
139 expect(next.score).toBe(0);
140 expect(next.best).toBe(30);
141 expect(again(newRound(0))).toBeNull();
142 });
143
144 test('the street has four houses', () => {
145 expect(spans(3).right).toBeGreaterThan(spans(3).left);
146 expect(zoneAt(spans(4).left + .1).zone).toBe('miss');
147 });
serve.test.mjs +7
@@ -36,6 +36,13 @@ test('stone skip is served without a track', async () => {
3636 expect((await fetch(base + '/stone-skip/skip.js')).status).toBe(200);
3737 });
3838
39 test('paper route is served without a track', async () => {
40 const page = await fetch(base + '/paper-route/');
41 expect(page.status).toBe(200);
42 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
43 expect((await fetch(base + '/paper-route/route.js')).status).toBe(200);
44 });
45
3946 test('a game folder without its slash redirects to it', async () => {
4047 const res = await fetch(base + '/balote', { redirect: 'manual' });
4148 expect(res.status).toBe(308);
shell.js +1
@@ -10,6 +10,7 @@ window.PixelPlays = (() => {
1010 { id: 'mini-ramp', title: 'Mini Ramp' },
1111 { id: 'kite-hill', title: 'Kite Hill', music: false, forged: true },
1212 { id: 'stone-skip', title: 'Stone Skip', music: false, forged: true },
13 { id: 'paper-route', title: 'Paper Route', music: false, forged: true },
1314 ];
1415 const MUSIC_VOLUME = .4;
1516 const CREDITS = [

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs