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

Migrated from github.com/amirmushichge/pixel-plays

Add Free Throw: sink ten shots on a rooftop court by releasing at the top of the jump #29

Merged opened this

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

Merged

quill/pixel-plays:quill/19-add-free-throw-sink-ten-shots-on-a-rooft → main 2 commits fork 4 threads · 4 unresolved

  • Merged. quill/19-add-free-throw-sink-ten-shots-on-a-rooft was merged into main as 9363771.

Review

Sign in to review this change.
7 files changed +693 −0
README.md +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 | [Free Throw](free-throw/) | Ten shots on a rooftop court from five spots that step back from the hoop: hold to crouch and build power, release to jump, tap at the top of the jump to shoot; a swish scores 3, off the rim or backboard 2, and the fig leaves show the wind that nudges long shots (forged by the crew on the engine and shell above, not by the original creators) | Hold and release, tap to shoot; space |
2324 | [Pottery Wheel](pottery-wheel/) | Three pots on a kick wheel: hold to centre the clay without pressing too hard, then pull the wall up, too fast tears it and too slow slumps, and each pot has 40 seconds (clay still being centred then dries and is lost, a pull is fired as it stands); the score is the total height in pixels (forged by the crew on the engine and shell above, not by the original creators) | Hold to press, drag up to pull; space, up arrow, F to fire |
2425 | [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 |
2526
free-throw/index.html added +397
@@ -0,0 +1,397 @@
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>Free Throw</title>
7 <style>
8 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; --accent: #b4452f; }
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 #power { width: 72px; height: 4px; margin-top: 4px; background: rgba(180, 69, 47, .16); }
24 #power i { display: block; height: 100%; background: var(--accent); transform-origin: left; transform: scaleX(0); }
25 #status { color: var(--muted); }
26 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
27 button:hover, button:focus-visible { color: var(--ink); }
28 </style>
29 </head>
30 <body>
31 <div id="stage"><canvas id="c" tabindex="0" aria-label="Rooftop basketball court with one hoop. Hold to crouch and build power, release to jump, then tap again at the top of the jump to shoot. Keyboard: hold space, release, press space again."></canvas></div>
32 <div id="scores">
33 <div class="row"><b id="score">0</b><span>points</span><span class="dots" id="shots"></span></div>
34 <div class="row"><b id="left">10</b><span>shots left</span></div>
35 <div class="row"><b id="best">0</b><span>best</span></div>
36 <div class="row"><span>wind</span><span id="wind">calm</span></div>
37 <div id="power"><i></i></div>
38 </div>
39 <div class="hud" id="bottom">
40 <div id="status" role="status" aria-live="polite"></div>
41 <button id="mute" type="button" aria-pressed="false">sound on</button>
42 </div>
43 <script src="../shell.js"></script>
44 <script>
45 PixelPlays.mount({
46 id: 'free-throw',
47 rules: [
48 'Ten shots from five spots, stepping back from the hoop. A swish scores 3, off the rim or backboard 2, a miss 0.',
49 'Hold to crouch and build power, release to jump, then tap again at the very top of the jump to shoot. Keyboard: space.',
50 'Early or late falls short. The fig leaves show the wind, which nudges long shots.',
51 ],
52 });
53 </script>
54 <script>window.PP_SCENE = { originY: 12, shadowX: 1.3, shadowY: -.12 };</script>
55 <script src="../engine.js"></script>
56 <script src="shot.js"></script>
57 <script>
58 'use strict';
59
60 const FT = window.FreeThrow;
61 const HX = 2, BOARD_X = HX + FT.RIM_R + FT.BOARD_GAP, POLE_X = BOARD_X + .5, BODY_LEAD = .55;
62 const BASELINE_X = 3.6;
63 const FIG_X = -6.6, FIG_Y = 2.9;
64 const CLAY = [188, 112, 84], CONCRETE = [202, 196, 184], PAINT = [246, 238, 216];
65 const IRON = [96, 104, 116], GLASS = [214, 228, 236], RIM = [226, 84, 40], NETC = [244, 242, 234], POT = [190, 98, 66];
66 const BALL = [226, 112, 42], SEAM = rgb(78, 36, 22);
67 const PLAYER = { shirt: [74, 112, 172], stripe: [60, 96, 154], legs: [30, 38, 56], hair: [40, 28, 24], skin: [200, 142, 108] };
68 const clayTiles = [CLAY, [182, 106, 80]].map(rampOf), concreteRamp = rampOf(CONCRETE);
69 const FENCE_Y = -3.5;
70
71 function paintAt(x, y) {
72 const lane = Math.abs(Math.abs(y) - 1.9) < .07 && x > -7.4 && x < 3.3;
73 const base = Math.abs(x - 3.3) < .07 && Math.abs(y) < 2;
74 const spot = FT.SPOTS.some(d => { const r = Math.hypot(x - (HX - d), y); return r < .46 && r > .3; });
75 return lane || base || spot;
76 }
77 function groundColor(x, y, ix, iy) {
78 const edge = Math.pow(Math.pow(Math.abs(x + 1.5) / 8.4, 6) + Math.pow(Math.abs(y - .2) / 4.3, 6), 1 / 6);
79 const rough = edge + (noise(x * 1.3, y * 1.3) - .5) * .13;
80 if (rough > 1.04) return 0;
81 if (rough > .93 && hash(ix, iy) < (rough - .93) / .11) return 0;
82 if (paintAt(x, y)) return rgb(...PAINT);
83 const court = x > -8 && x < 3.8 && Math.abs(y) < 2.7;
84 const fine = hash(ix, iy);
85 if (court) {
86 const ramp = clayTiles[(Math.floor(x / 1.5) + Math.floor(y / 1.5)) & 1];
87 return ramp[clamp(Math.floor(2.4 + (noise(x * 2, y * 2) - .5) * 1.4 + (bayerAt(ix, iy) - .5) * .5), 1, 3)];
88 }
89 return concreteRamp[clamp(Math.floor(2.5 + (noise(x * 1.5, y * 1.5) - .5) * 1.5 + (fine - .5) * .5), 1, 3)];
90 }
91 // the chain-link fence: a lattice of wire plotted only where the diamonds are, so the white shows through
92 function fence(x0, x1, y, h) {
93 const wire = rgb(150, 158, 170);
94 for (let x = x0; x <= x1 + .01; x += (x1 - x0) / 5) box(x - .07, y - .07, 0, x + .07, y + .07, h + .1, IRON, 3);
95 for (let x = x0; x <= x1; x += .035) for (let z = .1; z <= h; z += .035) {
96 const a = (x + z) / .55, b = (x - z) / .55;
97 if (a - Math.floor(a) < .12 || b - Math.floor(b) < .12) plot(x, y, z, wire);
98 }
99 for (let x = x0; x <= x1; x += .035) { plot(x, y, h, rgb(...IRON)); plot(x, y, h + .05, rgb(...IRON)); }
100 }
101 function hoop() {
102 box(POLE_X - .12, -.12, 0, POLE_X + .12, .12, 3.7, IRON, 5);
103 box(BOARD_X + .02, -.07, 3.25, POLE_X, .07, 3.4, IRON, 6);
104 box(BOARD_X - .08, -.95, FT.RIM_Z - .1, BOARD_X, .95, FT.BOARD_TOP + .05, GLASS, 7);
105 for (let k = 0; k < 56; k++) {
106 const a = k / 56 * Math.PI * 2;
107 sphere(HX + Math.cos(a) * FT.RIM_R, Math.sin(a) * FT.RIM_R, FT.RIM_Z, .07, RIM, 'solid');
108 }
109 box(BOARD_X - .1, -.16, FT.RIM_Z + .05, BOARD_X, .16, FT.RIM_Z + .5, RIM, 8); // the red square on the glass
110 // the net: wire hanging from the rim and narrowing, drawn as a diagonal lattice
111 const net = rgb(...NETC);
112 for (let z = FT.RIM_Z; z > FT.RIM_Z - .85; z -= .03) {
113 const r = FT.RIM_R * (1 - (FT.RIM_Z - z) * .45);
114 for (let a = 0; a < Math.PI * 2; a += .02) {
115 const lat = a * 7 + (FT.RIM_Z - z) * 14;
116 if (lat - Math.floor(lat) < .25) plot(HX + Math.cos(a) * r, Math.sin(a) * r, z, net);
117 }
118 }
119 }
120 function pot() { box(FIG_X - .5, FIG_Y - .5, 0, FIG_X + .5, FIG_Y + .5, .75, POT, 9); box(FIG_X - .56, FIG_Y - .56, .75, FIG_X + .56, FIG_Y + .56, .9, [210, 124, 88], 10); }
121
122 function bake() {
123 zb.fill(-1e9);
124 pix.fill(rgb(255, 255, 255));
125 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
126 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy);
127 if (!c) continue;
128 pix[i] = c; ground[i] = 1;
129 zb[i] = (g.x + g.y) / R2 * COS;
130 }
131 groundZ.set(zb);
132 fence(-7.6, 3.4, FENCE_Y, 3.6);
133 growTree(FIG_X, FIG_Y, .62, 300, 5);
134 pot();
135 hoop();
136 castShadow(POLE_X, 0, 3.7, .3); castShadow(BOARD_X, 0, 4.2, .6);
137 bakeOcclusion();
138 staticShadow.set(shadowMask);
139 applyShadows(groundZ);
140 bakedPix.set(pix);
141 bakedZ.set(zb);
142 }
143
144 /* ---------- game state ---------- */
145 const BEST_KEY = 'free-throw-best';
146 function loadBest() { try { return Math.max(0, parseInt(localStorage.getItem(BEST_KEY), 10) || 0); } catch (e) { return 0; } }
147 function saveBest(v) { try { localStorage.setItem(BEST_KEY, String(v)); } catch (e) { /* private mode: the best lives for the session */ } }
148 const G = {
149 phase: 'ready', held: 0, power: 0, jumpT: 0, tapAt: null, flightT: 0, timer: 0, time: 0, seed: (Math.random() * 1e9) | 0,
150 shot: 0, at: FT.SPOTS[0], score: 0, best: loadBest(), wind: 0, result: null, ball: null, status: '', body: null,
151 };
152 const nodes = {
153 score: document.getElementById('score'), left: document.getElementById('left'), best: document.getElementById('best'),
154 shots: document.getElementById('shots'), wind: document.getElementById('wind'), status: document.getElementById('status'),
155 power: document.querySelector('#power i'),
156 };
157 function windWords(w) {
158 const a = Math.abs(w);
159 if (a < .15) return 'calm';
160 return (a < .55 ? 'light ' : 'strong ') + (w > 0 ? 'tailwind' : 'headwind');
161 }
162 function renderHud() {
163 nodes.score.textContent = G.score;
164 nodes.left.textContent = FT.SHOTS - G.shot;
165 nodes.best.textContent = G.best;
166 nodes.wind.textContent = windWords(G.wind);
167 if (nodes.shots.children.length !== FT.SHOTS) nodes.shots.innerHTML = '<i></i>'.repeat(FT.SHOTS);
168 [...nodes.shots.children].forEach((el, k) => el.classList.toggle('off', k < G.shot));
169 }
170 function setStatus(text) {
171 if (text === G.status) return;
172 G.status = text;
173 nodes.status.textContent = text;
174 }
175 function nextShot() {
176 G.phase = 'ready'; G.held = 0; G.power = 0; G.jumpT = 0; G.tapAt = null; G.result = null; G.ball = null; G.timer = 0;
177 G.wind = FT.windFor(G.seed, G.shot);
178 G.at = FT.SPOTS[FT.spotIndex(G.shot)];
179 const spot = FT.spotIndex(G.shot) + 1;
180 setStatus(`spot ${spot} of ${FT.SPOTS.length} · hold to crouch, release to jump, tap at the top`);
181 renderHud();
182 }
183 function resetGame() {
184 G.shot = 0; G.score = 0; G.seed = (Math.random() * 1e9) | 0;
185 nextShot();
186 }
187 function press() {
188 ensureAudio();
189 if (G.phase === 'done' && G.timer > .8) return resetGame();
190 if (G.phase === 'result' && G.timer > .5) return nextShot();
191 if (G.phase === 'jump') return shoot(G.jumpT);
192 if (G.phase !== 'ready') return;
193 G.phase = 'crouch'; G.held = 0;
194 setStatus('');
195 }
196 function release() {
197 if (G.phase !== 'crouch') return;
198 G.power = FT.powerFor(G.held);
199 G.phase = 'jump'; G.jumpT = 0;
200 sound('whoosh', G.power);
201 }
202 function shoot(tapAt) {
203 G.tapAt = tapAt === null ? null : Math.min(tapAt, FT.JUMP_TIME);
204 G.result = FT.fly({ power: G.power, tapAt: G.tapAt, distance: G.at, wind: G.wind });
205 G.phase = 'flight'; G.flightT = 0;
206 sound('whoosh', .3);
207 }
208 function land() {
209 const r = G.result;
210 G.ball = FT.settle(r);
211 G.score += r.points; G.shot++; G.phase = 'result'; G.timer = 0;
212 sound(r.outcome === 'swish' ? 'swish' : r.outcome === 'miss' ? 'thud' : 'clank');
213 const off = r.off;
214 const why = r.outcome === 'swish' ? 'swish' : r.outcome === 'rim' ? 'off the rim, it drops' : r.outcome === 'board' ? 'off the backboard, it drops'
215 : Math.abs(off) > .25 ? (off < 0 ? 'released early, short' : 'released late, short') : r.miss < 0 ? 'short' : 'long';
216 const last = G.shot >= FT.SHOTS;
217 let tail = ' · tap for the next shot';
218 if (last) {
219 const record = G.score > G.best;
220 if (record) { G.best = G.score; saveBest(G.best); sound('point'); }
221 tail = ` · ${G.score} of ${FT.SHOTS * 3}${record ? ', a new best' : ''} · tap to play again`;
222 G.phase = 'done';
223 }
224 setStatus(`${why} · +${r.points}${tail}`);
225 renderHud();
226 }
227
228 function update(dt) {
229 G.time += dt;
230 if (G.phase === 'crouch') G.held = Math.min(FT.POWER_TIME, G.held + dt);
231 if (G.phase === 'jump' || G.phase === 'flight' || G.phase === 'result' || G.phase === 'done') G.jumpT = Math.min(FT.JUMP_TIME, G.jumpT + dt);
232 if (G.phase === 'jump' && G.jumpT >= FT.JUMP_TIME) shoot(null);
233 else if (G.phase === 'flight') {
234 G.flightT += dt;
235 if (G.flightT >= G.result.t) land();
236 } else if (G.phase === 'result' || G.phase === 'done') {
237 G.timer += dt;
238 G.ball = FT.roll(G.ball, dt);
239 const edge = BASELINE_X - (HX - G.at) - FT.BALL_R; // a ball never rolls off the rooftop
240 if (G.ball.s > edge) G.ball = { ...G.ball, s: edge, vx: 0 };
241 }
242 nodes.power.style.transform = `scaleX(${G.phase === 'crouch' ? FT.powerFor(G.held) : G.phase === 'ready' ? 0 : G.power})`;
243 }
244
245 /* ---------- drawing ---------- */
246 function poseFor() {
247 const breathe = Math.sin(G.time * 1.8) * .012;
248 if (G.phase === 'crouch') {
249 const p = FT.powerFor(G.held);
250 return { crouch: .15 + p * .75, lean: .12 + p * .18, stance: .22, armR: 1.1 + p * .3, armL: 1.1 + p * .3 };
251 }
252 if (G.phase === 'jump' || G.phase === 'flight') {
253 const up = clamp(G.jumpT / (FT.JUMP_TIME / 2), 0, 1), follow = G.phase === 'flight' ? 1 : 0;
254 return { crouch: 0, lean: 0, stance: .16, z: FT.jumpRise(G.jumpT), armR: lerp(1.4, 2.85, ease(up)) + follow * .2, armL: lerp(1.4, 2.2, ease(up)) };
255 }
256 if (G.phase === 'result' || G.phase === 'done') return { crouch: .1 * (1 - clamp(G.jumpT / FT.JUMP_TIME, 0, 1)), lean: .05, stance: .18, z: FT.jumpRise(G.jumpT), armR: 2.5, armL: 1.2 };
257 return { crouch: breathe, lean: breathe, stance: .16, armR: .9, armL: .7 + breathe };
258 }
259 // the ball as a round sprite on whole pixels, banded so it reads at three pixels across
260 function drawBall(wx, wy, wz) {
261 const p = project(wx, wy, wz), cx = Math.round(p.sx), cy = Math.round(p.sy), ramp = rampOf(BALL);
262 for (let dy = -3; dy <= 3; dy++) for (let dx = -3; dx <= 3; dx++) {
263 const n = dx * dx + dy * dy;
264 if (n > 10) continue;
265 const ix = cx + dx, iy = cy + dy;
266 if (ix < 0 || iy < 0 || ix >= W || iy >= H) continue;
267 const i = iy * W + ix, d = p.d + Math.sqrt(Math.max(0, 10 - n)) * .06;
268 if (d <= zb[i]) continue;
269 zb[i] = d;
270 const l = clamp(2.6 - (dx + dy) * .32 + (n > 7 ? -.8 : 0), 1, 4);
271 pix[i] = (dx === 0 || dy === 0) && n > 0 && n < 10 ? SEAM : ramp[Math.floor(l)];
272 }
273 }
274 function ballWorld(figHand) {
275 const xs = HX - G.at;
276 if (G.phase === 'flight') {
277 const path = G.result.path, t = G.flightT;
278 let k = 1;
279 while (k < path.length - 1 && path[k][0] < t) k++;
280 const a = path[k - 1], b = path[k], f = b[0] > a[0] ? clamp((t - a[0]) / (b[0] - a[0]), 0, 1) : 1;
281 return [xs + lerp(a[1], b[1], f), 0, lerp(a[2], b[2], f)];
282 }
283 if (G.phase === 'result' || G.phase === 'done') return [xs + G.ball.s, 0, G.ball.z];
284 return [figHand[0] + .1, figHand[1] - .42, figHand[2] + .05];
285 }
286 // the fig leaves lean with the wind and tremble more in a stronger one; under reduced motion only the lean is left
287 function drawFigLeaves(t) {
288 const strength = Math.abs(G.wind), lean = G.wind * 1.7;
289 for (const leaf of leaves) {
290 const reach = clamp(leaf.z / 2.4, .3, 1);
291 const swayX = (Math.sin(t * .9 + leaf.x * .5 + leaf.z * .7) + .55 * Math.sin(t * 2.3 + leaf.k * 1.7)) * reach * (.35 + strength);
292 const dx = Math.round(swayX * .9 + lean * reach), dy = Math.round(Math.sin(t * 1.3 + leaf.y + leaf.k) * reach * .45 * (.35 + strength));
293 const px = leaf.pixels;
294 for (let n = 0; n < px.length; n += 4) {
295 const ix = px[n] + dx, iy = px[n + 1] + dy;
296 if (ix < 0 || iy < 0 || ix >= W || iy >= H) continue;
297 const i = iy * W + ix;
298 if (px[n + 2] <= zb[i]) continue;
299 zb[i] = px[n + 2];
300 pix[i] = px[n + 3];
301 }
302 if (leaf.k % 2 === 0) castShadow(leaf.x + swayX * .12, leaf.y, leaf.z, leaf.r);
303 }
304 }
305 function drawSpotRing() {
306 const xs = HX - G.at, pts = [];
307 for (let k = 0; k < 14; k++) {
308 const a = k / 14 * Math.PI * 2, p = project(xs + Math.cos(a) * .62, Math.sin(a) * .62, 0);
309 pts.push([p.sx, p.sy]);
310 }
311 drawDots(pts, SIGNAL);
312 }
313 function draw() {
314 pix.set(bakedPix);
315 zb.set(bakedZ);
316 pendingShadows.length = 0;
317 const xs = HX - G.at - BODY_LEAD;
318 const hand = figure(xs, -.35, 0, poseFor(), PLAYER, dynamicAdd);
319 const ball = ballWorld(hand);
320 castShadow(ball[0], ball[1], ball[2], .3);
321 const windT = STILL ? 0 : Math.floor(G.time * WIND_FPS) / WIND_FPS;
322 drawFigLeaves(windT);
323 flushShadows();
324 applyShadows(bakedZ);
325 shadeEdges();
326 if (G.phase === 'ready') drawSpotRing();
327 drawBall(ball[0], ball[1], ball[2]);
328 ctx.putImageData(image, 0, 0);
329 }
330
331 /* ---------- input ---------- */
332 canvas.addEventListener('pointerdown', e => {
333 canvas.focus({ preventScroll: true });
334 canvas.setPointerCapture(e.pointerId);
335 press();
336 });
337 canvas.addEventListener('pointerup', release);
338 canvas.addEventListener('pointercancel', release);
339 canvas.addEventListener('keydown', e => {
340 if (e.key !== ' ' && e.key !== 'Enter') return;
341 e.preventDefault();
342 if (e.repeat) return;
343 press();
344 });
345 canvas.addEventListener('keyup', e => {
346 if (e.key === ' ' || e.key === 'Enter') release();
347 });
348 canvas.addEventListener('blur', release);
349
350 /* ---------- sound ---------- */
351 let audio = null, muted = false;
352 function ensureAudio() {
353 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
354 const AC = window.AudioContext || window.webkitAudioContext;
355 if (AC) audio = new AC();
356 }
357 function sound(kind, n = 0) {
358 if (!audio || muted) return;
359 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
360 const spec = {
361 whoosh: [240 + n * 300, 520 + n * 500, .16, .05, 'triangle'],
362 swish: [900, 1500, .22, .06, 'triangle'],
363 clank: [320, 180, .12, .14, 'square'],
364 thud: [160, 60, .14, .18, 'sine'],
365 point: [660, 880, .16, .08, 'triangle'],
366 }[kind];
367 osc.type = spec[4];
368 osc.frequency.setValueAtTime(spec[0], now);
369 osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]);
370 gain.gain.setValueAtTime(spec[3], now);
371 gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]);
372 osc.connect(gain).connect(audio.destination);
373 osc.start(now); osc.stop(now + spec[2] + .01);
374 }
375 const muteButton = document.getElementById('mute');
376 muteButton.addEventListener('click', () => {
377 muted = !muted;
378 muteButton.textContent = muted ? 'sound off' : 'sound on';
379 muteButton.setAttribute('aria-pressed', String(muted));
380 });
381
382 /* ---------- fit and boot ---------- */
383 addEventListener('resize', fit);
384 fit();
385 bake();
386 nextShot();
387 let last = performance.now();
388 function frame(now) {
389 update(Math.min(.04, (now - last) / 1000));
390 last = now;
391 draw();
392 requestAnimationFrame(frame);
393 }
394 requestAnimationFrame(frame);
395 </script>
396 </body>
397 </html>
free-throw/shot.js added +116
@@ -0,0 +1,116 @@
1 'use strict';
2 // The rules of one free throw: plain numbers in, plain numbers out, no DOM. The page draws what this decides.
3 // Distances are in world units along the shot (s = 0 at the shooter's feet, the hoop centre at s = spot distance).
4 (function (root) {
5 const SHOTS = 10;
6 const SPOTS = [3.4, 4.6, 5.8, 7, 8.2]; // distance from the hoop centre, nearest first; two shots from each
7 const POWER_TIME = 2.4; // seconds of crouching for full power
8 const JUMP_TIME = .7; // the jump lasts this long, its top is at half
9 const JUMP_HEIGHT = .55;
10 const HAND_HEIGHT = 2.45; // the ball leaves the hands this high above the feet
11 const SPEED_MIN = 4.6, SPEED_MAX = 11;
12 const ANGLE = 52 * Math.PI / 180;
13 const TIMING_LOSS = .22; // fraction of the speed lost by releasing a whole half-jump from the top
14 const GRAVITY = 9.8;
15 const WIND_PUSH = .9; // sideways acceleration at full wind, positive helps the ball along
16 const BALL_R = .3, RIM_R = .62, RIM_Z = 3.05;
17 const BOARD_GAP = .28, BOARD_TOP = RIM_Z + 1.3; // the backboard stands this far behind the rim circle
18 const SWISH_R = RIM_R - BALL_R * .5; // a ball centred this close to the middle drops clean through
19 const BOARD_KEEP = .7; // share of its speed a ball keeps coming off the glass
20 const STEP = 1 / 240;
21
22 const unit = v => (Number.isFinite(v) ? Math.min(1, Math.max(0, v)) : 0);
23 const spotIndex = shot => Math.min(SPOTS.length - 1, Math.max(0, Math.floor((Number.isFinite(shot) ? shot : 0) / (SHOTS / SPOTS.length))));
24 const powerFor = held => unit(held / POWER_TIME);
25 // how far the feet are off the floor, t seconds after the jump began
26 function jumpRise(t) {
27 if (!Number.isFinite(t) || t <= 0 || t >= JUMP_TIME) return 0;
28 return JUMP_HEIGHT * 4 * (t / JUMP_TIME) * (1 - t / JUMP_TIME);
29 }
30 // how far a release came from the top of the jump: 0 at the top, -1 at take-off, 1 at landing. Never releasing is a late one
31 function timing(tapAt) {
32 if (tapAt === null || !Number.isFinite(tapAt) || tapAt >= JUMP_TIME) return 1;
33 return Math.max(-1, (Math.max(0, tapAt) - JUMP_TIME / 2) / (JUMP_TIME / 2));
34 }
35 // the wind of a shot, from -1 (against the ball) to 1 (behind it): fixed by the round's seed and the shot number
36 function windFor(seed, shot) {
37 let h = (Math.imul((seed | 0) ^ 0x9e3779b9, 2654435761) + Math.imul((shot | 0) + 1, 40503)) >>> 0;
38 h = Math.imul(h ^ h >>> 15, 2246822519) >>> 0;
39 h = Math.imul(h ^ h >>> 13, 3266489917) >>> 0;
40 const r = ((h ^ h >>> 16) >>> 0) / 4294967295;
41 return Math.round((r * 2 - 1) * 20) / 20;
42 }
43 // the ball's speed and height as it leaves the hands
44 function launch(power, tapAt) {
45 const off = timing(tapAt), rise = jumpRise(tapAt === null || !Number.isFinite(tapAt) ? JUMP_TIME : Math.min(tapAt, JUMP_TIME));
46 const speed = (SPEED_MIN + unit(power) * (SPEED_MAX - SPEED_MIN)) * (1 - TIMING_LOSS * Math.abs(off));
47 return { speed, z: HAND_HEIGHT + rise, off };
48 }
49 // fly one shot. shot = { power, tapAt, distance, wind }; returns the verdict and the path as [seconds, s, z] samples
50 function fly(shot, glass = true) {
51 const d = Number.isFinite(shot.distance) ? shot.distance : SPOTS[0];
52 const wind = Math.min(1, Math.max(-1, Number.isFinite(shot.wind) ? shot.wind : 0));
53 const l = launch(shot.power, shot.tapAt);
54 const board = d + RIM_R + BOARD_GAP;
55 let s = 0, z = l.z, vx = l.speed * Math.cos(ANGLE), vz = l.speed * Math.sin(ANGLE), t = 0, touched = '';
56 const path = [[0, s, z]];
57 for (let n = 0; n < 2400; n++) {
58 vx += wind * WIND_PUSH * STEP;
59 vz -= GRAVITY * STEP;
60 const pz = z, ps = s;
outdated

This catches every forward ball in the board's height band and turns it back at 45% speed, so it always drops near the rim. A full-power shot from any spot, in any wind, scores 2 here. A hard or high hit should miss.

61 s += vx * STEP; z += vz * STEP; t += STEP;
62 if (glass && ps + BALL_R < board && s + BALL_R >= board && vx > 0 && z > RIM_Z - .1 && z < BOARD_TOP) { // the backboard gives the ball back, softened
63 s = board - BALL_R; vx = -vx * BOARD_KEEP; touched = 'board';
64 }
65 if (n % 4 === 3) path.push([t, s, z]);
66 if (vz < 0 && pz >= RIM_Z && z < RIM_Z) {
67 const miss = Math.abs(s - d);
68 let outcome = 'miss';
outdated

Once touched is set, anything within RIM_R + BALL_R of the centre counts as an in-bank. With the rebound above it, that covers every overpowered shot. Score board only on a soft bank onto the rim.

69 if (miss <= SWISH_R) outcome = touched ? 'board' : 'swish';
70 else if (touched) outcome = miss <= RIM_R ? 'board' : 'miss'; // only a soft bank that drops onto the rim circle scores
71 else if (miss <= RIM_R + BALL_R) outcome = 'rim';
72 path.push([t, s, z]);
73 return { outcome, points: outcome === 'swish' ? 3 : outcome === 'miss' ? 0 : 2, miss: s - d, t, path, vx, vz, s, z, off: l.off };
74 }
75 if (z < BALL_R && vz < 0) break;
76 }
77 path.push([t, s, z]);
78 return { outcome: 'miss', points: 0, miss: s - d, t, path, vx, vz, s, z, off: l.off };
79 }
80 // a ball that has finished its flight carries on: in the hoop it drops through the net, otherwise it bounces and rolls.
81 // ball = { s, z, vx, vz, through }; returns the next ball, one step later
82 function roll(ball, dt) {
83 let { s, z, vx, vz } = ball;
84 vz -= GRAVITY * dt;
85 s += vx * dt; z += vz * dt;
86 if (z <= BALL_R) {
87 z = BALL_R;
88 if (Math.abs(vz) > 1.1) vz = -vz * .55; else vz = 0;
89 vx *= Math.max(0, 1 - 2.2 * dt);
90 if (!vz && Math.abs(vx) < .05) vx = 0;
91 }
92 return { s, z, vx, vz, through: ball.through };
93 }
94 // the ball as it is when it crosses the rim: through the net it falls straight down, off the rim it hops
95 function settle(result) {
96 const through = result.outcome === 'swish' || result.outcome === 'rim' || result.outcome === 'board';
97 if (result.outcome === 'swish') return { s: result.s, z: result.z, vx: 0, vz: -1, through };
98 if (through) return { s: result.s, z: result.z, vx: result.vx * .15, vz: -.5, through };
99 return { s: result.s, z: result.z, vx: result.vx * .6, vz: result.vz * .5, through };
outdated

The bisection needs the miss to grow with power, and the board breaks that. idealPower(3.4, 1) returns 1.000. Please add a test that the result sits strictly inside (0, 1) for every spot and wind.

100 }
101 // the power that carries a shot released at the top of the jump onto the hoop centre, found by bisection
102 function idealPower(distance, wind = 0) {
103 let lo = 0, hi = 1;
104 for (let k = 0; k < 40; k++) {
105 const mid = (lo + hi) / 2;
106 const r = fly({ power: mid, tapAt: JUMP_TIME / 2, distance, wind }, false); // no glass, so the miss only grows with power
107 if (r.miss < 0) lo = mid; else hi = mid;
108 }
109 return (lo + hi) / 2;
110 }
111 const api = {
112 SHOTS, SPOTS, POWER_TIME, JUMP_TIME, JUMP_HEIGHT, HAND_HEIGHT, ANGLE, BALL_R, RIM_R, RIM_Z, BOARD_GAP, BOARD_TOP,
113 spotIndex, powerFor, jumpRise, timing, windFor, launch, fly, roll, settle, idealPower,
114 };
115 if (typeof module !== 'undefined') module.exports = api; else root.FreeThrow = api;
116 })(typeof window !== 'undefined' ? window : globalThis);
free-throw/shot.test.mjs added +170
@@ -0,0 +1,170 @@
1 import { test, expect } from 'bun:test';
2 import T from './shot.js';
3
4 const TOP = T.JUMP_TIME / 2;
5 const far = T.SPOTS[T.SPOTS.length - 1];
6
7 test('the power follows the hold and is clamped', () => {
8 expect(T.powerFor(0)).toBe(0);
9 expect(T.powerFor(T.POWER_TIME / 2)).toBeCloseTo(.5);
10 expect(T.powerFor(99)).toBe(1);
11 expect(T.powerFor(NaN)).toBe(0);
12 });
13
14 test('two shots from each of five spots that step back from the hoop', () => {
15 expect(T.SHOTS).toBe(10);
16 expect(T.SPOTS.length).toBe(5);
17 expect([...T.SPOTS].sort((a, b) => a - b)).toEqual(T.SPOTS);
18 expect([0, 1, 2, 3, 8, 9].map(T.spotIndex)).toEqual([0, 0, 1, 1, 4, 4]);
19 });
20
21 test('the feet leave the floor and come back, highest at the middle of the jump', () => {
22 expect(T.jumpRise(0)).toBe(0);
23 expect(T.jumpRise(T.JUMP_TIME)).toBe(0);
24 expect(T.jumpRise(TOP)).toBeCloseTo(T.JUMP_HEIGHT);
25 expect(T.jumpRise(TOP)).toBeGreaterThan(T.jumpRise(TOP / 2));
26 });
27
28 test('timing is 0 at the top, negative before it, positive after, and no release is late', () => {
29 expect(T.timing(TOP)).toBe(0);
30 expect(T.timing(0)).toBe(-1);
31 expect(T.timing(TOP / 2)).toBeLessThan(0);
32 expect(T.timing(TOP * 1.5)).toBeGreaterThan(0);
33 expect(T.timing(null)).toBe(1);
34 expect(T.timing(NaN)).toBe(1);
35 });
36
37 test('a release at the top with the right power swishes from every spot, for 3', () => {
38 for (const distance of T.SPOTS) {
39 const r = T.fly({ power: T.idealPower(distance), tapAt: TOP, distance, wind: 0 });
40 expect(r.outcome).toBe('swish');
41 expect(r.points).toBe(3);
42 }
43 });
44
45 test('an early release falls short, and so does a late one', () => {
46 const power = T.idealPower(far);
47 for (const tapAt of [TOP * .4, TOP * 1.7, null]) {
48 const r = T.fly({ power, tapAt, distance: far, wind: 0 });
49 expect(r.outcome).toBe('miss');
50 expect(r.points).toBe(0);
51 expect(r.miss).toBeLessThan(-1);
52 }
53 });
54
55 test('the arc rises with power and the ball travels further', () => {
56 const at = power => T.fly({ power, tapAt: TOP, distance: far });
57 const apex = r => Math.max(...r.path.map(p => p[2]));
58 expect(apex(at(.6))).toBeGreaterThan(apex(at(.3)));
59 expect(at(.6).miss).toBeGreaterThan(at(.3).miss);
60 });
61
62 test('a shot just off the middle rattles in off the rim for 2', () => {
63 const distance = T.SPOTS[2], power = T.idealPower(distance);
64 let seen = null;
65 for (let k = 1; k < 60 && !seen; k++) {
66 const r = T.fly({ power: power + k * .004, tapAt: TOP, distance });
67 if (r.outcome === 'rim') seen = r;
68 }
69 expect(seen.points).toBe(2);
70 expect(Math.abs(seen.miss)).toBeGreaterThan(T.RIM_R - T.BALL_R * .5);
71 });
72
73 test('a soft bank off the backboard that drops onto the rim scores 2', () => {
outdated

This passes because every power above ideal banks in. Add the other side too: full power at the top of the jump misses (0 points) from the near spots.

74 const distance = T.SPOTS[2], power = T.idealPower(distance);
75 let seen = null;
76 for (let k = 1; k < 40 && !seen; k++) {
77 const r = T.fly({ power: power + k * .01, tapAt: TOP, distance });
78 if (r.outcome === 'board') seen = r;
79 }
80 expect(seen.points).toBe(2);
81 expect(Math.abs(seen.miss)).toBeLessThanOrEqual(T.RIM_R);
82 });
83
84 test('full power at the top of the jump misses from every spot in every wind', () => {
85 for (const wind of [-1, 0, 1]) for (const distance of T.SPOTS) {
86 const r = T.fly({ power: 1, tapAt: TOP, distance, wind });
87 expect(r.points).toBe(0);
88 }
89 expect(T.fly({ power: 1, tapAt: TOP, distance: T.SPOTS[0], wind: 0 }).points).toBe(0);
90 });
91
92 test('the scoring band of power is bounded on both sides at every spot and wind', () => {
93 for (const wind of [-1, 0, 1]) for (const distance of T.SPOTS) {
94 const scores = Array.from({ length: 101 }, (_, k) => T.fly({ power: k / 100, tapAt: TOP, distance, wind }).points > 0);
95 const first = scores.indexOf(true), last = scores.lastIndexOf(true);
96 expect(first).toBeGreaterThan(0);
97 expect(last).toBeLessThan(100);
98 expect(scores.slice(first, last + 1).every(Boolean)).toBe(true); // one unbroken band
99 }
100 });
101
102 test('the ideal power sits strictly inside 0 and 1 for every spot and wind', () => {
103 for (const wind of [-1, 0, 1]) for (const distance of T.SPOTS) {
104 const p = T.idealPower(distance, wind);
105 expect(p).toBeGreaterThan(0);
106 expect(p).toBeLessThan(1);
107 expect(T.fly({ power: p, tapAt: TOP, distance, wind }).outcome).toBe('swish');
108 }
109 });
110
111 test('a hard, high hit on the glass comes off long and misses', () => {
112 const r = T.fly({ power: 1, tapAt: TOP, distance: T.SPOTS[0] });
113 expect(r.outcome).toBe('miss');
114 });
115
116 test('a throw that falls well short misses for 0', () => {
117 const r = T.fly({ power: 0, tapAt: TOP, distance: far });
118 expect(r.outcome).toBe('miss');
119 expect(r.points).toBe(0);
120 });
121
122 test('the same shot scores differently against a headwind and with a tailwind', () => {
123 const shot = { power: T.idealPower(far), tapAt: TOP, distance: far };
124 const calm = T.fly({ ...shot, wind: 0 }), head = T.fly({ ...shot, wind: -1 }), tail = T.fly({ ...shot, wind: 1 });
125 expect(calm.points).toBe(3);
126 expect(head.points).toBeLessThan(calm.points);
127 expect(head.miss).toBeLessThan(calm.miss);
128 expect(tail.miss).toBeGreaterThan(calm.miss);
129 });
130
131 test('wind matters more the longer the shot', () => {
132 const drift = distance => {
133 const shot = { power: T.idealPower(distance), tapAt: TOP, distance };
134 return T.fly({ ...shot, wind: 1 }).miss - T.fly({ ...shot, wind: -1 }).miss;
135 };
136 expect(drift(far)).toBeGreaterThan(drift(T.SPOTS[0]));
137 });
138
139 test('the wind is fixed by the seed and shot, and stays between -1 and 1', () => {
140 expect(T.windFor(7, 3)).toBe(T.windFor(7, 3));
141 const winds = Array.from({ length: 40 }, (_, k) => T.windFor(k, k * 3));
142 for (const w of winds) { expect(w).toBeGreaterThanOrEqual(-1); expect(w).toBeLessThanOrEqual(1); }
143 expect(new Set(winds).size).toBeGreaterThan(10);
144 });
145
146 test('hostile numbers still give a verdict', () => {
147 const r = T.fly({ power: NaN, tapAt: NaN, distance: NaN, wind: Infinity });
148 expect(['swish', 'rim', 'board', 'miss']).toContain(r.outcome);
149 expect(Number.isFinite(r.miss)).toBe(true);
150 });
151
152 test('a ball that misses bounces and settles on the floor', () => {
153 const r = T.fly({ power: 0, tapAt: TOP, distance: far });
154 let ball = T.settle(r), bounces = 0, lastVz = ball.vz;
155 for (let k = 0; k < 60 * 20; k++) {
156 ball = T.roll(ball, 1 / 60);
157 if (lastVz < 0 && ball.vz > 0) bounces++;
158 lastVz = ball.vz;
159 }
160 expect(bounces).toBeGreaterThan(0);
161 expect(ball.z).toBeCloseTo(T.BALL_R);
162 expect(ball.vx).toBe(0);
163 });
164
165 test('a swish drops straight down through the net', () => {
166 const distance = far, r = T.fly({ power: T.idealPower(distance), tapAt: TOP, distance });
167 const ball = T.settle(r);
168 expect(ball.through).toBe(true);
169 expect(ball.vx).toBe(0);
170 });
index.html +1
@@ -36,6 +36,7 @@ footer a { display: inline; padding: 0; font-weight: inherit; text-decoration: u
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>
3838 <li><a href="pottery-wheel/">Pottery Wheel</a><span>Shape a pot on a kick wheel: hold to centre the clay without collapsing it, then pull the wall as tall as you can before it tears</span><span>Game forged by the crew</span></li>
39 <li><a href="free-throw/">Free Throw</a><span>Ten shots on a rooftop court: hold to crouch and build power, release to jump, then shoot at the top of the jump</span><span>Game forged by the crew</span></li>
3940 <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>
4041 </ul>
4142 <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>
serve.test.mjs +7
@@ -94,6 +94,13 @@ test('pottery wheel is served without a track', async () => {
9494 expect((await fetch(base + '/pottery-wheel/clay.js')).status).toBe(200);
9595 });
9696
97 test('free throw is served without a track', async () => {
98 const page = await fetch(base + '/free-throw/');
99 expect(page.status).toBe(200);
100 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
101 expect((await fetch(base + '/free-throw/shot.js')).status).toBe(200);
102 });
103
97104 test('a game folder without its slash redirects to it', async () => {
98105 const res = await fetch(base + '/balote', { redirect: 'manual' });
99106 expect(res.status).toBe(308);
shell.js +1
@@ -15,6 +15,7 @@ window.PixelPlays = (() => {
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 },
1717 { id: 'pottery-wheel', title: 'Pottery Wheel', blurb: 'Shape a pot on a kick wheel: hold to centre the clay without collapsing it, then pull the wall as tall as you can before it tears', music: false, forged: true },
18 { id: 'free-throw', title: 'Free Throw', blurb: 'Ten shots on a rooftop court: hold to crouch and build power, release to jump, then shoot at the top of the jump', music: false, forged: true },
1819 { 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 },
1920 ];
2021 const MUSIC_VOLUME = .4;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs