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

Migrated from github.com/amirmushichge/pixel-plays

Add Sled Run: ride a sledge down a snowy hill and land the jumps #23

Merged opened this

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

Merged

quill/pixel-plays:quill/12-add-sled-run-ride-a-sledge-down-a-snowy → main 3 commits fork

  • Merged. quill/12-add-sled-run-ride-a-sledge-down-a-snowy was merged into main as 0737544.

Review

Sign in to review this change.
7 files changed +494 −1
README.md +2 −1
@@ -19,6 +19,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
1919 | [Stone Skip](stone-skip/) | Skim a flat stone across a lake, five throws, count the bounces (forged by the crew on the engine and shell above, not by the original creators) | Drag back and release; arrows + space |
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 |
22 | [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 |
2223
2324 ## Run
2425 Requires [Node.js](https://nodejs.org/); nothing to install.
@@ -32,7 +33,7 @@ Then open http://127.0.0.1:5300/. `PORT` and `HOST` override the port and addres
3233 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.
3334
3435 ## Add a game
35 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 and Pizza Toss 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`.
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`.
3637
3738 - `shell.js` provides the game menu, the Rules popup, the credits and the background music.
3839 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
index.html +1
@@ -34,6 +34,7 @@ footer a { display: inline; padding: 0; font-weight: inherit; text-decoration: u
3434 <li><a href="paper-route/">Paper Route</a><span>Ten newspapers thrown from a passing bike: porch 3, lawn 1, a window costs 2</span><span>Game forged by the crew</span></li>
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>
37 <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>
3738 </ul>
3839 <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>
3940 </main>
serve.test.mjs +7
@@ -66,6 +66,13 @@ test('paper route is served without a track', async () => {
6666 expect((await fetch(base + '/paper-route/route.js')).status).toBe(200);
6767 });
6868
69 test('sled run is served without a track', async () => {
70 const page = await fetch(base + '/sled-run/');
71 expect(page.status).toBe(200);
72 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
73 expect((await fetch(base + '/sled-run/sled.js')).status).toBe(200);
74 });
75
6976 test('pizza toss is served without a track', async () => {
7077 const page = await fetch(base + '/pizza-toss/');
7178 expect(page.status).toBe(200);
shell.js +1
@@ -13,6 +13,7 @@ window.PixelPlays = (() => {
1313 { id: 'paper-route', title: 'Paper Route', blurb: 'Ten newspapers thrown from a passing bike: porch 3, lawn 1, a window costs 2', music: false, forged: true },
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 },
16 { 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 },
1617 ];
1718 const MUSIC_VOLUME = .4;
1819 const CREDITS = [
sled-run/index.html added +261
@@ -0,0 +1,261 @@
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>Sled Run</title>
7 <style>
8 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; --accent: #c4503a; }
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: flex; align-items: baseline; gap: 8px; pointer-events: none; }
16 #score { font-size: 16px; font-weight: 600; min-width: 1ch; color: var(--accent); font-variant-numeric: tabular-nums; }
17 #meta { color: var(--muted); font-variant-numeric: tabular-nums; }
18 #bottom { bottom: max(14px, env(safe-area-inset-bottom)); align-items: flex-end; }
19 #status { color: var(--muted); }
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="Sled Run. Hold the mouse, a finger or space to tuck and go faster; let go to sit up and steady. Let go on a kicker to jump, then hold briefly to level the nose and land flat."></canvas></div>
26 <div id="scores"><b id="score">0</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: 'sled-run',
35 rules: [
36 'Hold to tuck: faster and lower. Let go to sit up: slower and steadier.',
37 'Let go on a kicker to jump, then hold a moment to level the nose in the air.',
38 'Land flat for 30 points; land nose-down and you tumble. 40 seconds, distance counts too.',
39 ],
40 });
41 </script>
42 <script>window.PP_SCENE = { originY: 12, shadowX: 1.3, shadowY: -.12 };</script>
43 <script src="../engine.js"></script>
44 <script src="sled.js"></script>
45 <script>
46 'use strict';
47
48 const BEST_KEY = 'pixel-plays-sled-run-best';
49 const HALF = SledRun.LEN / 2; // the model runs 0..LEN along the slope; the world is centred on the origin
50 const SNOW = [[188, 202, 226], [200, 214, 236], [212, 224, 242], [224, 233, 247]];
51 const KICKER = [240, 245, 252], WOOD = [190, 116, 58], STEEL = [150, 158, 172];
52 const PINE = [[26, 62, 52], [40, 88, 62], [62, 116, 74]], SNOWCAP = [232, 240, 248];
53 const RIDER = { shirt: [196, 70, 52], stripe: [244, 236, 220], legs: [48, 58, 92], hair: [60, 40, 30], skin: [222, 170, 132] };
54 const PINES = [[-10.5, -4.8, 1], [-6.5, -5.3, .85], [-2, -5, 1.05], [3.5, -5.2, .9], [8, -4.9, 1], [11, -4.2, .8], [-9.5, 5.2, .9], [-4.5, 5.6, 1], [5.5, 5.4, .95], [10.5, 5, .85]];
55
56 /* ---------- ground ---------- */
57 function groundColor(x, y, ix, iy, i) {
58 const edge = Math.pow(Math.pow(Math.abs(x) / 13, 4) + Math.pow(Math.abs(y) / 6.8, 4), .25);
59 const rough = edge + (noise(x * 1.3, y * 1.3) - .5) * .1;
60 if (rough > 1.04) return 0;
61 if (rough > .94 && hash(ix, iy) < (rough - .94) / .1) return 0;
62 const packed = Math.abs(y) < 1.4 && Math.abs(x) < 11.8; // the groomed run is a touch brighter
63 const t = noise(x * .7, y * .7) * 1.1 + (hash(ix, iy) - .5) * .3 + (packed ? .25 : 0);
64 return rgb(...SNOW[clamp(Math.floor(t * 4 + (bayerAt(ix, iy) - .5) * .5), 0, 3)]);
65 }
66
67 // a pine: a trunk and tiers of needles that sway in drawLeaves, with snow on the upper boughs
68 function growPine(x, y, s, seed) {
69 capsule([x, y, 0], [x, y, 1.4 * s], .22 * s, .16 * s, () => BARK, 'rough');
70 for (let tier = 0; tier < 4; tier++) {
71 const z = (.9 + tier * 1.05) * s, radius = (1.6 - tier * .36) * s;
72 for (let n = 0; n < 60; n++) {
73 const k = seed + tier * 100 + n, a = hash(k, 7) * 6.283, d = Math.sqrt(hash(k, 8)) * radius;
74 const lx = x + Math.cos(a) * d, ly = y + Math.sin(a) * d, lz = z + (1 - d / radius) * 1.15 * s;
75 const capped = d / radius < .45 && hash(k, 9) > .35;
76 const needle = capped ? SNOWCAP : PINE[hash(k, 10) > .6 ? 2 : hash(k, 11) > .4 ? 1 : 0];
77 capture = [];
78 sphere(lx, ly, lz, (.2 + hash(k, 12) * .12) * s, needle, 'rough');
79 leaves.push({ x: lx, y: ly, z: lz, k, r: .36 * s, pixels: capture, reach: clamp((lz - 1) / 4, .25, .8) });
80 capture = null;
81 }
82 }
83 castShadow(x, y, 2 * s, 1.1 * s, 1, .4);
84 }
85 function growKicker(k) {
86 const x0 = k.at - HALF, step = .06;
87 for (let a = 0; a < k.len; a += step) box(x0 + a, -1.1, 0, x0 + a + step, 1.1, k.h * (a + step) / k.len, KICKER, 3);
88 castShadow(x0 + k.len, 0, k.h, 1.1, 1, .4);
89 }
90 function bake() {
91 zb.fill(-1e9);
92 pix.fill(rgb(255, 255, 255));
93 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
94 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy, i);
95 if (!c) continue;
96 pix[i] = c; ground[i] = 1;
97 zb[i] = (g.x + g.y) / R2 * COS;
98 }
99 groundZ.set(zb);
100 PINES.forEach(([x, y, s], n) => growPine(x, y, s, n * 977));
101 SledRun.KICKERS.forEach(growKicker);
102 bakeOcclusion();
103 staticShadow.set(shadowMask);
104 applyShadows(groundZ);
105 bakedPix.set(pix);
106 bakedZ.set(zb);
107 }
108
109 /* ---------- state ---------- */
110 const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })();
111 let ride = SledRun.newState(best0), time = 0, status = '', overT = 0, shown = '', note = '', noteT = 0;
112 const nodes = { score: document.getElementById('score'), meta: document.getElementById('meta'), status: document.getElementById('status') };
113 function renderHud() {
114 const text = ride.score + '|' + Math.ceil(ride.left) + '|' + ride.clean + '|' + ride.best;
115 if (text === shown) return;
116 shown = text;
117 nodes.score.textContent = ride.score;
118 nodes.meta.textContent = Math.ceil(ride.left) + 's · ' + Math.floor(ride.distance) + ' m · ' + ride.clean + ' clean · best ' + ride.best;
119 }
120 function setStatus(text) {
121 if (text === status) return;
122 status = text;
123 nodes.status.textContent = text;
124 }
125 function statusFor() {
126 if (ride.phase === 'ready') return 'hold to tuck, let go on a kicker to jump';
127 if (ride.phase === 'over') return ride.score + (ride.record ? ' · new best' : '') + ' · tap to ride again';
128 if (noteT > 0) return note;
129 if (ride.air) return ride.tuck ? 'nose dipping' : 'nose rising · hold to level';
130 return '';
131 }
132 function noteFor(event) {
133 return { clean: 'clean landing · +' + SledRun.CLEAN_POINTS, tumble: 'nose first · tumble', rough: 'nose high · rough landing' }[event] || '';
134 }
135 function press() {
136 ensureAudio();
137 if (ride.phase === 'over') { if (overT > .8) { ride = SledRun.newState(ride.best); shown = ''; } return; }
138 SledRun.setTuck(ride, true);
139 }
140 function release() { SledRun.setTuck(ride, false); }
141 function update(dt) {
142 time += dt;
143 noteT = Math.max(0, noteT - dt);
144 SledRun.step(ride, dt);
145 const e = ride.event;
146 if (e === 'launch') sound('launch');
147 else if (e === 'clean' || e === 'tumble' || e === 'rough') { sound(e); note = noteFor(e); noteT = 1.4; }
148 else if (e === 'over') { overT = 0; sound('point'); if (ride.record) try { localStorage.setItem(BEST_KEY, String(ride.best)); } catch (err) { /* private window: keep it for this visit */ } }
149 if (ride.phase === 'over') overT += dt;
150 setStatus(statusFor());
151 renderHud();
152 }
153
154 /* ---------- drawing ---------- */
155 function drawSled() {
156 const X = ride.x - HALF, tumbling = ride.tumble > 0, spin = tumbling ? 1 - ride.tumble / SledRun.TUMBLE : 0;
157 const theta = tumbling ? Math.min(Math.PI, spin * 7) : ride.pitch;
158 const cx = Math.cos(theta), sx = Math.sin(theta);
159 const z = ride.z + .14, tuck = ride.tuck && !ride.air && !tumbling;
160 const at = d => [X + cx * d, 0, z + sx * d + (tumbling ? Math.sin(spin * Math.PI) * 1.1 : 0)];
161 for (const y of [-.32, .32]) {
162 const a = at(-.85), b = at(.7), tip = at(1);
163 tip[2] += .22 * cx; tip[0] -= .1 * sx;
164 a[1] = b[1] = tip[1] = y;
165 dynamicAdd(a, b, .07, .07, () => STEEL);
166 dynamicAdd(b, tip, .07, .06, () => STEEL);
167 }
168 for (const d of [-.5, 0, .5]) {
169 const a = at(d), b = at(d);
170 a[1] = -.36; b[1] = .36; a[2] += .1; b[2] += .1;
171 dynamicAdd(a, b, .09, .09, () => WOOD);
172 }
173 const lie = tumbling && spin > .3;
174 const pose = tumbling
175 ? { z: lie ? 0 : at(0)[2] - .1, crouch: .9, lean: lie ? 1.45 : 1.1, stance: .1, armR: 1.8, armL: 1.8, scale: .8 }
176 : ride.air
177 ? { z: z + .1, crouch: ride.tuck ? .9 : .5, lean: ride.tuck ? .6 - ride.pitch * .3 : -.15 - ride.pitch * .3, stance: .3, armR: 1.1, armL: 1.1, scale: .8 }
178 : tuck
179 ? { z: z + .08, crouch: 1, lean: 1.0, stance: .1, armR: 1.5, armL: 1.5, scale: .8 }
180 : { z: z + .1, crouch: .5, lean: -.08, stance: .22, armR: 1.1, armL: 1.1, scale: .8 };
181 const wobble = !STILL && !tuck && !ride.air && !tumbling && ride.phase === 'run' ? Math.floor(time * WIND_FPS) % 2 * .02 : 0;
182 figure(X - .1, (lie ? .9 : 0) + wobble, 0, pose, RIDER, dynamicAdd);
183 }
184 function draw() {
185 pix.set(bakedPix);
186 zb.set(bakedZ);
187 pendingShadows.length = 0;
188 drawSled();
189 drawLeaves(STILL ? 0 : Math.floor(time * WIND_FPS) / WIND_FPS);
190 flushShadows();
191 applyShadows(bakedZ);
192 shadeEdges();
193 ctx.putImageData(image, 0, 0);
194 }
195
196 /* ---------- input ---------- */
197 canvas.addEventListener('pointerdown', e => {
198 canvas.setPointerCapture(e.pointerId);
199 canvas.focus({ preventScroll: true });
200 press();
201 });
202 canvas.addEventListener('pointerup', release);
203 canvas.addEventListener('pointercancel', release);
204 canvas.addEventListener('blur', release);
205 const KEYS = new Set([' ', 'ArrowDown', 'Enter']);
206 canvas.addEventListener('keydown', e => {
207 if (!KEYS.has(e.key)) return;
208 e.preventDefault();
209 if (!e.repeat) press();
210 });
211 canvas.addEventListener('keyup', e => { if (KEYS.has(e.key)) release(); });
212
213 /* ---------- sound ---------- */
214 let audio = null, muted = false;
215 function ensureAudio() {
216 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
217 const AC = window.AudioContext || window.webkitAudioContext;
218 if (AC) audio = new AC();
219 }
220 function sound(kind) {
221 if (!audio || muted) return;
222 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
223 const spec = {
224 launch: [300, 640, .14, .05, 'triangle'],
225 clean: [560, 840, .18, .08, 'triangle'],
226 rough: [180, 100, .12, .14, 'sine'],
227 tumble: [240, 60, .32, .18, 'triangle'],
228 point: [660, 880, .16, .08, 'triangle'],
229 }[kind];
230 osc.type = spec[4];
231 osc.frequency.setValueAtTime(spec[0], now);
232 osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]);
233 gain.gain.setValueAtTime(spec[3], now);
234 gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]);
235 osc.connect(gain).connect(audio.destination);
236 osc.start(now); osc.stop(now + spec[2] + .01);
237 }
238 const muteButton = document.getElementById('mute');
239 muteButton.addEventListener('click', () => {
240 muted = !muted;
241 muteButton.textContent = muted ? 'sound off' : 'sound on';
242 muteButton.setAttribute('aria-pressed', String(muted));
243 });
244
245 /* ---------- boot ---------- */
246 addEventListener('resize', fit);
247 fit();
248 bake();
249 renderHud();
250 setStatus(statusFor());
251 let last = performance.now();
252 function frame(now) {
253 update(Math.min(.04, (now - last) / 1000));
254 last = now;
255 draw();
256 requestAnimationFrame(frame);
257 }
258 requestAnimationFrame(frame);
259 </script>
260 </body>
261 </html>
sled-run/sled.js added +83
@@ -0,0 +1,83 @@
1 'use strict';
2 // Sled Run rules as plain data in, plain data out: speed, kickers, jumps, landings and the score.
3 // The page draws from this state and the tests drive it, so both read the same numbers.
4 (function (root) {
5 const ROUND = 40, LEN = 20, GRAVITY = 18;
6 const SIT = 4.6, TUCK = 8, SPEED_UP = 5, SPEED_DOWN = 3; // metres per second, and how fast the sledge changes speed
7 const KICKERS = [{ at: 2.5, len: 1.8, h: .9 }, { at: 11, len: 1.8, h: .9 }];
8 const LAUNCH_PITCH = .5; // nose-up angle a kicker throws you at, in radians
9 const NOSE_DOWN = -.35, NOSE_UP = .35; // flat is between these; below tumbles, above lands rough
10 const PITCH_HOLD = -2.6, PITCH_FREE = 1; // radians per second in the air: tucking dips the nose, sitting up raises it
11 const TUMBLE = 1.1, CLEAN_POINTS = 30;
12 const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
13
14 function newState(best = 0) {
15 return {
16 phase: 'ready', t: 0, left: ROUND, x: 0, z: 0, vz: 0, pitch: 0, speed: SIT, tuck: false, air: false, jumped: false,
17 tumble: 0, distance: 0, clean: 0, tumbles: 0, score: 0, best: Math.max(0, Math.floor(Number(best)) || 0), record: false, event: '',
18 };
19 }
20 // height of the snow under x: a kicker is a wedge that climbs to h then drops away
21 function groundAt(x) {
22 for (const k of KICKERS) if (x >= k.at && x <= k.at + k.len) return k.h * (x - k.at) / k.len;
23 return 0;
24 }
25 const onKicker = x => KICKERS.some(k => x >= k.at && x <= k.at + k.len);
26 const scoreOf = S => Math.floor(S.distance) + S.clean * CLEAN_POINTS;
27
28 // hold = tuck, release = sit up; the first press starts the run, a release on a kicker jumps
29 function setTuck(S, on) {
30 on = !!on;
31 if (S.phase === 'ready' && on) S.phase = 'run';
32 if (S.phase !== 'run') { S.tuck = false; return; }
33 if (S.tuck && !on && !S.air && S.tumble <= 0 && onKicker(S.x)) {
34 S.air = true; S.jumped = true;
35 S.vz = 2.5 + S.speed * .5; S.pitch = LAUNCH_PITCH;
36 S.event = 'launch';
37 }
38 S.tuck = on;
39 }
40 function land(S) {
41 S.air = false; S.z = groundAt(S.x); S.vz = 0;
42 const p = S.pitch;
43 S.pitch = 0;
44 if (!S.jumped) return;
45 S.jumped = false;
46 if (p < NOSE_DOWN) { S.tumble = TUMBLE; S.speed = 0; S.tumbles++; S.event = 'tumble'; }
47 else if (p > NOSE_UP) { S.speed *= .6; S.event = 'rough'; }
48 else { S.clean++; S.event = 'clean'; }
49 }
50 // advance by dt seconds; S.event names what just happened ('' when nothing) for the page to sound and show
51 function step(S, dt) {
52 S.event = '';
53 if (S.phase !== 'run') return S;
54 dt = clamp(dt, 0, .1);
55 S.t += dt; S.left = Math.max(0, ROUND - S.t);
56 if (S.tumble > 0) {
57 S.tumble = Math.max(0, S.tumble - dt);
58 if (!S.tumble) { S.speed = 1.5; S.tuck = false; }
59 } else if (!S.air) {
60 const target = S.tuck ? TUCK : SIT;
61 S.speed += clamp(target - S.speed, -SPEED_DOWN * dt, SPEED_UP * dt);
62 }
63 if (S.tumble <= 0) {
64 const dx = S.speed * dt;
65 S.x += dx; S.distance += dx;
66 if (S.air) {
67 S.vz -= GRAVITY * dt; S.z += S.vz * dt;
68 S.pitch = clamp(S.pitch + (S.tuck ? PITCH_HOLD : PITCH_FREE) * dt, -1.6, 1.6);
69 if (S.vz < 0 && S.z <= groundAt(S.x)) land(S);
70 } else S.z = groundAt(S.x);
71 }
72 if (S.x >= LEN) { S.x -= LEN; }
73 S.score = scoreOf(S);
74 if (S.left <= 0) {
75 S.phase = 'over'; S.tuck = false; S.air = false; S.z = 0; S.pitch = 0;
76 if (S.score > S.best) { S.best = S.score; S.record = true; }
77 S.event = 'over';
78 }
79 return S;
80 }
81 const api = { ROUND, LEN, SIT, TUCK, KICKERS, TUMBLE, CLEAN_POINTS, newState, groundAt, onKicker, setTuck, step };
82 if (typeof module !== 'undefined') module.exports = api; else root.SledRun = api;
83 })(typeof window !== 'undefined' ? window : globalThis);
sled-run/sled.test.mjs added +139
@@ -0,0 +1,139 @@
1 import { test, expect } from 'bun:test';
2 import { ROUND, SIT, TUCK, KICKERS, TUMBLE, CLEAN_POINTS, newState, groundAt, onKicker, setTuck, step } from './sled.js';
3
4 const run = (S, seconds, dt = 1 / 60) => { for (let t = 0; t < seconds; t += dt) step(S, dt); return S; };
5 // ride tucked until the middle of the first kicker, then release
6 function jump(S) {
7 setTuck(S, true);
8 while (S.x < KICKERS[0].at + 1.2) step(S, 1 / 60);
9 setTuck(S, false);
10 return S;
11 }
12 // jump, then hold the tuck for `hold` seconds in the air, and return what the landing was
13 function landing(hold) {
14 const S = jump(newState());
15 let held = 0, seen = '';
16 for (let n = 0; n < 600 && S.air; n++) {
17 setTuck(S, held < hold);
18 if (held < hold) held += 1 / 60;
19 step(S, 1 / 60);
20 if (S.event) seen = S.event;
21 }
22 return seen;
23 }
24
25 test('nothing moves until the first press', () => {
26 const S = newState();
27 run(S, 2);
28 expect(S.x).toBe(0);
29 expect(S.phase).toBe('ready');
30 setTuck(S, true);
31 expect(S.phase).toBe('run');
32 });
33
34 test('tucking goes faster than sitting up', () => {
35 const tucked = newState(), sat = newState();
36 setTuck(tucked, true); setTuck(sat, true); setTuck(sat, false);
37 run(tucked, 1.5); run(sat, 1.5);
38 expect(tucked.speed).toBeCloseTo(TUCK);
39 expect(sat.speed).toBeCloseTo(SIT);
40 expect(tucked.distance).toBeGreaterThan(sat.distance);
41 });
42
43 test('releasing on a kicker launches, nose up', () => {
44 const S = jump(newState());
45 expect(S.air).toBe(true);
46 expect(S.event).toBe('launch');
47 expect(S.pitch).toBeGreaterThan(0);
48 step(S, 1 / 60);
49 expect(S.z).toBeGreaterThan(groundAt(S.x));
50 });
51
52 test('releasing off a kicker stays on the snow', () => {
53 const S = newState();
54 setTuck(S, true);
55 run(S, .2);
56 expect(onKicker(S.x)).toBe(false);
57 setTuck(S, false);
58 expect(S.air).toBe(false);
59 });
60
61 test('riding off a kicker without releasing earns nothing', () => {
62 const S = newState();
63 setTuck(S, true);
64 run(S, 3);
65 expect(S.air).toBe(false);
66 expect(S.clean + S.tumbles).toBe(0);
67 });
68
69 test('landing flat is a clean landing worth points', () => {
70 const S = jump(newState());
71 const before = S.score;
72 let held = 0;
73 while (S.air) { setTuck(S, held < .3); held += 1 / 60; step(S, 1 / 60); }
74 expect(S.event).toBe('clean');
75 expect(S.clean).toBe(1);
76 expect(S.score).toBeGreaterThanOrEqual(before + CLEAN_POINTS);
77 expect(landing(.3)).toBe('clean');
78 });
79
80 test('landing nose-down tumbles the rider and stops the sledge', () => {
81 expect(landing(10)).toBe('tumble');
82 const S = jump(newState());
83 setTuck(S, true);
84 while (S.air) step(S, 1 / 60);
85 expect(S.tumbles).toBe(1);
86 expect(S.speed).toBe(0);
87 const x = S.x;
88 run(S, TUMBLE / 2);
89 expect(S.x).toBe(x);
90 run(S, TUMBLE);
91 expect(S.tumble).toBe(0);
92 expect(S.speed).toBeGreaterThan(0);
93 });
94
95 test('landing nose-up is rough: no points, no tumble', () => {
96 expect(landing(0)).toBe('rough');
97 });
98
99 test('a clean landing adds its points on top of distance', () => {
100 const S = newState();
101 S.distance = 100; S.clean = 2;
102 step(S, 0); // not running: score untouched
103 expect(S.score).toBe(0);
104 setTuck(S, true);
105 step(S, 1 / 60);
106 expect(S.score).toBe(Math.floor(S.distance) + 2 * CLEAN_POINTS);
107 });
108
109 test('the sledge wraps to the top of the hill', () => {
110 const S = newState();
111 setTuck(S, true);
112 run(S, 6);
113 expect(S.x).toBeLessThan(20);
114 });
115
116 test('the run lasts the round, then keeps the best', () => {
117 const S = newState(5);
118 setTuck(S, true);
119 run(S, ROUND - 1);
120 expect(S.phase).toBe('run');
121 run(S, 2);
122 expect(S.phase).toBe('over');
123 expect(S.event).toBe('');
124 expect(S.best).toBe(S.score);
125 expect(S.record).toBe(true);
126 const keep = S.score;
127 run(S, 5);
128 expect(S.score).toBe(keep);
129 });
130
131 test('a lower score leaves the best alone, and a bad best is ignored', () => {
132 const S = newState(1e6);
133 setTuck(S, true);
134 run(S, ROUND + 1);
135 expect(S.best).toBe(1e6);
136 expect(S.record).toBe(false);
137 expect(newState(NaN).best).toBe(0);
138 expect(newState(-4).best).toBe(0);
139 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs