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

Migrated from github.com/amirmushichge/pixel-plays

Add Stone Skip: skim a flat stone across a lake, count the bounces #8

Merged opened this

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

Merged

quill/pixel-plays:quill/4-add-stone-skip-skim-a-flat-stone-across → main 3 commits fork 7 threads · 7 unresolved

  • Merged. quill/4-add-stone-skip-skim-a-flat-stone-across was merged into main as 9b1d2b8.

Review

Sign in to review this change.
7 files changed +541 −4
README.md +2 −1
@@ -14,6 +14,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
1414 | [Rooftop Laundry](laundry/) | Get the washing into the basket before the storm | Drag; space |
1515 | [Tie-Break](tie-break/) | Clay-court tie-break against a bot, the moment you hit decides where the ball lands | Tap; space |
1616 | [Mini Ramp](mini-ramp/) | 60 seconds on a skateboard ramp, pump for height and grab in the air | Hold and release; space |
17 | [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 |
1718
1819 ## Run
1920 Requires [Node.js](https://nodejs.org/); nothing to install.
@@ -27,7 +28,7 @@ Then open http://127.0.0.1:5300/. `PORT` and `HOST` override the port and addres
2728 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.
2829
2930 ## Add a game
30 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`.
31 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 plays on its own sound effects).
3132
3233 - `shell.js` provides the game menu, the Rules popup, the credits and the background music.
3334 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
serve.test.mjs +7
@@ -22,6 +22,13 @@ test('every game page and its track is served', async () => {
2222 }
2323 });
2424
25 test('stone skip is served without a track', async () => {
26 const page = await fetch(base + '/stone-skip/');
27 expect(page.status).toBe(200);
28 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
29 expect((await fetch(base + '/stone-skip/skip.js')).status).toBe(200);
30 });
31
2532 test('a game folder without its slash redirects to it', async () => {
2633 const res = await fetch(base + '/balote', { redirect: 'manual' });
2734 expect(res.status).toBe(308);
shell.js +15 −3
@@ -1,19 +1,25 @@
11 'use strict';
22 // Shared chrome for every game: game menu (top centre) and rules popup (top right).
33 window.PixelPlays = (() => {
4 // add a game here and give it a folder; `soon` entries show in the menu but do not link
4 // add a game here and give it a folder (`music: false` when it has no track, `forged: true` when it was made on the forge rather than by the original creators); `soon` entries show in the menu but do not link
55 const GAMES = [
66 { id: 'balote', title: 'Balote' },
77 { id: 'stari-most', title: 'Stari Most' },
88 { id: 'laundry', title: 'Rooftop Laundry' },
99 { id: 'tie-break', title: 'Tie-Break' },
1010 { id: 'mini-ramp', title: 'Mini Ramp' },
11 { id: 'stone-skip', title: 'Stone Skip', music: false, forged: true },
1112 ];
1213 const MUSIC_VOLUME = .4;
1314 const CREDITS = [

These credits now show on Stone Skip too, saying AmirMushich made it. Give each game its own credit so forge-made games say they were forged here on AmirMushich's engine.

1415 ['Concept by', 'abhi', 'https://x.com/awwbhi2'],
1516 ['Game by', 'AmirMushich', 'https://x.com/AmirMushich'],
1617 ];
18 const FORGED_CREDITS = [
19 ['Concept by', 'abhi', 'https://x.com/awwbhi2'],
20 ['Engine by', 'AmirMushich', 'https://x.com/AmirMushich'],
21 ];
22 const FORGED_NOTE = 'Game forged by the crew';
1723 const css = `
1824 .pp-link { font: inherit; color: #8b877f; background: none; border: 0; padding: 10px; margin: 0; cursor: pointer; }
1925 .pp-link:hover, .pp-link:focus-visible, .pp-link[aria-expanded="true"] { color: #1c1b19; }
@@ -109,7 +115,7 @@ window.PixelPlays = (() => {
109115
110116 const credits = document.createElement('div');
111117 credits.id = 'pp-credits';
112 for (const [label, name, url] of CREDITS) {
118 for (const [label, name, url] of game.forged ? FORGED_CREDITS : CREDITS) {
113119 const line = document.createElement('span');
114120 const link = document.createElement('a');
115121 link.href = url;
@@ -120,8 +126,14 @@ window.PixelPlays = (() => {
120126 credits.append(line);
121127 }
122128
129 if (game.forged) {
130 const note = document.createElement('span');
131 note.textContent = FORGED_NOTE;
132 credits.append(note);
133 }
134
123135 document.body.append(menu, open, dialog, credits);
124 startMusic(id);
136 if (game.music !== false) startMusic(id);
125137 }
126138 // each game loops <id>/<id>.mp3 from the first gesture, because browsers block sound before one.
127139 // The game's own sound button mutes it too.
shell.test.mjs added +48
@@ -0,0 +1,48 @@
1 import { test, expect } from 'bun:test';
2
3 // a stand-in element that accepts everything shell.js does to it
4 const element = () => ({
5 children: [], style: {}, classList: { add() {}, remove() {}, toggle() {} },
6 append(...n) { this.children.push(...n); }, addEventListener() {}, setAttribute() {}, showModal() {}, close() {},
7 });
8 const SAVED = ['window', 'document', 'Audio', 'PixelPlays'];
9 let audios, byId;
10 // stubs live only while a test runs, so they never leak into the server tests in the same process
11 function stub() {
12 audios = []; byId = {};
13 globalThis.window = globalThis;
14 globalThis.Audio = class { constructor(src) { this.src = src; audios.push(src); } play() { return Promise.resolve(); } pause() {} };
15 globalThis.document = {
16 head: element(), body: element(), hidden: false, addEventListener() {},
17 createElement: () => element(),
18 getElementById: id => (byId[id] ??= element()),
19 };
20 }
21 function unstub() { for (const k of SAVED) delete globalThis[k]; }
22 function guarded(fn) { return async () => { stub(); try { await fn(); } finally { unstub(); } }; }
23 let loads = 0;
24 async function mount(id) {
25 await import('./shell.js?' + loads++);
26 window.PixelPlays.mount({ id, rules: ['x'] });
27 return document.body.children.at(-1);
28 }
29 const text = el => typeof el === 'string' ? el : [el.textContent ?? '', ...(el.children ?? []).map(text)].join(' ');
30
31 test('a game with a track builds an Audio for it', guarded(async () => {
32 await mount('balote');
33 expect(audios).toEqual(['balote.mp3']);
34 }));
35
36 test('a music: false game never asks for a track', guarded(async () => {
37 await mount('stone-skip');
38 expect(audios).toEqual([]);
39 }));
40
41 test('forged games credit the engine, not the game, to AmirMushich', guarded(async () => {
42 const credits = await mount('stone-skip');
43 const t = text(credits);
44 expect(t).toContain('Engine by');
45 expect(t).toContain('forged by the crew');
46 expect(t).not.toContain('Game by');
47 expect(text(await mount('balote'))).toContain('Game by');
48 }));
stone-skip/index.html added +375
@@ -0,0 +1,375 @@
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>Stone Skip</title>
7 <style>
8 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; --accent: #3f7f9c; }
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: grab; outline: none; }
14 canvas:active { cursor: grabbing; }
15 .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; }
16 #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; }
17 #bottom { bottom: max(14px, env(safe-area-inset-bottom)); align-items: flex-end; }
18 .row { display: flex; align-items: center; gap: 8px; color: var(--accent); }
19 .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; }
20 .row span { color: var(--muted); }
21 .dots { display: flex; gap: 3px; }
22 .dots i { width: 6px; height: 6px; background: var(--accent); }
23 .dots i.off { opacity: .16; }
24 #status { color: var(--muted); }
25 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
26 button:hover, button:focus-visible { color: var(--ink); }
27 </style>
28 </head>
29 <body>
30 <div id="stage"><canvas id="c" tabindex="0" aria-label="Lake shore. Drag back and release to throw the stone, or use arrow keys and space."></canvas></div>
31 <div id="scores">
32 <div class="row"><b id="bounces">0</b><span>bounces</span></div>
33 <div class="row"><b id="best">0</b><span>best</span><span class="dots" id="throws"></span></div>
34 </div>
35 <div class="hud" id="bottom">
36 <div id="status" role="status" aria-live="polite"></div>
37 <button id="mute" type="button" aria-pressed="false">sound on</button>
38 </div>
39 <script src="../shell.js"></script>
40 <script>
41 PixelPlays.mount({
42 id: 'stone-skip',
43 rules: [
44 'Skim the stone across the lake and count the bounces. You get five throws; your best counts.',
45 'Drag back and release to throw: pull further for power, pull down to throw higher. Keyboard: arrows to set angle and power, space to throw.',
46 'Too steep or too slow and the stone sinks on its first touch. Throw flat and fast to skip more.',
47 ],
48 });
49 </script>
50 <script>window.PP_SCENE = { originY: 16, shadowX: 1.3, shadowY: -.12 };</script>
51 <script src="../engine.js"></script>
52 <script src="skip.js"></script>
53 <script>
54 'use strict';
55
56 const SKIP = window.StoneSkip;
57 const THROWS = 5, THROW_X = -8.6, BANK_X = 12;
58 const KIND_WATER = 4, KIND_SAND = 5;
59 const SAND = [222, 198, 154], WATER = [70, 134, 168], STONE = [128, 126, 132];
60 const WATER_TONES = [[58, 118, 154], [64, 127, 161], [72, 137, 170], [84, 150, 181]];
61 const SAND_TONES = [[200, 174, 132], [212, 187, 144], [222, 198, 154], [231, 209, 166]];
62 const FOAM = rgb(232, 244, 248);
63 const HIKER = { shirt: [196, 120, 52], stripe: [240, 232, 214], legs: [52, 62, 82], hair: [60, 42, 30], skin: [222, 170, 132] };
64
65 // where the water begins along x, wobbling with y so the shore is not a ruler
66 const shoreAt = y => SKIP.WATER_X + (noise(y * .5, 3) - noise(0, 3)) * 1.6;
67 const bankAt = y => BANK_X + (noise(y * .6, 9) - .5) * 1.4;
68 function groundColor(x, y, ix, iy, i) {
69 const edge = Math.pow(Math.pow(Math.abs(x) / 16.2, 4) + Math.pow(Math.abs(y) / 7.4, 4), .25);
70 const rough = edge + (noise(x * 1.3, y * 1.3) - .5) * .13;
71 if (rough > 1.04) return 0;
72 if (rough > .93 && hash(ix, iy) < (rough - .93) / .11) return 0;
73 const fine = hash(ix, iy);
74 if (x > shoreAt(y) && x < bankAt(y)) {
75 kinds[i] = KIND_WATER;
76 const depth = noise(x * .35, y * .5) * .8 + noise(x * 1.7, y * 2.4) * .25 + (fine - .5) * .12;
77 return rgb(...WATER_TONES[clamp(Math.floor(depth * 4 + (bayerAt(ix, iy) - .5) * .5), 0, 3)]);
78 }
79 const wet = Math.min(Math.abs(x - shoreAt(y)), Math.abs(x - bankAt(y)));
80 if (wet < 1.1 + noise(x * 2, y * 2) * .9) {
81 kinds[i] = KIND_SAND;
82 if (fine > .985) return rampOf(SAND)[4];
83 if (hash(ix - 1, iy - 1) > .985) return rampOf(SAND)[1];
84 return rgb(...SAND_TONES[clamp(Math.floor(noise(x * .8, y * .8) * 4 + (bayerAt(ix, iy) - .5) * .5), 0, 3)]);
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 // tall reeds standing in the grass where it meets the sand; they sway with the other tufts
92 function growReeds() {
93 for (let iy = 4; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
94 const i = iy * W + ix;
95 if (kinds[i] !== KIND_GRASS || hash(ix * 5, iy * 3) > .5) continue;
96 const g = unproject(ix + .5, iy + .5);
97 const near = Math.min(Math.abs(g.x - shoreAt(g.y)), Math.abs(g.x - bankAt(g.y)));
98 if (near > 2.4 || hash(ix * 2, iy * 7) > .5) continue;
99 tufts.push({ ix, iy, i, height: 4 + (hash(ix, iy * 3) * 3 | 0), base: 1, phase: ix * .11 + iy * .19 + hash(ix, iy), bloom: 0 });
100 }
101 }
102
103 function bake() {
104 zb.fill(-1e9);
105 pix.fill(rgb(255, 255, 255));
106 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
107 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy, i);
108 if (!c) continue;
109 pix[i] = c; ground[i] = 1;
110 zb[i] = (g.x + g.y) / R2 * COS;
111 }
112 growGrass();
113 growReeds();
114 groundZ.set(zb);
115
116 growTree(-11.5, -4.6, 1, 420, 11);
117 // a little heap of flat stones by the thrower's feet
118 for (const [dx, dy, dz] of [[.2, 1.1, .1], [.55, 1.35, .1], [.4, 1.2, .26]]) {
119 sphere(THROW_X + dx, dy, dz, .2, STONE, 'rough');
120 castShadow(THROW_X + dx, dy, dz, .22);
121 }
122 bakeOcclusion();
123 staticShadow.set(shadowMask);
124 applyShadows(groundZ);
125 bakedPix.set(pix);
126 bakedZ.set(zb);
127 }
128
129 /* ---------- game state ---------- */
130 const G = {
131 phase: 'aim', power: .6, pitch: .08, swing: 0, timer: 0, time: 0, stone: null,
132 throwsLeft: THROWS, bounces: 0, best: 0, ripples: [], pointer: null, status: '',
133 };
134 const nodes = {
135 bounces: document.getElementById('bounces'), best: document.getElementById('best'),
136 throws: document.getElementById('throws'), status: document.getElementById('status'),
137 };
138 function renderHud() {
139 nodes.bounces.textContent = G.bounces;
140 nodes.best.textContent = G.best;
141 if (nodes.throws.children.length !== THROWS) nodes.throws.innerHTML = '<i></i>'.repeat(THROWS);
142 [...nodes.throws.children].forEach((el, k) => el.classList.toggle('off', k >= G.throwsLeft));
143 }
144 function setStatus(text) {
145 if (text === G.status) return;
146 G.status = text;
147 nodes.status.textContent = text;
148 }
149 function newThrow() {
150 G.phase = 'aim'; G.stone = null; G.bounces = 0; G.timer = 0;
151 setStatus('drag back, release to throw');
152 renderHud();
153 }
154 function resetGame() {
155 G.throwsLeft = THROWS; G.best = 0; G.ripples = [];
156 newThrow();
157 }
158 function release() {
159 if (G.power < .05) return;
160 G.phase = 'swing'; G.swing = 0; G.released = false;
161 setStatus('');
162 }
163 function launch() {
164 G.stone = SKIP.launch(G.power, G.pitch);
165 G.throwsLeft--; G.bounces = 0;
166 renderHud();
167 sound('whoosh');
168 }
169 function ripple(x, big) {
170 G.ripples.push({ x, age: 0, life: big ? 1.4 : 1.0, reach: big ? 1.6 : 1.1 });
171 }
172 function finishThrow(how) {
173 G.phase = 'done'; G.timer = 0;
174 const n = G.bounces, record = n > G.best;
175 if (record) { G.best = n; sound('point'); }
176 const last = G.throwsLeft === 0;
177 const what = how === 'land' ? 'it drops on the sand' : n ? 'it sinks' : 'it sinks at once';
178 setStatus(`${n} ${n === 1 ? 'bounce' : 'bounces'}, ${what}${record && n ? ', a new best' : ''}${last ? ` · best ${G.best} · tap to play again` : ' · tap to throw again'}`);
179 renderHud();
180 }
181
182 function update(dt) {
183 G.time += dt;
184 for (const r of G.ripples) r.age += dt;
185 G.ripples = G.ripples.filter(r => r.age < r.life);
186 if (G.phase === 'swing') {
187 G.swing = Math.min(1, G.swing + dt / .22);
188 if (!G.released && G.swing > .62) { G.released = true; launch(); G.phase = 'fly'; G.timer = 0; }
189 } else if (G.phase === 'fly') {
190 G.timer += dt;
191 const s = G.stone;
192 for (let k = 0; k < 4 && s.state === 'air'; k++) {
193 const e = SKIP.step(s, dt / 4);
194 if (e === 'bounce') { G.bounces = s.bounces; ripple(s.x, false); sound('plink', s.bounces); renderHud(); }
195 else if (e === 'sink') { ripple(s.x, true); sound('sink'); finishThrow('sink'); }
196 else if (e === 'land') { sound('thud'); finishThrow('land'); }
outdated

This branch never runs (see skip.js:21).

197 }
198 } else if (G.phase === 'done') {
199 G.timer += dt;
200 }
201 }
202
203 /* ---------- drawing ---------- */
204 const POSE_STANCE = .22;
205 function poseFor(active) {
206 const breathe = Math.sin(G.time * 1.8) * .012;
207 if (!active) return { armR: .05 + breathe, armL: .1, stance: .1, lean: breathe };
208 if (G.phase === 'aim') {
209 const pull = G.power;
210 return { crouch: .3 + G.pitch * .3 + pull * .3, lean: .25 + pull * .2, stance: POSE_STANCE, armR: -.1 - pull * 1.1, armL: .3 + pull * .3 };
211 }
212 if (G.phase === 'swing') {
213 const t = ease(G.swing), from = -.1 - G.power * 1.1;
214 return { crouch: lerp(.3 + G.power * .3, .4, t), lean: lerp(.25 + G.power * .2, .5, t), stance: .3, armR: lerp(from, 1.35, t), armL: lerp(.3, -.25, t) };
215 }
216 const settle = clamp(G.timer * 1.5, 0, 1);
217 return { crouch: lerp(.4, .08, ease(settle)), lean: lerp(.5, .08, ease(settle)), stance: lerp(.3, .14, settle), armR: lerp(1.35, .1, ease(settle)), armL: lerp(-.25, .1, settle) };
218 }
219 function drawAim() {
220 if (G.power < .05) return;
221 const s = SKIP.launch(G.power, G.pitch), dots = [];
222 let landed = null;
223 for (let k = 0; k < 60; k++) {
224 s.vz -= SKIP.GRAVITY * .03;
225 s.x += s.vx * .03; s.z += s.vz * .03;
226 if (s.z <= SKIP.RADIUS) { landed = s.x; break; }
227 if (k % 2 === 0) { const p = project(s.x, 0, s.z); dots.push([p.sx, p.sy]); }
228 }
229 const dark = rgb(28, 27, 25);
230 drawDots(dots, dark);
231 if (landed !== null) {
232 const p = project(landed, 0, 0), cross = [];
233 for (let k = -2; k <= 2; k++) cross.push([p.sx + k, p.sy], [p.sx, p.sy + k]);
234 drawDots(cross, dark);
235 }
236 }
237 // rings of foam on the water: whole pixels, thinning out as they spread
238 function drawRipples() {
239 for (const r of G.ripples) {
240 const t = r.age / r.life, radius = .25 + ease(t) * r.reach, fade = 1 - t;
241 const n = Math.ceil(radius * S * 5);
242 for (let k = 0; k < n; k++) {
243 const a = k / n * Math.PI * 2, p = project(r.x + Math.cos(a) * radius, Math.sin(a) * radius, 0);
244 const ix = p.sx | 0, iy = p.sy | 0;
245 if (ix < 0 || iy < 0 || ix >= W || iy >= H) continue;
246 const i = iy * W + ix;
247 if (kinds[i] === KIND_WATER && bayerAt(ix, iy) < fade) pix[i] = FOAM;
248 }
249 }
250 }
251 function draw() {
252 pix.set(bakedPix);
253 zb.set(bakedZ);
254 const active = G.phase !== 'done' || G.timer < 1;
255 pendingShadows.length = 0;
256 const hand = figure(THROW_X, 0, 0, poseFor(active), HIKER, dynamicAdd);
257 if (G.phase === 'aim') {
258 sphere(hand[0], hand[1], hand[2] - .04, .2, STONE, 'gloss');
259 pendingShadows.push(hand, .2, hand, .2);
260 }
261 const s = G.stone;
262 if (s && s.state !== 'sunk') {
263 sphere(s.x, 0, s.z, .2, STONE, 'gloss');
264 castShadow(s.x, 0, s.z - .2, .2, 1, 0);
265 }
266 const windT = STILL ? 0 : Math.floor(G.time * WIND_FPS) / WIND_FPS;
267 drawLeaves(windT);
268 drawTufts(windT);
269 flushShadows();
270 applyShadows(bakedZ);
271 shadeEdges();
272 drawRipples();
273 if (G.phase === 'aim') drawAim();
274 ctx.putImageData(image, 0, 0);
275 }
276
277 /* ---------- input ---------- */
278 const PULL_FULL = 90; // canvas pixels of pull for full power
279 function toCanvas(e) {
280 const r = canvas.getBoundingClientRect();
281 return { x: (e.clientX - r.left) * W / r.width, y: (e.clientY - r.top) * H / r.height };
282 }
283 canvas.addEventListener('pointerdown', e => {
284 ensureAudio();
285 canvas.focus({ preventScroll: true });
286 if (G.phase === 'done' && G.timer > .5) return G.throwsLeft ? newThrow() : resetGame();
287 if (G.phase !== 'aim') return;
288 canvas.setPointerCapture(e.pointerId);
289 G.pointer = toCanvas(e);
290 });
291 canvas.addEventListener('pointermove', e => {
292 if (!G.pointer) return;
293 const p = toCanvas(e), dx = p.x - G.pointer.x, dy = p.y - G.pointer.y;
294 G.power = clamp(Math.hypot(dx, dy) / PULL_FULL, 0, 1);
295 // pulling back flat throws flat; pulling down throws higher
296 G.pitch = clamp(Math.atan2(dy, -dx), 0, SKIP.MAX_PITCH);
297 });
298 canvas.addEventListener('pointerup', () => {
299 if (!G.pointer) return;
300 G.pointer = null;
301 if (G.phase === 'aim') release();
302 });
303 canvas.addEventListener('pointercancel', () => { G.pointer = null; });
304 canvas.addEventListener('keydown', e => {
305 ensureAudio();
306 if (e.key === ' ' || e.key === 'Enter') {
307 e.preventDefault();
308 if (G.phase === 'done' && G.timer > .5) return G.throwsLeft ? newThrow() : resetGame();
309 if (G.phase === 'aim') release();
310 return;
311 }
312 if (G.phase !== 'aim') return;
313 if (e.key === 'ArrowLeft') G.power = clamp(G.power - .03, 0, 1);
314 else if (e.key === 'ArrowRight') G.power = clamp(G.power + .03, 0, 1);
315 else if (e.key === 'ArrowUp') G.pitch = clamp(G.pitch + .02, 0, SKIP.MAX_PITCH);
316 else if (e.key === 'ArrowDown') G.pitch = clamp(G.pitch - .02, 0, SKIP.MAX_PITCH);
317 else return;
318 e.preventDefault();
319 });
320
321 /* ---------- sound ---------- */
322 let audio = null, muted = false;
323 function ensureAudio() {
324 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
325 const AC = window.AudioContext || window.webkitAudioContext;
326 if (AC) audio = new AC();
327 }
328 function sound(kind, n = 1) {
329 if (!audio || muted) return;
330 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
331 const spec = {
332 plink: [520 + n * 90, 300 + n * 40, .07, .1, 'sine'], // each skip a little higher
333 sink: [260, 90, .22, .22, 'sine'],
334 thud: [150, 70, .09, .2, 'sine'],
335 whoosh: [320, 180, .1, .035, 'triangle'],
336 point: [660, 880, .16, .08, 'triangle'],
337 }[kind];
338 osc.type = spec[4];
339 osc.frequency.setValueAtTime(spec[0], now);
340 osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]);
341 gain.gain.setValueAtTime(spec[3], now);
342 gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]);
343 osc.connect(gain).connect(audio.destination);
344 osc.start(now); osc.stop(now + spec[2] + .01);
345 }
346 const muteButton = document.getElementById('mute');
347 muteButton.addEventListener('click', () => {
348 muted = !muted;
349 muteButton.textContent = muted ? 'sound off' : 'sound on';
350 muteButton.setAttribute('aria-pressed', String(muted));
351 });
352
353 /* ---------- fit and boot ---------- */
354 function fit() {
355 const dpr = window.devicePixelRatio || 1;
356 const fitScale = Math.min(innerWidth / W, (innerHeight - 40) / H);
357 const scale = Math.max(1, Math.floor(fitScale * dpr)) / dpr;
358 canvas.style.width = W * scale + 'px';
359 canvas.style.height = H * scale + 'px';
360 }
361 addEventListener('resize', fit);
362 fit();
363 bake();
364 newThrow();
365 let last = performance.now();
366 function frame(now) {
367 update(Math.min(.04, (now - last) / 1000));
368 last = now;
369 draw();
370 requestAnimationFrame(frame);
371 }
372 requestAnimationFrame(frame);
373 </script>
outdated

A debug hook nothing uses. Remove it, or use it in a page test.

374 </body>
375 </html>
stone-skip/skip.js added +45
@@ -0,0 +1,45 @@
1 'use strict';
2 // The physics of one throw: plain numbers in, plain numbers out, no DOM. The page draws what this decides.
3 (function (root) {
4 const GRAVITY = 9.8, START_X = -7.4, START_Z = .5, RADIUS = .2;
5 const MAX_SPEED = 10, MAX_PITCH = .96;
6 const SINK_SLOPE = .42; // steeper than this on touching the water and the stone sinks
7 const MIN_SPEED = 3; // slower than this along the water and it sinks
8 const BOUNCE_LIFT = .9, BOUNCE_DRAG = .03, SLOPE_DRAG = .3, MIN_HOP = .45;
9 const WATER_X = -6.24; // where the lake starts along the throw line; the page draws its shore here
10 const LAKE_END = 10; // no throw reaches this far, so the far bank is scenery
11
12 const unit = v => (Number.isFinite(v) ? Math.min(1, Math.max(0, v)) : 0);
13 function launch(power, pitch) {
14 const p = unit(power), a = unit(pitch / MAX_PITCH) * MAX_PITCH, v = 4 + p * (MAX_SPEED - 4);
15 return { x: START_X, z: START_Z, vx: v * Math.cos(a), vz: v * Math.sin(a), bounces: 0, state: 'air' };
16 }
17 // advance by dt seconds; returns 'bounce', 'sink' or 'land' (dropped on the sand) on the step it happens, otherwise ''
18 function step(s, dt) {
19 if (s.state !== 'air') return '';
20 s.vz -= GRAVITY * dt;
21 s.x += s.vx * dt; s.z += s.vz * dt;
outdated

Unreachable: the furthest any throw gets is x ≈ 8.8, and FAR_BANK is 12.4. Either tune the physics so a perfect throw clears the lake and test it, or remove the bank branch (here, plus the thud sound and the 'it clears the lake' text in index.html).

22 if (s.z > RADIUS || s.vz > 0) return '';

The first touch is treated as water wherever it lands. At power ≤ 0.1, flat throws touch down at x ≈ -6.3, which is on the sand (the shore at y=0 is ≈ -6.24). Fix it here, or raise the minimum release power in the page.

23 s.z = RADIUS;
24 if (s.x < WATER_X) { s.state = 'land'; return 'land'; }
25 const slope = -s.vz / s.vx, lift = -s.vz * Math.max(.3, BOUNCE_LIFT - slope * .8);
26 if (slope > SINK_SLOPE || s.vx < MIN_SPEED || lift < MIN_HOP) { s.state = 'sunk'; return 'sink'; }
27 s.vz = lift;
28 s.vx *= 1 - BOUNCE_DRAG - slope * SLOPE_DRAG;
29 s.bounces++;
30 return 'bounce';
31 }
outdated

The page doesn't call simulate; only the tests do. Fix the comment.

32 // fly a whole throw in fixed steps; the tests use this to sweep every power and angle
33 function simulate(power, pitch) {
34 const s = launch(power, pitch), events = [];
35 let reach = s.x;
36 for (let t = 0; t < 20 && s.state === 'air'; t += 1 / 240) {
37 const e = step(s, 1 / 240);
38 reach = Math.max(reach, s.x);
39 if (e) events.push({ e, x: s.x });
40 }
41 return { bounces: s.bounces, state: s.state, events, reach };
42 }
43 const api = { GRAVITY, START_X, START_Z, RADIUS, MAX_SPEED, MAX_PITCH, WATER_X, LAKE_END, launch, step, simulate };
44 if (typeof module !== 'undefined') module.exports = api; else root.StoneSkip = api;
45 })(typeof window !== 'undefined' ? window : globalThis);
stone-skip/skip.test.mjs added +49
@@ -0,0 +1,49 @@
1 import { test, expect } from 'bun:test';
2 import { simulate, launch, step, LAKE_END, MAX_PITCH } from './skip.js';
3
4 test('a flat fast throw skips several times', () => {
5 const r = simulate(1, .05);
6 expect(r.bounces).toBeGreaterThanOrEqual(5);
7 });
8
9 test('a flat fast throw skips more than a slower one', () => {
10 expect(simulate(1, .05).bounces).toBeGreaterThan(simulate(.45, .05).bounces);
11 });
12
13 test('too steep sinks on the first touch', () => {
14 const r = simulate(.9, .6);
15 expect(r.bounces).toBe(0);
16 expect(r.state).toBe('sunk');
17 });
18
19 test('too slow sinks on the first touch', () => {
20 const r = simulate(.2, .1);
21 expect(r.bounces).toBe(0);
22 expect(r.state).toBe('sunk');
23 });
24
25 test('inputs are clamped at the boundary', () => {
26 expect(launch(NaN, Infinity).vx).toBeGreaterThan(0);
27 expect(launch(5, -3).vx).toBeLessThanOrEqual(10);
28 expect(launch(-1, 0).vx).toBeGreaterThan(0);
29 });
30
31 test('a finished stone stays finished', () => {
32 const s = launch(.9, .6);
33 while (s.state === 'air') step(s, 1 / 240);
34 expect(step(s, 1 / 240)).toBe('');
35 });
36
37 test('the weakest throws drop on the sand, not into the water', () => {
38 for (const power of [0, .05, .1]) {
39 const r = simulate(power, 0);
40 expect(r.state).toBe('land');
41 expect(r.bounces).toBe(0);
42 }
43 });
44
45 test('no throw reaches the far bank', () => {
46 let reach = 0;
47 for (let p = 0; p <= 1; p += .05) for (let a = 0; a <= 1; a += .05) reach = Math.max(reach, simulate(p, a * MAX_PITCH).reach);
48 expect(reach).toBeLessThan(LAKE_END);
49 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs