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

Migrated from github.com/amirmushichge/pixel-plays

Add Row Home: race a rowing boat across the river by stroking in rhythm #25

Merged opened this

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

Merged

quill/pixel-plays:quill/13-add-row-home-race-a-rowing-boat-across-t → main 1 commit fork

  • Merged. quill/13-add-row-home-race-a-rowing-boat-across-t was merged into main as d4383a2.

Review

Sign in to review this change.
7 files changed +556 −1
README.md +2 −1
@@ -20,6 +20,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
2020 | [Pizza Toss](pizza-toss/) | Five tosses of pizza dough: hold to spin, catch it before it drops, too much spin tears it (forged by the crew on the engine and shell above, not by the original creators) | Hold and release, tap to catch; space |
2121 | [Harbour Crane](harbour-crane/) | Stack ten crates onto a bobbing fishing boat from a swinging crane hook; one hanging more than half off tips into the water (forged by the crew on the engine and shell above, not by the original creators) | Tap; space |
2222 | [Sled Run](sled-run/) | Ride a sledge down a snowy hill for 40 seconds: tuck for speed, release on a kicker to jump, land flat for points and nose-down to tumble (forged by the crew on the engine and shell above, not by the original creators) | Hold and release; space |
23 | [Row Home](row-home/) | Race a rowing boat across the river against a bot: stroke in rhythm with the glide, too early catches a crab, hold left or right to steer against the current (forged by the crew on the engine and shell above, not by the original creators) | Tap or space to stroke; hold left/right |
2324
2425 ## Run
2526 Requires [Node.js](https://nodejs.org/); nothing to install.
@@ -33,7 +34,7 @@ Then open http://127.0.0.1:5300/. `PORT` and `HOST` override the port and addres
3334 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.
3435
3536 ## Add a game
36 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 (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too). 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 and Sled Run 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`.
37 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 (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too). 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 and Row Home 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`.
3738
3839 - `shell.js` provides the game menu, the Rules popup, the credits and the background music.
3940 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
index.html +1
@@ -35,6 +35,7 @@ footer a { display: inline; padding: 0; font-weight: inherit; text-decoration: u
3535 <li><a href="pizza-toss/">Pizza Toss</a><span>Five tosses of pizza dough: hold to spin, catch it before it drops, too much spin tears it</span><span>Game forged by the crew</span></li>
3636 <li><a href="harbour-crane/">Harbour Crane</a><span>Stack ten crates onto a bobbing fishing boat from a swinging crane hook</span><span>Game forged by the crew</span></li>
3737 <li><a href="sled-run/">Sled Run</a><span>Ride a sledge down a snowy hill: tuck for speed, release on a kicker to jump, land flat</span><span>Game forged by the crew</span></li>
38 <li><a href="row-home/">Row Home</a><span>Race a rowing boat across the river against a bot: stroke in rhythm with the glide, too early catches a crab</span><span>Game forged by the crew</span></li>
3839 </ul>
3940 <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.</footer>
4041 </main>
row-home/index.html added +341
@@ -0,0 +1,341 @@
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>Row Home</title>
7 <style>
8 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; }
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 #scores b { font-size: 16px; font-weight: 600; font-variant-numeric: tabular-nums; min-width: 5ch; }
17 #scores span { color: var(--muted); font-variant-numeric: tabular-nums; min-height: 1.35em; }
18 #bottom { bottom: max(14px, env(safe-area-inset-bottom)); align-items: flex-end; }
19 #status { color: var(--muted); min-height: 1.35em; }
20 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
21 button:hover, button:focus-visible { color: var(--ink); }
22 </style>
23 </head>
24 <body>
25 <div id="stage"><canvas id="c" tabindex="0" aria-label="Row Home. Tap or press space for each stroke: stroke again as the boat starts to slow, too early catches a crab. Hold left or right, or press the left or right half of the picture, to steer against the current. Reach the far jetty before the bot."></canvas></div>
26 <div id="scores"><b id="score">0.0s</b><span id="meta"></span></div>
27 <div class="hud" id="bottom">
28 <div id="status" role="status" aria-live="polite"></div>
29 <button id="mute" type="button" aria-pressed="false">sound on</button>
30 </div>
31 <script src="../shell.js"></script>
32 <script>
33 PixelPlays.mount({
34 id: 'row-home',
35 rules: [
36 'Tap or press space for each stroke: the boat surges, then glides and slows.',
37 'Stroke again as it slows. Too early catches a crab and stalls you.',
38 'Hold left or right, or press that half of the picture, to steer against the current.',
39 'Reach the far jetty before the bot boat.',
40 ],
41 });
42 </script>
43 <script>window.PP_SCENE = { originY: 0, shadowX: 1.1, shadowY: -.3 };</script>
44 <script src="../engine.js"></script>
45 <script src="model.js"></script>
46 <script>
47 'use strict';
48
49 const BEST_KEY = 'pixel-plays-row-home-best';
50 const HALF_LENGTH = 17, HALF_WIDTH = 7, RIVER = 3.7, ROPE = -1.5, BOT_LANE = -2.6, END = RowModel.START + RowModel.LENGTH;
51 const HULL = [214, 72, 52], HULL_BOT = [248, 200, 60], INSIDE = [236, 214, 176], OAR = [190, 150, 98];
52 const DECK = [150, 112, 78], POST = [96, 72, 56], BUOY = [240, 236, 226], BUOY_RED = [214, 72, 52];
53 const ROWER = { shirt: [226, 96, 56], stripe: [240, 230, 210], legs: [52, 66, 96], hair: [58, 38, 30], skin: [222, 170, 132] };
54 const ROWER_BOT = { shirt: [60, 96, 150], stripe: [240, 230, 210], legs: [64, 60, 74], hair: [120, 80, 40], skin: [214, 160, 124] };
55 const WATER = [[48, 100, 150], [62, 124, 170], [84, 150, 188], [118, 176, 204]];
56 const WAKE = [rgb(236, 246, 250), rgb(190, 220, 232)];
57 const wet = new Uint8Array(W * H);
58
59 /* ---------- ground ---------- */
60 function groundColor(x, y, ix, iy, i) {
61 const edge = Math.pow(Math.pow(Math.abs(x) / HALF_LENGTH, 4) + Math.pow(Math.abs(y) / HALF_WIDTH, 4), .25);
62 const rough = edge + (noise(x * 1.3, y * 1.3) - .5) * .1;
63 if (rough > 1.04) return 0;
64 if (rough > .94 && hash(ix, iy) < (rough - .94) / .1) return 0;
65 const shore = RIVER + (noise(x * .6, 3) - .5) * .7;
66 if (Math.abs(y) < shore) {
67 wet[i] = 1;
68 const t = noise(x * .45, y * 2.4) * 1.1 + (hash(ix, iy) - .5) * .4 + (1 - Math.abs(y) / shore) * .25 - .12;
69 return rgb(...WATER[clamp(Math.floor(t * 3.6), 0, 3)]);
70 }
71 kinds[i] = KIND_GRASS;
72 const t = noise(x * .9, y * .9) * 1.15 + (hash(ix, iy) - .5) * .55 - .08 + (1 - edge) * .14;
73 return rgb(...GRASS[clamp(Math.floor(t * 4.2), 0, 3)]);
74 }
75 // reeds stand taller than grass and crowd the water's edge, so they are the first thing the breeze moves
76 function growReeds() {
77 for (let iy = 3; iy < H - 1; iy++) for (let ix = 1; ix < W - 1; ix++) {
78 const i = iy * W + ix;
79 if (kinds[i] !== KIND_GRASS || hash(ix * 5, iy * 3) > .5) continue;
80 if (!(wet[i - 1] || wet[i + 1] || wet[i - W] || wet[i + W] || wet[i - 2 * W] || wet[i - 2] || wet[i + 2])) continue;
81 tufts.push({ ix, iy, i, height: 4 + (hash(ix, iy * 7) * 4 | 0), base: 1 + (hash(ix * 3, iy) * 2 | 0), phase: ix * .13 + iy * .17 + hash(ix, iy) * .9, bloom: 0 });
82 }
83 }
84 function jetty(x0, x1) {
85 box(x0, -RIVER - .2, 0, x1, RIVER + .2, .45, DECK, x0);
86 for (const px of [x0 + .2, x1 - .2]) for (const py of [-RIVER, RIVER]) {
87 capsule([px, py, .6], [px, py, 1.1], .12, .12, () => POST, 'rough');
88 castShadow(px, py, 1.1, .2);
89 }
90 castShadow((x0 + x1) / 2, 0, .45, 1.5, 1, .2);
91 }
92 function bake() {
93 zb.fill(-1e9);
94 pix.fill(rgb(255, 255, 255));
95 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
96 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy, i);
97 if (!c) continue;
98 pix[i] = c; ground[i] = 1;
99 zb[i] = (g.x + g.y) / R2 * COS;
100 }
101 growGrass();
102 growReeds();
103 groundZ.set(zb);
104 jetty(RowModel.START - 3.2, RowModel.START - .6);
105 jetty(END + .6, END + 3.2);
106 // finish flag on the far jetty
107 capsule([END + 2.6, -RIVER, .45], [END + 2.6, -RIVER, 3.1], .07, .07, () => POST, 'rough');
108 for (let k = 0; k < 6; k++) for (let m = 0; m < 3; m++) {
109 sphere(END + 2.6 + k * .24 + .15, -RIVER, 2.9 - m * .3, .17, (k + m) % 2 ? [250, 246, 226] : BUOY_RED, 'solid');
110 }
111 castShadow(END + 2.6, -RIVER, 3.1, .3);
112 // lane rope: buoys between the two courses
113 for (let x = RowModel.START - .5; x <= END + .6; x += 1.6) {
114 const red = Math.round((x - RowModel.START) / 1.6) % 2;
115 sphere(x, ROPE, .12, .18, red ? BUOY_RED : BUOY, 'solid');
116 castShadow(x, ROPE, .3, .16, 1, 0);
117 }
118 growTree(-12.5, 5.2, .8, 260, 5);
119 castShadow(-12.5, 5.2, 1.2, 1, 1, .4);
120 bakeOcclusion();
121 staticShadow.set(shadowMask);
122 applyShadows(groundZ);
123 bakedPix.set(pix);
124 bakedZ.set(zb);
125 }
126
127 /* ---------- state ---------- */
128 const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })();
129 let R = RowModel.newState(best0), steerKey = 0, steerPointer = 0, time = 0, status = '', wake = [], botWake = [], overT = 0, lastPhase = 'ready', lastKind = '';
130 const nodes = { score: document.getElementById('score'), meta: document.getElementById('meta'), status: document.getElementById('status') };
131 const fmt = t => t.toFixed(1) + 's';
132 let shown = '';
133 function renderHud() {
134 const shownTime = R.phase === 'over' ? R.time : R.t;
135 const text = fmt(shownTime) + '|' + R.best + '|' + Math.round(RowModel.progress(R) * 100) + '|' + R.phase;
136 if (text === shown) return;
137 shown = text;
138 nodes.score.textContent = fmt(shownTime);
139 const lead = Math.round((R.x - R.bot) * 10) / 10;
140 nodes.meta.textContent = (R.best ? 'best ' + fmt(R.best) + ' · ' : '') + (R.phase === 'race' ? (lead >= 0 ? 'ahead ' : 'behind ') + Math.abs(lead).toFixed(1) : R.phase === 'over' ? (R.won ? 'you won' : 'bot won') : 'bot ready');
141 }
142 function setStatus(text) {
143 if (text === status) return;
144 status = text;
145 nodes.status.textContent = text;
146 }
147 function statusFor() {
148 if (R.phase === 'ready') return 'tap or press space to stroke';
149 if (R.phase === 'over') return fmt(R.time) + (R.won ? '' : ' · the bot beat you') + (R.record ? ' · new best' : '') + ' · tap to row again';
150 if (R.crab > 0) return 'caught a crab';
151 if (R.scraping) return 'scraping the rope or bank';
152 if (RowModel.inRhythm(R)) return 'stroke now';
153 return R.since < RowModel.RHYTHM_FROM ? 'glide' : 'late · stroke';
154 }
155 function reset() {
156 R = RowModel.newState(R.best);
157 wake = []; botWake = []; lastKind = '';
158 }
159 function stroke() {
160 ensureAudio();
161 if (R.phase === 'over') { if (overT > .8) reset(); return; }
162 const kind = RowModel.stroke(R);
163 if (kind && kind !== 'stalled') { lastKind = kind; sound(kind); }
164 }
165 const steer = () => steerKey || steerPointer;
166 function update(dt) {
167 time += dt;
168 RowModel.step(R, dt, steer());
169 if (R.phase !== lastPhase) {
170 if (R.phase === 'over') {
171 steerPointer = 0; overT = 0;
172 sound(R.won ? 'win' : 'lose');
173 if (R.record) try { localStorage.setItem(BEST_KEY, String(R.best)); } catch (e) { /* private window: keep it for this visit */ }
174 }
175 lastPhase = R.phase;
176 }
177 if (R.phase === 'over') overT += dt;
178 // the wake: where each boat has been, kept until it has spread out
179 const trail = (list, x, lane, v) => {
180 for (const p of list) p.age += dt;
181 while (list.length && list[0].age > 1.6) list.shift();
182 if (v > .25 && (!list.length || x - list[list.length - 1].x > .3)) list.push({ x, lane, age: 0 });
183 };
184 if (R.phase === 'race') { trail(wake, R.x, R.lane, R.v); trail(botWake, R.bot, BOT_LANE, R.botDone ? 0 : 1); }
185 setStatus(statusFor());
186 renderHud();
187 }
188
189 /* ---------- drawing ---------- */
190 // whole-pixel ripples drift across the water, stepped like the wind
191 function drawRipples(t) {
192 if (STILL) return;
193 const step = Math.floor(t * 3);
194 for (let iy = 0; iy < H; iy += 3) for (let ix = 0; ix < W; ix++) {
195 const i = iy * W + ix;
196 if (!wet[i] || zb[i] !== groundZ[i]) continue;
197 if (hash(((ix >> 3) + step) | 0, iy * 3.1) > .07 || (ix & 7) > 2) continue;
198 tint(i, 1.12, 1.08, 1.04);
199 }
200 }
201 // two arms spread behind each boat; every dot lands on a whole pixel
202 function drawWake(list) {
203 const dots = [];
204 for (const p of list) {
205 const spread = .25 + p.age * .7, fade = p.age / 1.6;
206 for (const side of [-1, 1]) {
207 const a = project(p.x - p.age * .3, p.lane + side * spread, 0);
208 if (hash(p.x * 9, side + p.age * 4) > fade * 1.1) dots.push([Math.round(a.sx), Math.round(a.sy)]);
209 }
210 if (p.age < .5) { const c = project(p.x - .5, p.lane, 0); dots.push([Math.round(c.sx), Math.round(c.sy)]); }
211 }
212 drawDots(dots, WAKE[0]);
213 }
214 function drawBoat(x, lane, hullColor, palette, bob, since, stalled) {
215 const z = .12 + bob;
216 // hull: a pointed lens of spheres stern to bow
217 for (let k = -5; k <= 5; k++) {
218 const u = k / 5, r = .3 * (1 - Math.pow(Math.abs(u), 3)) + .08;
219 capsule([x + u * 1.05, lane, z + .1 + .06 * u * u], [x + u * 1.05 + .2, lane, z + .1 + .06 * u * u], r, r, h => (h > z + .16 ? INSIDE : hullColor), 'solid');
220 }
221 pendingShadows.push([x - .9, lane, z + .15], .25, [x + .9, lane, z + .15], .25);
222 // oars: the stroke sweeps the blades back with the blades in the water, then lifts them forward
223 const dip = clamp(since / .35, 0, 1), inWater = since < .35 && !stalled;
224 const sweep = stalled ? .9 : inWater ? lerp(.7, -.7, dip) : lerp(-.7, .7, clamp((since - .35) / .45, 0, 1));
225 for (const side of [-1, 1]) {
226 const lock = [x, lane + side * .36, z + .42];
227 const tip = [x + sweep * .9, lane + side * 2.2, inWater ? .08 : stalled ? .1 : z + .75];
228 capsule(lock, tip, .05, .06, () => OAR, 'rough');
229 pendingShadows.push(lock, .05, tip, .06);
230 if (inWater) {
231 sphere(tip[0], tip[1], tip[2], .13, OAR, 'solid');
232 }
233 }
234 const crouch = inWater ? .5 : stalled ? .8 : .1;
235 figure(x - .15, lane, Math.PI, { stance: .02, crouch: .55 + crouch * .2, lean: inWater ? -.5 : .25, armR: 1.8, armL: 1.8, scale: .85, z: z + .02 }, palette, dynamicAdd);
236 }
237 function draw() {
238 pix.set(bakedPix);
239 zb.set(bakedZ);
240 pendingShadows.length = 0;
241 const windT = STILL ? 0 : Math.floor(time * WIND_FPS) / WIND_FPS;
242 drawRipples(time);
243 drawWake(botWake);
244 drawWake(wake);
245 const bob = ph => STILL ? 0 : Math.sin(Math.floor(time * WIND_FPS) / WIND_FPS * 2.2 + ph) * .03;
246 const botSince = R.phase === 'race' ? R.t % 1.1 : 1;
247 drawBoat(R.bot, BOT_LANE, HULL_BOT, ROWER_BOT, bob(1.3), botSince, false);
248 drawBoat(R.x, R.lane, HULL, ROWER, bob(0), R.since, R.crab > 0);
249 drawTufts(windT);
250 drawLeaves(windT);
251 flushShadows();
252 applyShadows(bakedZ);
253 shadeEdges();
254 if (R.phase === 'ready') {
255 const head = project(R.x, R.lane, 2.4);
256 drawArrow(head.sx, head.sy, time);
257 }
258 ctx.putImageData(image, 0, 0);
259 }
260
261 /* ---------- input ---------- */
262 canvas.addEventListener('pointerdown', e => {
263 canvas.focus({ preventScroll: true });
264 canvas.setPointerCapture(e.pointerId);
265 const box = canvas.getBoundingClientRect();
266 steerPointer = e.clientX < box.left + box.width / 2 ? 1 : -1;
267 stroke();
268 });
269 const letGo = () => { steerPointer = 0; };
270 canvas.addEventListener('pointerup', letGo);
271 canvas.addEventListener('pointercancel', letGo);
272 addEventListener('blur', () => { steerPointer = 0; steerKey = 0; });
273 const KEYS = { ArrowLeft: 1, a: 1, A: 1, ArrowRight: -1, d: -1, D: -1 };
274 canvas.addEventListener('keydown', e => {
275 if (e.key in KEYS) { e.preventDefault(); steerKey = KEYS[e.key]; return; }
276 if (e.key !== ' ' && e.key !== 'Enter') return;
277 e.preventDefault();
278 if (!e.repeat) stroke();
279 });
280 canvas.addEventListener('keyup', e => {
281 if (e.key in KEYS && steerKey === KEYS[e.key]) steerKey = 0;
282 });
283
284 /* ---------- sound ---------- */
285 let audio = null, muted = false, noise1 = null;
286 function ensureAudio() {
287 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
288 const AC = window.AudioContext || window.webkitAudioContext;
289 if (!AC) return;
290 audio = new AC();
291 noise1 = audio.createBuffer(1, audio.sampleRate >> 2, audio.sampleRate);
292 const data = noise1.getChannelData(0);
293 for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
294 }
295 function splash(freq, len, vol) {
296 const now = audio.currentTime, src = audio.createBufferSource(), filter = audio.createBiquadFilter(), gain = audio.createGain();
297 src.buffer = noise1; filter.type = 'bandpass'; filter.frequency.value = freq; filter.Q.value = .8;
298 gain.gain.setValueAtTime(vol, now);
299 gain.gain.exponentialRampToValueAtTime(.0005, now + len);
300 src.connect(filter).connect(gain).connect(audio.destination);
301 src.start(now); src.stop(now + len + .01);
302 }
303 function sound(kind) {
304 if (!audio || muted) return;
305 if (kind === 'good' || kind === 'first') return splash(900, .22, .3);
306 if (kind === 'late') return splash(600, .2, .18);
307 if (kind === 'crab') return splash(240, .35, .5);
308 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
309 const spec = kind === 'win' ? [520, 880, .3] : [300, 160, .35];
310 osc.type = 'triangle';
311 osc.frequency.setValueAtTime(spec[0], now);
312 osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]);
313 gain.gain.setValueAtTime(.14, now);
314 gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]);
315 osc.connect(gain).connect(audio.destination);
316 osc.start(now); osc.stop(now + spec[2] + .01);
317 }
318 const muteButton = document.getElementById('mute');
319 muteButton.addEventListener('click', () => {
320 muted = !muted;
321 muteButton.textContent = muted ? 'sound off' : 'sound on';
322 muteButton.setAttribute('aria-pressed', String(muted));
323 });
324
325 /* ---------- boot ---------- */
326 addEventListener('resize', fit);
327 fit();
328 bake();
329 setStatus(statusFor());
330 renderHud();
331 let last = performance.now();
332 function frame(now) {
333 update(Math.min(.04, (now - last) / 1000));
334 last = now;
335 draw();
336 requestAnimationFrame(frame);
337 }
338 requestAnimationFrame(frame);
339 </script>
340 </body>
341 </html>
row-home/model.js added +82
@@ -0,0 +1,82 @@
1 'use strict';
2 // Row Home rules as plain data in, plain data out: stroke timing, the crab, the current and the finish.
3 // The page draws from this state and the tests drive it, so both read the same numbers.
4 (function (root) {
5 const LENGTH = 24, START = -12, LANE_MIN = -1.1, LANE_MAX = 3.1, LANE_START = 1.2;
6 const DRAG = .9, STEER = 1.4, CURRENT = .55, SCRAPE = 2.5;
7 const RHYTHM_FROM = .8, RHYTHM_TO = 1.5; // seconds since the last stroke in which the oars bite cleanly
8 const IMPULSE = { late: .8, good: 1.1 }, STREAK_BONUS = .1, STREAK_MAX = 4, FIRST = .9;
9 const CRAB_TIME = 1, CRAB_DRAG = 3.2, CRAB_KICK = .15;
10 const BOT_PACE = 1.18, BOT_SURGE = .3, BOT_BEAT = 1.1;
11 const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
12
13 // the slow cross-current: pushes toward +lane, then back, over about 18 seconds
14 const current = t => CURRENT * Math.sin(t * .35);
15 // the bot rows in a steady beat; its speed rises and falls once a stroke
16 const botSpeed = (t, pace) => pace * (1 + BOT_SURGE * Math.sin(t * 2 * Math.PI / BOT_BEAT));
17
18 function newState(best = 0, botPace = BOT_PACE) {
19 return {
20 phase: 'ready', t: 0, x: START, lane: LANE_START, v: 0, since: 9, streak: 0, crab: 0, last: '',
21 bot: START, botPace, botDone: 0, time: 0, won: false, best, record: false, scraping: false,
22 };
23 }
24 const progress = s => clamp((s.x - START) / LENGTH, 0, 1);
25 // is the next stroke in rhythm with the glide?
26 const inRhythm = s => s.since >= RHYTHM_FROM && s.since <= RHYTHM_TO;
27
28 // one stroke: in rhythm it surges, late it is a plain pull, early it catches a crab
29 function stroke(s) {
30 if (s.phase === 'over') return '';
31 if (s.crab > 0) return 'stalled';
32 if (s.phase === 'ready') { s.phase = 'race'; s.since = 0; s.v += FIRST; s.last = 'first'; return 'first'; }
33 let kind;
34 if (s.since < RHYTHM_FROM) {
35 kind = 'crab';
36 s.crab = CRAB_TIME; s.streak = 0; s.v = Math.min(s.v, CRAB_KICK);
37 } else if (s.since <= RHYTHM_TO) {
38 kind = 'good';
39 s.v += IMPULSE.good + Math.min(s.streak, STREAK_MAX) * STREAK_BONUS;
40 s.streak++;
41 } else {
42 kind = 'late';
43 s.v += IMPULSE.late; s.streak = 0;
44 }
45 s.since = 0; s.last = kind;
46 return kind;
47 }
48
49 // 'ready' and 'over' wait for the player; steer is -1 (right), 0 or 1 (left)
50 function step(s, dt, steer = 0) {
51 if (s.phase !== 'race') return s;
52 s.t += dt;
53 s.since += dt;
54 if (s.crab > 0) s.crab = Math.max(0, s.crab - dt);
55 s.v = Math.max(0, s.v - s.v * (s.crab > 0 ? CRAB_DRAG : DRAG) * dt);
56 s.lane += (clamp(steer, -1, 1) * STEER + current(s.t)) * dt;
57 s.scraping = s.lane < LANE_MIN || s.lane > LANE_MAX;
58 if (s.scraping) {
59 s.lane = clamp(s.lane, LANE_MIN, LANE_MAX);
60 s.v = Math.max(0, s.v - s.v * SCRAPE * dt);
61 }
62 s.x += s.v * dt;
63 if (!s.botDone) {
64 s.bot += botSpeed(s.t, s.botPace) * dt;
65 if (s.bot >= START + LENGTH) { s.bot = START + LENGTH; s.botDone = s.t; }
66 }
67 if (s.x >= START + LENGTH) {
68 s.x = START + LENGTH;
69 s.phase = 'over'; s.time = s.t; s.v = 0;
70 s.won = !s.botDone;
71 s.record = !s.best || s.time < s.best;
72 if (s.record) s.best = s.time;
73 }
74 return s;
75 }
76 const api = {
77 LENGTH, START, LANE_MIN, LANE_MAX, RHYTHM_FROM, RHYTHM_TO, CRAB_TIME,
78 current, botSpeed, newState, progress, inRhythm, stroke, step,
79 };
80 if (typeof module !== 'undefined' && module.exports) module.exports = api;
81 else root.RowModel = api;
82 })(typeof window !== 'undefined' ? window : globalThis);
row-home/model.test.mjs added +122
@@ -0,0 +1,122 @@
1 import { test, expect } from 'bun:test';
2 import { createRequire } from 'node:module';
3
4 const M = createRequire(import.meta.url)('./model.js');
5 const run = (s, seconds, steer = 0) => { for (let i = 0; i < Math.round(seconds * 60); i++) M.step(s, 1 / 60, steer); return s; };
6 const started = () => { const s = M.newState(); M.stroke(s); return s; };
7 // strokes every `gap` seconds until the race ends (or `limit` seconds pass)
8 function row(s, gap, limit = 90) {
9 while (s.phase !== 'over' && s.t < limit) { run(s, gap); M.stroke(s); }
10 return s;
11 }
12
13 test('ready waits for the first stroke, which starts the race', () => {
14 const s = M.newState();
15 run(s, 2);
16 expect(s.t).toBe(0);
17 expect(M.stroke(s)).toBe('first');
18 expect(s.phase).toBe('race');
19 expect(s.v).toBeGreaterThan(0);
20 });
21
22 test('a stroke surges the boat, then it glides and slows', () => {
23 const s = started();
24 const v0 = s.v;
25 run(s, .5);
26 const mid = s.v;
27 run(s, .5);
28 expect(mid).toBeLessThan(v0);
29 expect(s.v).toBeLessThan(mid);
30 expect(s.x).toBeGreaterThan(M.START);
31 });
32
33 test('an in-rhythm stroke beats a stroke made early', () => {
34 const early = started(); run(early, .3);
35 const rhythm = started(); run(rhythm, 1);
36 const e = early.v, r = rhythm.v;
37 expect(M.inRhythm(rhythm)).toBe(true);
38 expect(M.inRhythm(early)).toBe(false);
39 expect(M.stroke(early)).toBe('crab');
40 expect(M.stroke(rhythm)).toBe('good');
41 expect(rhythm.v - r).toBeGreaterThan(early.v - e);
42 });
43
44 test('a crab stalls the boat for a moment, then rowing resumes', () => {
45 const s = started(); run(s, .3);
46 M.stroke(s);
47 expect(s.crab).toBe(M.CRAB_TIME);
48 const v = s.v;
49 expect(M.stroke(s)).toBe('stalled');
50 expect(s.v).toBe(v);
51 run(s, M.CRAB_TIME + .05);
52 expect(s.crab).toBe(0);
53 expect(M.stroke(s)).not.toBe('stalled');
54 });
55
56 test('strokes in a row keep a streak that adds speed; a late one drops it', () => {
57 const s = started();
58 run(s, 1); M.stroke(s); run(s, 1); M.stroke(s);
59 expect(s.streak).toBe(2);
60 run(s, 1);
61 const before = M.newState(); M.stroke(before); run(before, 1);
62 const gain = v => { const c = { ...v }; const v0 = c.v; M.stroke(c); return c.v - v0; };
63 expect(gain(s)).toBeGreaterThan(gain(before));
64 run(s, 2);
65 M.stroke(s);
66 expect(s.last).toBe('late');
67 expect(s.streak).toBe(0);
68 });
69
70 test('holding left or right steers against a slow current', () => {
71 const drift = started(); run(drift, 2);
72 const left = started(); run(left, 2, 1);
73 const right = started(); run(right, 2, -1);
74 expect(left.lane).toBeGreaterThan(drift.lane);
75 expect(right.lane).toBeLessThan(drift.lane);
76 expect(M.current(0)).toBe(0);
77 expect(M.current(4.5)).toBeGreaterThan(.3);
78 expect(M.current(13.5)).toBeLessThan(-.3);
79 });
80
81 test('the lane ends at the rope and the bank, and scraping slows the boat', () => {
82 const s = started(); run(s, 4, -1);
83 expect(s.lane).toBe(M.LANE_MIN);
84 expect(s.scraping).toBe(true);
85 const clear = started(); run(clear, 4, 0);
86 const scraped = started(); scraped.lane = M.LANE_MIN; scraped.v = clear.v = 2;
87 run(scraped, .5, -1); run(clear, .5, 0);
88 expect(scraped.v).toBeLessThan(clear.v);
89 });
90
91 test('a race has a finish time and a best', () => {
92 const s = M.newState(100);
93 M.stroke(s);
94 row(s, 1);
95 expect(s.phase).toBe('over');
96 expect(s.x).toBe(M.START + M.LENGTH);
97 expect(s.time).toBeGreaterThan(8);
98 expect(s.time).toBeLessThan(40);
99 expect(s.record).toBe(true);
100 expect(s.best).toBe(s.time);
101 const t = s.t; M.step(s, 1, 0);
102 expect(s.t).toBe(t);
103 });
104
105 test('rowing in rhythm beats the bot; stroking too early does not', () => {
106 const good = M.newState(); M.stroke(good); row(good, 1);
107 expect(good.won).toBe(true);
108 expect(good.botDone).toBe(0);
109 const eager = M.newState(); M.stroke(eager); row(eager, .4, 120);
110 expect(eager.phase === 'over' ? eager.time : 120).toBeGreaterThan(good.time + 5);
111 expect(eager.won).toBe(false);
112 });
113
114 test('the bot has its own finish, and a slow best does not replace a faster one', () => {
115 const s = M.newState(5); M.stroke(s); row(s, 1);
116 expect(s.record).toBe(false);
117 expect(s.best).toBe(5);
118 const bot = M.newState(); bot.phase = 'race';
119 run(bot, 40);
120 expect(bot.botDone).toBeGreaterThan(15);
121 expect(bot.botDone).toBeLessThan(25);
122 });
serve.test.mjs +7
@@ -52,6 +52,13 @@ test('Kite Hill and its model script are served', async () => {
5252 expect((await fetch(base + '/kite-hill/model.js')).status).toBe(200);
5353 });
5454
55 test('Row Home and its model script are served without a track', async () => {
56 const page = await fetch(base + '/row-home/');
57 expect(page.status).toBe(200);
58 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
59 expect((await fetch(base + '/row-home/model.js')).status).toBe(200);
60 });
61
5562 test('stone skip is served without a track', async () => {
5663 const page = await fetch(base + '/stone-skip/');
5764 expect(page.status).toBe(200);
shell.js +1
@@ -14,6 +14,7 @@ window.PixelPlays = (() => {
1414 { id: 'pizza-toss', title: 'Pizza Toss', blurb: 'Five tosses of pizza dough: hold to spin, catch it before it drops, too much spin tears it', music: false, forged: true },
1515 { id: 'harbour-crane', title: 'Harbour Crane', blurb: 'Stack ten crates onto a bobbing fishing boat from a swinging crane hook', music: false, forged: true },
1616 { id: 'sled-run', title: 'Sled Run', blurb: 'Ride a sledge down a snowy hill: tuck for speed, release on a kicker to jump, land flat', music: false, forged: true },
17 { id: 'row-home', title: 'Row Home', blurb: 'Race a rowing boat across the river against a bot: stroke in rhythm with the glide, too early catches a crab', music: false, forged: true },
1718 ];
1819 const MUSIC_VOLUME = .4;
1920 const CREDITS = [

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs