Public: anyone can read this; the crew can change it.
Migrated from github.com/amirmushichge/pixel-plays
Add Soapbox Derby: steer a wooden cart down a cobbled hill between the hay bales #80
Check · Review · Land · Live done — Landed and live in production.
quill/pixel-plays:quill/66-add-soapbox-derby-steer-a-wooden-cart-do → main 5 commits fork
10 files
changed +683
−1
README.md +2 −1
| @@ -40,6 +40,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am | ||
| 40 | 40 | | [](tram-line/) | A 120-second timetable over eight stops: hold to power, release to coast, brake so the front door lands on the yellow mark; within 0.5 m scores 3, within 2 m scores 1, overshooting the shelter scores 0 and strands the passengers, stopping between stops costs 1, and each second left at the last stop adds 1 (forged by the crew on the engine and shell above, not by the original creators) | Hold up or W (right half) to power, down or S (left half) to brake | |
| 41 | 41 | | [](espresso-bar/) | Twenty cups slide past under an espresso spout, each with a painted fill line and an order card (espresso a short line, latte a tall one): hold to pour, and the stream keeps falling for a quarter second after you let go; within 3% of the line scores 3, within 10% scores 1, over the brim spills and costs a life, and a cup that passes untouched costs a life; cups come faster as the round goes, three lives end it (forged by the crew on the engine and shell above, not by the original creators) | Hold space, or press and hold the canvas | |
| 42 | 42 | | [](goalkeeper/) | Ten penalties in a village football ground: each taker runs up and their hips and plant foot lean toward the side they will shoot (arms spread wide is down the middle), readable for a short tell window before the kick that shrinks with every penalty; tap the left third of the canvas to dive left, the right third to dive right and the middle third to stay up, and a dive to the right side before the ball arrives saves it, while diving before the tell window opens lets the taker switch side half the time; seven saves wins; the concept is the ordinary football penalty, with no particular game as its source (forged by the crew on the engine and shell above, not by the original creators) | Tap left, middle or right; Left and Right arrows dive, Up stays | |
| 43 | | [](soapbox-derby/) | A 360 m cobbled hill in a wooden cart that rolls and gathers speed by itself: steer between the gaps in gates of hay bales that narrow down the hill (the cart answers late, so steer early); a bale slows it hard and costs one of three lives, a smooth flagstone strip gives a short boost, and the banner scores your time against your best (forged by the crew on the engine and shell above, not by the original creators) | Drag left or right; left/right arrows | | |
| 43 | 44 | |
| 44 | 45 | ## Run |
| 45 | 46 | Requires [](https://nodejs.org/); nothing to install. |
| @@ -59,7 +60,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is | ||
| 59 | 60 | Every page carries Open Graph and Twitter tags (between `og:begin` and `og:end`), and `og/<id>.png` is a 1200x630 card: the game's own opening frame, scaled 2x on white; `og/home.png` is a grid of all of them. Because the games are static, `bun scripts/og.mjs` makes them without a browser: it runs each page's scripts in a `vm` against a stub DOM, captures the canvas pixels and writes the PNG (zlib only, no dependency) and the tags. Run it after adding a game or changing a scene; `serve.test.mjs` fails when a card or its tags are missing or stale. Scenes are rendered with a seeded `Math.random`, so the cards are byte-for-byte reproducible. Absolute URLs use `ORIGIN` at the top of the script (the forge production site), so change it there if the site moves. |
| 60 | 61 | |
| 61 | 62 | ## Add a game |
| 62 | 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 as a card with its `kind`, `input` and `accent`, searchable and filterable by kind (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too, with the same `data-kind`, `data-input`, `--accent` and tags line). Then run `bun scripts/og.mjs` to make its share card and tags. The page needs a `#mute` button. Put its background track at `<id>/<id>.mp3`, or set `music: false` on its `GAMES` entry when it has none (Stone Skip, Kite Hill, Paper Route, Harbour Crane, Pizza Toss, Sled Run, Pottery Wheel, Row Home, Orchard, Lighthouse, Market Scale, Window Washer, Domino Run, Campfire, Beekeeper, Bread Oven, Ice Fishing, Tightrope, Tram Line, Archery, Bell Tower, Espresso Bar, Goalkeeper, Wood Split and Signal Box 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`. | |
| 63 | 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 as a card with its `kind`, `input` and `accent`, searchable and filterable by kind (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too, with the same `data-kind`, `data-input`, `--accent` and tags line). Then run `bun scripts/og.mjs` to make its share card and tags. The page needs a `#mute` button. Put its background track at `<id>/<id>.mp3`, or set `music: false` on its `GAMES` entry when it has none (Stone Skip, Kite Hill, Paper Route, Harbour Crane, Pizza Toss, Sled Run, Pottery Wheel, Row Home, Orchard, Lighthouse, Market Scale, Window Washer, Domino Run, Campfire, Beekeeper, Bread Oven, Ice Fishing, Tightrope, Tram Line, Archery, Bell Tower, Espresso Bar, Goalkeeper, Wood Split, Signal Box and Soapbox Derby 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`. | |
| 63 | 64 | |
| 64 | 65 | - `shell.js` provides the game menu, the Rules popup, the credits and the background music. |
| 65 | 66 | - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals. |
index.html +1
| @@ -90,6 +90,7 @@ footer a::after { content: none; } | ||
| 90 | 90 | <li data-kind="Precision" data-input="Hold" style="--accent:#c9a227"><a href="tram-line/">Tram Line</a><span>Drive a tram along eight stops: brake so the door lands on the yellow mark, exact scores 3, overshoot scores nothing</span><span>Game forged by the crew</span><span class="tags">Precision · Hold</span></li> |
| 91 | 91 | <li data-kind="Precision" data-input="Hold" style="--accent:#6f4a33"><a href="espresso-bar/">Espresso Bar</a><span>Pour twenty coffees to the line as cups slide past: hold to pour, let go early, over the brim costs a life</span><span>Game forged by the crew</span><span class="tags">Precision · Hold</span></li> |
| 92 | 92 | <li data-kind="Sport" data-input="Tap" style="--accent:#3f7a3a"><a href="goalkeeper/">Goalkeeper</a><span>Read the taker and dive left or right to save ten penalties</span><span>Game forged by the crew</span><span class="tags">Sport · Tap</span></li> |
| 93 | <li data-kind="Racing" data-input="Drag" style="--accent:#b5562b"><a href="soapbox-derby/">Soapbox Derby</a><span>Steer a wooden cart down a cobbled hill between the hay bales, fastest time wins</span><span>Game forged by the crew</span><span class="tags">Racing · Drag</span></li> | |
| 93 | 94 | </ul> |
| 94 | 95 | <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.<br><a href="stats/">Most played</a></footer> |
| 95 | 96 | </main> |
og/home.png
Binary file not shown.
og/soapbox-derby.png added
Binary file not shown.
serve.test.mjs +7
| @@ -409,6 +409,13 @@ test('Tram Line and its rules script are served without a track', async () => { | ||
| 409 | 409 | expect((await fetch(base + '/tram-line/line.js')).status).toBe(200); |
| 410 | 410 | }); |
| 411 | 411 | |
| 412 | test('Soapbox Derby and its rules script are served without a track', async () => { | |
| 413 | const page = await fetch(base + '/soapbox-derby/'); | |
| 414 | expect(page.status).toBe(200); | |
| 415 | expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8'); | |
| 416 | expect((await fetch(base + '/soapbox-derby/cart.js')).status).toBe(200); | |
| 417 | }); | |
| 418 | ||
| 412 | 419 | test('Espresso Bar and its rules script are served without a track', async () => { |
| 413 | 420 | const page = await fetch(base + '/espresso-bar/'); |
| 414 | 421 | expect(page.status).toBe(200); |
shell.js +1
| @@ -34,6 +34,7 @@ window.PixelPlays = (() => { | ||
| 34 | 34 | { id: 'tram-line', title: 'Tram Line', blurb: 'Drive a tram along eight stops: brake so the door lands on the yellow mark, exact scores 3, overshoot scores nothing', kind: 'Precision', input: 'Hold', accent: '#c9a227', music: false, forged: true }, |
| 35 | 35 | { id: 'espresso-bar', title: 'Espresso Bar', blurb: 'Pour twenty coffees to the line as cups slide past: hold to pour, let go early, over the brim costs a life', kind: 'Precision', input: 'Hold', accent: '#6f4a33', music: false, forged: true }, |
| 36 | 36 | { id: 'goalkeeper', title: 'Goalkeeper', blurb: 'Read the taker and dive left or right to save ten penalties', kind: 'Sport', input: 'Tap', accent: '#3f7a3a', music: false, forged: true }, |
| 37 | { id: 'soapbox-derby', title: 'Soapbox Derby', blurb: 'Steer a wooden cart down a cobbled hill between the hay bales, fastest time wins', kind: 'Racing', input: 'Drag', accent: '#b5562b', music: false, forged: true }, | |
| 37 | 38 | ]; |
| 38 | 39 | const MUSIC_VOLUME = .4; |
| 39 | 40 | const CREDITS = [ |
soapbox-derby/cart.js added +100
| @@ -0,0 +1,100 @@ | ||
| 1 | 'use strict'; | |
| 2 | // The soapbox derby rules: a wooden cart rolling down a cobbled street, steered between gates of hay bales. | |
| 3 | // Metres and seconds; lane is metres across the street, positive to the player's right. Plain numbers in, plain | |
| 4 | // numbers out, no DOM. The page draws what this decides. | |
| 5 | (function (root) { | |
| 6 | const LENGTH = 360, ROAD_HALF = 3.6, CART_HALF = .5, LANE_MAX = ROAD_HALF - CART_HALF; // metres down the hill, and across | |
| 7 | const GRAVITY = 1.8, MAX_SPEED = 18; // m/s^2 the hill adds, and the speed it tops out at | |
| 8 | const STEER_LAG = .35; // seconds: the lane closes 63% of the gap to where you steer in this time | |
| 9 | const HIT_SLOW = .35, INVULN = 1, LIVES = 3; // a bale keeps 35% of the speed; the cart is clear of bales for 1 s after | |
| 10 | const GATE_FIRST = 40, GATE_GAP = 36, GATE_DEPTH = 1.2, CART_REACH = 1.4; // a gate is a row of bales GATE_DEPTH deep | |
| 11 | const GATE_WIDE = 3.4, GATE_NARROW = 1.7; // gap in metres at the top of the hill and at the banner | |
| 12 | const STRIP_FIRST = 58, STRIP_GAP = GATE_GAP, STRIP_LENGTH = 8, STRIP_HALF = 1.2; // flagstone strips between gates | |
| 13 | const BOOST_TIME = 1.5, BOOST_GRAVITY = 6, BOOST_CAP = 6; // while boosted: extra push, and a higher top speed | |
| 14 | const RESTART_AFTER = .6; | |
| 15 | ||
| 16 | const finite = v => (Number.isFinite(v) ? v : 0); | |
| 17 | const clamp = (v, a, b) => Math.max(a, Math.min(b, v)); | |
| 18 | const GATES = Math.floor((LENGTH - 30 - GATE_FIRST) / GATE_GAP) + 1; | |
| 19 | const STRIPS = GATES - 1; | |
| 20 | const isGate = n => Number.isInteger(n) && n >= 0 && n < GATES; | |
| 21 | const isStrip = n => Number.isInteger(n) && n >= 0 && n < STRIPS; | |
| 22 | // a repeatable number in [0, 1) for this seed and slot | |
| 23 | function noise(seed, n) { | |
| 24 | let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0; | |
| 25 | h = Math.imul(h ^ (h >>> 13), 1274126177); | |
| 26 | return ((h ^ (h >>> 16)) >>> 0) / 4294967296; | |
| 27 | } | |
| 28 | // how wide the gap in a gate is this far down the hill: it narrows in a straight line | |
| 29 | const gateWidth = d => GATE_WIDE + (GATE_NARROW - GATE_WIDE) * clamp(finite(d) / LENGTH, 0, 1); | |
| 30 | // gate n: where its row of bales starts, the middle of its gap and the gap's width; gaps swing left, then right | |
| 31 | function gateAt(n, seed = 0) { | |
| 32 | if (!isGate(n)) return null; | |
| 33 | const x = GATE_FIRST + n * GATE_GAP, width = gateWidth(x), reach = ROAD_HALF - width / 2 - .15; | |
| 34 | const side = n % 2 ? 1 : -1; | |
| 35 | return { index: n, x, width, centre: side * reach * (.45 + .55 * noise(seed, n)) }; | |
| 36 | } | |
| 37 | function stripAt(n, seed = 0) { | |
| 38 | if (!isStrip(n)) return null; | |
| 39 | return { index: n, x: STRIP_FIRST + n * STRIP_GAP, length: STRIP_LENGTH, half: STRIP_HALF, lane: (noise(seed, 100 + n) * 2 - 1) * (LANE_MAX - STRIP_HALF * .5) }; | |
| 40 | } | |
| 41 | ||
| 42 | function newRound(best = 0, seed = 0) { | |
| 43 | return { phase: 'play', outcome: '', time: 0, timer: 0, x: 0, v: 0, lane: 0, lives: LIVES, boost: 0, clear: 0, hits: 0, best: Math.max(0, finite(best)), record: false, seed: finite(seed) >>> 0 }; | |
| 44 | } | |
| 45 | const distanceLeft = s => Math.max(0, LENGTH - s.x); | |
| 46 | ||
| 47 | // does a cart at this distance and lane overlap a bale of gate n | |
| 48 | function hitsGate(x, lane, g) { | |
| 49 | if (!g || Math.abs(x - (g.x + GATE_DEPTH / 2)) >= GATE_DEPTH / 2 + CART_REACH) return false; | |
| 50 | return lane - CART_HALF < g.centre - g.width / 2 || lane + CART_HALF > g.centre + g.width / 2; | |
| 51 | } | |
| 52 | function finish(s, outcome, events) { | |
| 53 | s.phase = 'over'; s.outcome = outcome; s.timer = 0; | |
| 54 | if (outcome === 'won') { s.x = LENGTH; if (!s.best || s.time < s.best) { s.best = s.time; s.record = true; } } | |
| 55 | events.push({ type: outcome, time: s.time, lives: s.lives, record: s.record }); | |
| 56 | } | |
| 57 | // move the cart: steer is where you point it, -1 (full left) to 1 (full right) | |
| 58 | function advance(s, dt, input) { | |
| 59 | const events = []; | |
| 60 | dt = Math.max(0, Math.min(.1, finite(dt))); | |
| 61 | if (s.phase !== 'play') { s.timer += dt; return events; } | |
| 62 | s.time += dt; | |
| 63 | const steer = clamp(finite(input && input.steer), -1, 1); | |
| 64 | s.lane += (steer * LANE_MAX - s.lane) * (1 - Math.exp(-dt / STEER_LAG)); | |
| 65 | s.lane = clamp(s.lane, -LANE_MAX, LANE_MAX); | |
| 66 | const boosted = s.boost > 0, cap = MAX_SPEED + (boosted ? BOOST_CAP : 0); | |
| 67 | const before = s.x; | |
| 68 | s.v = Math.min(cap, s.v + (GRAVITY + (boosted ? BOOST_GRAVITY : 0)) * dt); | |
| 69 | if (s.v >= cap - 1e-9) s.v = cap; | |
| 70 | s.x += s.v * dt; | |
| 71 | s.boost = Math.max(0, s.boost - dt); s.clear = Math.max(0, s.clear - dt); | |
| 72 | for (let n = 0; n < STRIPS; n++) { | |
| 73 | const t = stripAt(n, s.seed); | |
| 74 | if (s.x >= t.x && before <= t.x + t.length && Math.abs(s.lane - t.lane) < t.half + CART_HALF * .5) { | |
| 75 | if (s.boost <= 0) events.push({ type: 'boost', strip: n }); | |
| 76 | s.boost = BOOST_TIME; | |
| 77 | } | |
| 78 | } | |
| 79 | if (s.clear <= 0) for (let n = 0; n < GATES; n++) { | |
| 80 | if (!hitsGate(s.x, s.lane, gateAt(n, s.seed))) continue; | |
| 81 | s.v *= HIT_SLOW; s.lives--; s.hits++; s.clear = INVULN; s.boost = 0; | |
| 82 | events.push({ type: 'hit', gate: n, lives: s.lives }); | |
| 83 | break; | |
| 84 | } | |
| 85 | if (s.lives <= 0) finish(s, 'lost', events); | |
| 86 | else if (s.x >= LENGTH) finish(s, 'won', events); | |
| 87 | return events; | |
| 88 | } | |
| 89 | // a tap after the run has been over for a moment starts the next one; otherwise null | |
| 90 | function again(s) { | |
| 91 | return s.phase === 'over' && s.timer > RESTART_AFTER ? newRound(s.best, s.seed + 1) : null; | |
| 92 | } | |
| 93 | ||
| 94 | const api = { | |
| 95 | LENGTH, ROAD_HALF, CART_HALF, LANE_MAX, GRAVITY, MAX_SPEED, STEER_LAG, HIT_SLOW, INVULN, LIVES, GATE_FIRST, GATE_GAP, GATE_DEPTH, GATES, STRIPS, | |
| 96 | GATE_WIDE, GATE_NARROW, STRIP_LENGTH, STRIP_HALF, BOOST_TIME, BOOST_GRAVITY, BOOST_CAP, RESTART_AFTER, | |
| 97 | gateWidth, gateAt, stripAt, hitsGate, newRound, distanceLeft, advance, again, | |
| 98 | }; | |
| 99 | if (typeof module !== 'undefined') module.exports = api; else root.Cart = api; | |
| 100 | })(typeof window !== 'undefined' ? window : globalThis); |
soapbox-derby/cart.test.mjs added +156
| @@ -0,0 +1,156 @@ | ||
| 1 | import { test, expect } from 'bun:test'; | |
| 2 | import { LENGTH, LANE_MAX, MAX_SPEED, STEER_LAG, HIT_SLOW, INVULN, LIVES, BOOST_TIME, GATE_WIDE, GATE_NARROW, GATES, STRIPS, gateWidth, gateAt, stripAt, hitsGate, newRound, distanceLeft, advance, again } from './cart.js'; | |
| 3 | ||
| 4 | const run = (s, seconds, input = {}) => { const out = []; for (let t = 0; t < seconds - 1e-9; t += 1 / 60) out.push(...advance(s, 1 / 60, input)); return out; }; | |
| 5 | // a cart placed square in the gap of gate n, just before its bales | |
| 6 | const atGate = (n, seed = 0) => { const s = newRound(0, seed), g = gateAt(n, seed); s.x = g.x - 1.3; s.v = 8; s.lane = g.centre; return [s, g]; }; | |
| 7 | ||
| 8 | test('the cart gathers speed on its own, up to a top speed', () => { | |
| 9 | const s = newRound(); | |
| 10 | run(s, 1); | |
| 11 | expect(s.v).toBeGreaterThan(1); | |
| 12 | const v = s.v; | |
| 13 | run(s, 2); | |
| 14 | expect(s.v).toBeGreaterThan(v); | |
| 15 | const t = newRound(); | |
| 16 | t.x = 1; t.v = MAX_SPEED - .05; | |
| 17 | run(t, 1); | |
| 18 | expect(t.v).toBe(MAX_SPEED); | |
| 19 | }); | |
| 20 | ||
| 21 | test('steering reaches the target lane only after the lag', () => { | |
| 22 | const s = newRound(); | |
| 23 | run(s, .1, { steer: 1 }); | |
| 24 | expect(s.lane).toBeGreaterThan(0); | |
| 25 | expect(s.lane).toBeLessThan(LANE_MAX * .3); | |
| 26 | run(s, STEER_LAG - .1, { steer: 1 }); | |
| 27 | expect(s.lane).toBeLessThan(LANE_MAX * .7); | |
| 28 | run(s, STEER_LAG * 6, { steer: 1 }); | |
| 29 | expect(s.lane).toBeGreaterThan(LANE_MAX * .99); | |
| 30 | expect(s.lane).toBeLessThanOrEqual(LANE_MAX); | |
| 31 | }); | |
| 32 | ||
| 33 | test('steering left goes negative and out-of-range or junk input is held in range', () => { | |
| 34 | const s = newRound(); | |
| 35 | run(s, 3, { steer: -9 }); | |
| 36 | expect(s.lane).toBeLessThan(0); | |
| 37 | expect(s.lane).toBeGreaterThanOrEqual(-LANE_MAX); | |
| 38 | run(s, .5, { steer: NaN }); | |
| 39 | expect(Number.isFinite(s.lane)).toBe(true); | |
| 40 | }); | |
| 41 | ||
| 42 | test('a bale hit slows the cart hard and costs a life, once', () => { | |
| 43 | const [s, g] = atGate(0); | |
| 44 | s.lane = g.centre + g.width; // well inside the bales | |
| 45 | const v = s.v; | |
| 46 | const events = run(s, 1 / 30); | |
| 47 | expect(events.filter(e => e.type === 'hit').length).toBe(1); | |
| 48 | expect(s.lives).toBe(LIVES - 1); | |
| 49 | expect(s.v).toBeLessThan(v * HIT_SLOW + 1); | |
| 50 | run(s, .3, { steer: 1 }); | |
| 51 | expect(s.lives).toBe(LIVES - 1); // the same bale does not cost twice | |
| 52 | }); | |
| 53 | ||
| 54 | test('passing through the gap costs nothing', () => { | |
| 55 | const [s, g] = atGate(2); | |
| 56 | run(s, 1, { steer: g.centre / LANE_MAX }); | |
| 57 | expect(s.lives).toBe(LIVES); | |
| 58 | }); | |
| 59 | ||
| 60 | test('a hit can land again after the clear period', () => { | |
| 61 | const [s, g] = atGate(0); | |
| 62 | s.lane = g.centre + g.width; | |
| 63 | run(s, 1 / 30); | |
| 64 | expect(s.lives).toBe(LIVES - 1); | |
| 65 | const h = gateAt(1); | |
| 66 | s.x = h.x - 1; s.lane = h.centre + h.width; s.clear = 0; | |
| 67 | run(s, 1 / 30); | |
| 68 | expect(s.lives).toBe(LIVES - 2); | |
| 69 | expect(INVULN).toBeGreaterThan(0); | |
| 70 | }); | |
| 71 | ||
| 72 | test('a boost strip raises speed for the stated time', () => { | |
| 73 | const t = stripAt(0); | |
| 74 | const on = newRound(), off = newRound(); | |
| 75 | for (const s of [on, off]) { s.x = t.x - 1; s.v = 6; } | |
| 76 | on.lane = t.lane; off.lane = t.lane > 0 ? t.lane - 3 : t.lane + 3; | |
| 77 | const events = run(on, .3); run(off, .3); | |
| 78 | expect(events.some(e => e.type === 'boost')).toBe(true); | |
| 79 | expect(on.boost).toBeGreaterThan(0); | |
| 80 | expect(on.v).toBeGreaterThan(off.v + .5); | |
| 81 | run(on, BOOST_TIME + .1); | |
| 82 | expect(on.boost).toBe(0); | |
| 83 | // the boost lifts the top speed too, then it settles back | |
| 84 | run(on, 3); | |
| 85 | expect(on.v).toBeLessThanOrEqual(MAX_SPEED); | |
| 86 | }); | |
| 87 | ||
| 88 | test('gates narrow with distance down the hill', () => { | |
| 89 | expect(gateWidth(0)).toBe(GATE_WIDE); | |
| 90 | expect(gateWidth(LENGTH)).toBe(GATE_NARROW); | |
| 91 | expect(gateWidth(LENGTH * 3)).toBe(GATE_NARROW); | |
| 92 | let w = Infinity; | |
| 93 | for (let n = 0; n < GATES; n++) { const g = gateAt(n, 5); expect(g.width).toBeLessThan(w); w = g.width; } | |
| 94 | expect(gateAt(GATES)).toBeNull(); | |
| 95 | }); | |
| 96 | ||
| 97 | test('every gap fits inside the street and every gate is beatable with the lag', () => { | |
| 98 | for (let seed = 0; seed < 30; seed++) for (let n = 0; n < GATES; n++) { | |
| 99 | const g = gateAt(n, seed); | |
| 100 | expect(g.centre - g.width / 2).toBeGreaterThanOrEqual(-3.6); | |
| 101 | expect(g.centre + g.width / 2).toBeLessThanOrEqual(3.6); | |
| 102 | expect(g.width).toBeGreaterThan(1.2); | |
| 103 | expect(hitsGate(g.x, g.centre, g)).toBe(false); | |
| 104 | expect(hitsGate(g.x, g.centre + g.width, g)).toBe(true); | |
| 105 | } | |
| 106 | expect(stripAt(STRIPS)).toBeNull(); | |
| 107 | }); | |
| 108 | ||
| 109 | test('reaching the banner ends the run with the time and a best', () => { | |
| 110 | const s = newRound(0, 3); | |
| 111 | let events = []; | |
| 112 | for (let n = 0; n < 6000 && s.phase === 'play'; n++) { | |
| 113 | // steer for the middle of the next gap | |
| 114 | const g = [...Array(GATES).keys()].map(i => gateAt(i, 3)).find(g => g.x + 3 > s.x); | |
| 115 | events = advance(s, 1 / 60, { steer: g ? Math.max(-1, Math.min(1, (g.x - s.x < 14 ? g.centre : 0) / LANE_MAX)) : 0 }); | |
| 116 | } | |
| 117 | expect(s.phase).toBe('over'); | |
| 118 | expect(s.outcome).toBe('won'); | |
| 119 | expect(s.lives).toBeGreaterThan(0); | |
| 120 | expect(s.time).toBeGreaterThan(15); | |
| 121 | expect(s.time).toBeLessThan(40); | |
| 122 | expect(distanceLeft(s)).toBe(0); | |
| 123 | expect(s.record).toBe(true); | |
| 124 | expect(s.best).toBe(s.time); | |
| 125 | expect(events.some(e => e.type === 'won')).toBe(true); | |
| 126 | }); | |
| 127 | ||
| 128 | test('the third bale ends the run', () => { | |
| 129 | const [t, g] = atGate(0); | |
| 130 | t.lives = 1; t.lane = g.centre + g.width; | |
| 131 | const events = run(t, 1 / 30); | |
| 132 | expect(t.lives).toBe(0); | |
| 133 | expect(t.phase).toBe('over'); | |
| 134 | expect(t.outcome).toBe('lost'); | |
| 135 | expect(events.some(e => e.type === 'lost')).toBe(true); | |
| 136 | expect(t.record).toBe(false); | |
| 137 | const x = t.x; | |
| 138 | run(t, 1); | |
| 139 | expect(t.x).toBe(x); | |
| 140 | }); | |
| 141 | ||
| 142 | test('a slower win does not replace a better time, and a tap restarts after a moment', () => { | |
| 143 | const s = newRound(20, 1); | |
| 144 | s.x = LENGTH - .1; s.v = 10; s.time = 30; | |
| 145 | run(s, .1); | |
| 146 | expect(s.outcome).toBe('won'); | |
| 147 | expect(s.best).toBe(20); | |
| 148 | expect(s.record).toBe(false); | |
| 149 | expect(again(s)).toBeNull(); | |
| 150 | run(s, 1); | |
| 151 | const next = again(s); | |
| 152 | expect(next.phase).toBe('play'); | |
| 153 | expect(next.best).toBe(20); | |
| 154 | expect(next.lives).toBe(LIVES); | |
| 155 | expect(again(next)).toBeNull(); | |
| 156 | }); |
soapbox-derby/index.html added +387
| @@ -0,0 +1,387 @@ | ||
| 1 | ||
| 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>Soapbox Derby</title> | |
| 7 | <!-- og:begin --> | |
| 8 | <meta name="description" content="Steer a wooden cart down a cobbled hill between the hay bales, fastest time wins"> | |
| 9 | <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/soapbox-derby/"> | |
| 10 | <meta property="og:type" content="website"> | |
| 11 | <meta property="og:site_name" content="Pixel Plays"> | |
| 12 | <meta property="og:title" content="Soapbox Derby"> | |
| 13 | <meta property="og:description" content="Steer a wooden cart down a cobbled hill between the hay bales, fastest time wins"> | |
| 14 | <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/soapbox-derby/"> | |
| 15 | <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/soapbox-derby.png"> | |
| 16 | <meta property="og:image:type" content="image/png"> | |
| 17 | <meta property="og:image:width" content="1200"> | |
| 18 | <meta property="og:image:height" content="630"> | |
| 19 | <meta property="og:image:alt" content="Soapbox Derby: the opening scene of the game"> | |
| 20 | <meta name="twitter:card" content="summary_large_image"> | |
| 21 | <!-- og:end --> | |
| 22 | <style> | |
| 23 | :root { : #1c1b19; : #8b877f; : #fff; : #b5562b; } | |
| 24 | * { box-sizing: border-box; } | |
| 25 | html, body { height: 100%; margin: 0; background: var(); color: var(); } | |
| 26 | body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; } | |
| 27 | #stage { position: fixed; inset: 0; display: grid; place-items: center; } | |
| 28 | canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; outline: none; } | |
| 29 | .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; } | |
| 30 | #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; } | |
| 31 | #bottom { bottom: max(14px, env(safe-area-inset-bottom)); align-items: flex-end; } | |
| 32 | .row { display: flex; align-items: center; gap: 8px; color: var(); } | |
| 33 | .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; } | |
| 34 | .row span { color: var(); } | |
| 35 | #status { color: var(); min-height: 1.35em; } | |
| 36 | button { pointer-events: auto; font: inherit; color: var(); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; } | |
| 37 | button:hover, button:focus-visible { color: var(); } | |
| 38 | </style> | |
| 39 | </head> | |
| 40 | <body> | |
| 41 | <div id="stage"><canvas id="c" tabindex="0" aria-label="A wooden cart rolling down a cobbled village street between hay bales, towards a chequered finish banner. It speeds up by itself. Drag left or right on the canvas, or press the left and right arrow keys, to steer; the cart answers a moment late, so steer early. Aim for the gap in each gate of bales: a bale slows the cart and costs one of three lives, a smooth flagstone strip gives a short speed boost, and the gaps narrow down the hill. Reach the banner as fast as you can."></canvas></div> | |
| 42 | <div id="scores"> | |
| 43 | <div class="row"><b id="time">0.0</b><span>seconds</span></div> | |
| 44 | <div class="row"><b id="left">360</b><span>metres to go</span></div> | |
| 45 | <div class="row"><b id="lives">3</b><span>lives</span></div> | |
| 46 | <div class="row"><b id="best">none</b><span>best time</span></div> | |
| 47 | </div> | |
| 48 | <div class="hud" id="bottom"> | |
| 49 | <div id="status" role="status" aria-live="polite"></div> | |
| 50 | <button id="mute" type="button" aria-pressed="false">sound on</button> | |
| 51 | </div> | |
| 52 | <script src="../shell.js"></script> | |
| 53 | <script> | |
| 54 | PixelPlays.mount({ | |
| 55 | id: 'soapbox-derby', | |
| 56 | rules: [ | |
| 57 | 'Drag left or right (or use the arrow keys) to steer; the cart answers late, so steer early.', | |
| 58 | 'Aim for the gap in each gate of bales: a bale slows you hard and costs a life, three end the run.', | |
| 59 | 'Flagstone strips give a short boost. Reach the banner, 360 m down, in the fastest time.', | |
| 60 | ], | |
| 61 | }); | |
| 62 | </script> | |
| 63 | <script>window.PP_SCENE = { originY: 0, shadowX: 1.3, shadowY: -.12 };</script> | |
| 64 | <script src="../engine.js"></script> | |
| 65 | <script src="cart.js"></script> | |
| 66 | <script> | |
| 67 | 'use strict'; | |
| 68 | ||
| 69 | const STEP = Math.SQRT2 / 5; // one camera step moves the street exactly 2px right and 1px down | |
| 70 | const CELL = STEP * 2, PHASES = 8; // the cobbles repeat every 8 steps, so 8 baked frames of ground scroll it without a seam | |
| 71 | const LEAD_STEPS = 24; // the cart sits 24 steps left of the screen centre so the gates show from far ahead | |
| 72 | const BEST_KEY = 'pixel-plays-soapbox-derby-best'; | |
| 73 | const KERB_Y = 3.6, VERGE_Y = 4.05, KERB_BALE = 4.55, KERB_SPACE = 6; // the street, its kerb stones, the grass verge, and a kerb bale every 6 steps | |
| 74 | const WOOD = [168, 112, 62], WOOD_DARK = [112, 74, 44], HAY = [214, 176, 72], HAY_DARK = [186, 146, 52], STRAP = [120, 84, 44]; | |
| 75 | const STEEL = [96, 100, 112], DARK = [52, 52, 60], RED = [186, 64, 52], CREAM = [236, 226, 200]; | |
| 76 | const FLAG_A = rgb(206, 204, 212), FLAG_B = rgb(190, 188, 200), FLAG_JOINT = rgb(150, 148, 160); | |
| 77 | const BLACK = rgb(34, 32, 40), WHITE = rgb(246, 244, 238); | |
| 78 | const FLAGS = [[200, 76, 64], [236, 196, 70], [74, 122, 170], [226, 226, 214], [96, 150, 104]]; | |
| 79 | ||
| 80 | /* ---------- state ---------- */ | |
| 81 | const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })(); | |
| 82 | let R = Cart.newRound(best0, Date.now() & 0xffff); | |
| 83 | const G = { time: 0, status: '', noteUntil: 0, steer: 0 }; | |
| 84 | const nodes = {}; | |
| 85 | for (const id of ['time', 'left', 'lives', 'best', 'status']) nodes[id] = document.getElementById(id); | |
| 86 | function renderHud() { | |
| 87 | nodes.time.textContent = R.time.toFixed(1); | |
| 88 | nodes.left.textContent = Math.ceil(Cart.distanceLeft(R)); | |
| 89 | nodes.lives.textContent = R.lives; | |
| 90 | nodes.best.textContent = R.best ? R.best.toFixed(1) + ' s' : 'none'; | |
| 91 | } | |
| 92 | function setStatus(text) { | |
| 93 | if (text === G.status) return; | |
| 94 | G.status = text; | |
| 95 | nodes.status.textContent = text; | |
| 96 | } | |
| 97 | function note(text) { setStatus(text); G.noteUntil = G.time + 2.2; } | |
| 98 | const HINT = 'drag or arrow keys to steer · steer early, the cart is slow to turn'; | |
| 99 | ||
| 100 | /* ---------- baked ground: the street at each of its eight scroll phases ---------- */ | |
| 101 | const mod = (a, n) => ((a % n) + n) % n; | |
| 102 | const phases = []; | |
| 103 | const baseZ = new Float32Array(W * H).fill(-1e9); | |
| 104 | const ROAD_EDGE = 4.9; | |
| 105 | function streetColor(xw, y) { | |
| 106 | const a = Math.abs(y); | |
| 107 | if (a > VERGE_Y) { const t = .9 + hash(Math.floor(xw / STEP), Math.floor(y * 4)) * .2; return rgb(150 * t, 150 * t, 84 * t); } | |
| 108 | if (a > KERB_Y) { | |
| 109 | const sx = mod(xw, STEP * 4) / (STEP * 4); | |
| 110 | return rgb(...(sx < .06 ? [186, 180, 168] : [222, 216, 202])); | |
| 111 | } | |
| 112 | const row = Math.floor((y + 9) / .5), u = xw / CELL + (row & 1) * .5, col = Math.floor(u); | |
| 113 | const fu = u - col, fv = (y + 9) / .5 - row; | |
| 114 | if (fu < .1 || fv < .12) return rgb(112, 106, 104); | |
| 115 | const t = .84 + hash(mod(col, 4), row) * .24; | |
| 116 | return rgb(168 * t, 160 * t, 152 * t); | |
| 117 | } | |
| 118 | function bakeGround() { | |
| 119 | const member = new Uint8Array(W * H); | |
| 120 | for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) { | |
| 121 | const g = unproject(ix + .5, iy + .5), i = iy * W + ix; | |
| 122 | const e = Math.abs(g.y) / ROAD_EDGE + (hash(ix, iy) - .5) * .1; | |
| 123 | if (e > 1.04 || (e > .94 && hash(iy, ix) < (e - .94) / .1)) continue; | |
| 124 | member[i] = 1; ground[i] = 1; | |
| 125 | baseZ[i] = (g.x + g.y) / R2 * COS; | |
| 126 | } | |
| 127 | groundZ.set(baseZ); | |
| 128 | for (let k = 0; k < PHASES; k++) { | |
| 129 | const buf = new Uint32Array(W * H).fill(rgb(255, 255, 255)); | |
| 130 | for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) { | |
| 131 | const i = iy * W + ix; | |
| 132 | if (!member[i]) continue; | |
| 133 | const g = unproject(ix + .5, iy + .5); | |
| 134 | buf[i] = streetColor(g.x + k * STEP, g.y); | |
| 135 | } | |
| 136 | phases.push(buf); | |
| 137 | } | |
| 138 | } | |
| 139 | ||
| 140 | /* ---------- scenery drawn once, then slid along the street in whole pixels ---------- */ | |
| 141 | // paint flat colour on the street without touching depth, so shadows and edges ignore it | |
| 142 | function paint(x0, x1, y0, y1, colorAt) { | |
| 143 | for (let x = x0; x <= x1; x += .06) for (let y = y0; y <= y1; y += .06) { | |
| 144 | const p = project(x, y, 0), ix = p.sx | 0, iy = p.sy | 0; | |
| 145 | if (ix >= 0 && iy >= 0 && ix < W && iy < H && ground[iy * W + ix]) pix[iy * W + ix] = colorAt(x, y); | |
| 146 | } | |
| 147 | } | |
| 148 | const flagstone = (x, y) => { | |
| 149 | const u = mod(x, 1.2) / 1.2, v = mod(y + (Math.floor(x / 1.2) & 1) * .5, 1) / 1; | |
| 150 | return u < .05 || v < .06 ? FLAG_JOINT : (Math.floor(x / 1.2) + Math.floor(y + (Math.floor(x / 1.2) & 1) * .5)) & 1 ? FLAG_A : FLAG_B; | |
| 151 | }; | |
| 152 | const chequer = (x, y) => ((Math.floor(x / .5) + Math.floor((y + 9) / .5)) & 1 ? BLACK : WHITE); | |
| 153 | function strips(cam) { | |
| 154 | for (let n = 0; n < Cart.STRIPS; n++) { | |
| 155 | const t = Cart.stripAt(n, R.seed), m = t.x - cam; | |
| 156 | if (m > 36 || m + t.length < -16) continue; | |
| 157 | paint(m, m + t.length, -t.lane - t.half, -t.lane + t.half, flagstone); | |
| 158 | } | |
| 159 | } | |
| 160 | function finishLine(cam) { | |
| 161 | const m = Cart.LENGTH - cam; | |
| 162 | if (m < 36 && m > -16) paint(m, m + 1, -Cart.ROAD_HALF, Cart.ROAD_HALF, chequer); | |
| 163 | } | |
| 164 | function bale(x, y0, y1, depth, seed, height = .95) { | |
| 165 | box(x, y0, 0, x + depth, y1, height, HAY, seed); | |
| 166 | box(x + depth * .3, y0 - .02, 0, x + depth * .4, y1 + .02, height * .98, STRAP, seed + 1); | |
| 167 | box(x + depth * .7, y0 - .02, 0, x + depth * .8, y1 + .02, height * .98, STRAP, seed + 2); | |
| 168 | castShadow(x + depth / 2, (y0 + y1) / 2, height, Math.max(.5, (y1 - y0) / 2), 1, 0); | |
| 169 | } | |
| 170 | function kerbBale(side, variant) { | |
| 171 | const y = side * KERB_BALE; | |
| 172 | bale(-.6, y - .5, y + .5, 1.2, 40 + variant * 7, .8 + variant * .15); | |
| 173 | } | |
| 174 | // a gate: rows of bales from kerb to gap and from gap to kerb, drawn on the lane side the page shows (screen right is -y) | |
| 175 | function gate(g) { | |
| 176 | const base = mod(g.x, STEP), lo = -g.centre - g.width / 2, hi = -g.centre + g.width / 2; | |
| 177 | let seed = 3; | |
| 178 | for (const [a, b] of [[-Cart.ROAD_HALF, lo], [hi, Cart.ROAD_HALF]]) { | |
| 179 | const n = Math.max(1, Math.round((b - a) / 1.1)), w = (b - a) / n; | |
| 180 | for (let k = 0; k < n; k++) bale(base, a + k * w + .02, a + (k + 1) * w - .02, Cart.GATE_DEPTH, seed += 5, .95 + (hash(seed, 1) > .5 ? .1 : 0)); | |
| 181 | } | |
| 182 | } | |
| 183 | function banner() { | |
| 184 | const base = 0; | |
| 185 | for (const y of [-4.2, 4.2]) capsule([base, y, 0], [base, y, 4.6], .14, .14, () => STEEL, 'solid'); | |
| 186 | for (let y = -4.2, k = 0; y < 4.2; y += .6, k++) for (let r = 0; r < 2; r++) box(base - .08, y, 3.3 + r * .6, base + .08, y + .6, 3.9 + r * .6, (k + r) & 1 ? [30, 28, 36] : [246, 244, 238], 60 + k + r); | |
| 187 | box(base - .12, -4.4, 3.2, base + .12, 4.4, 3.3, RED, 70); | |
| 188 | for (const y of [-4.2, 4.2]) castShadow(base, y, 4.2, .3, 1, 0); | |
| 189 | for (let y = -4; y <= 4; y += .8) castShadow(base, y, 3.8, .45, 1, 0); | |
| 190 | } | |
| 191 | // bunting across the street: a string between two posts with flags that swing between two poses | |
| 192 | function bunting(frame) { | |
| 193 | for (const y of [-4.3, 4.3]) capsule([0, y, 0], [0, y, 4.2], .08, .08, () => STEEL, 'solid'); | |
| 194 | for (let k = 0; k < 14; k++) { | |
| 195 | const y = -4.2 + k * .6, sag = 4.1 - .5 * Math.sin((k / 13) * Math.PI); | |
| 196 | box(-.04, y, sag - .05, .04, y + .6, sag, DARK, 80); | |
| 197 | const c = FLAGS[k % FLAGS.length], sway = ((k + frame) & 1) * .1 - .05; | |
| 198 | box(-.05 + sway, y + .1, sag - .5, .05 + sway, y + .5, sag - .05, c, 90 + k); | |
| 199 | } | |
| 200 | for (const y of [-4.3, 4.3]) castShadow(0, y, 4.1, .25, 1, 0); | |
| 201 | for (let y = -3.8; y <= 3.8; y += .8) castShadow(0, y, 3.8, .3, 1, 0); | |
| 202 | } | |
| 203 | // draw() onto empty buffers and keep what it wrote: pixels with depth, and shadow strength | |
| 204 | function record(drawIt) { | |
| 205 | const savedPix = pix.slice(), savedZ = zb.slice(); | |
| 206 | zb.fill(-1e9); shadowMask.fill(0); | |
| 207 | drawIt(); | |
| 208 | flushShadows(); | |
| 209 | pendingShadows.length = 0; | |
| 210 | const hits = [], shade = []; | |
| 211 | for (let i = 0; i < zb.length; i++) { | |
| 212 | if (zb[i] > -1e8) hits.push(i, pix[i], zb[i]); | |
| 213 | if (shadowMask[i]) shade.push(i, shadowMask[i]); | |
| 214 | } | |
| 215 | pix.set(savedPix); zb.set(savedZ); shadowMask.fill(0); | |
| 216 | return { hits, shade }; | |
| 217 | } | |
| 218 | // k camera steps from where the sprite was drawn is 2k px right and k px down, and k steps nearer the camera along x | |
| 219 | function blit(sprite, k) { | |
| 220 | const dx = 2 * k, dy = k, dd = k * STEP / R2 * COS, { hits, shade } = sprite; | |
| 221 | for (let n = 0; n < hits.length; n += 3) { | |
| 222 | const i = hits[n], ix = i % W + dx, iy = (i / W | 0) + dy; | |
| 223 | if (ix < 0 || iy < 0 || ix >= W || iy >= H) continue; | |
| 224 | const t = iy * W + ix, d = hits[n + 2] + dd; | |
| 225 | if (d <= zb[t]) continue; | |
| 226 | zb[t] = d; pix[t] = hits[n + 1]; | |
| 227 | } | |
| 228 | for (let n = 0; n < shade.length; n += 2) { | |
| 229 | const i = shade[n], ix = i % W + dx, iy = (i / W | 0) + dy; | |
| 230 | if (ix < 0 || iy < 0 || ix >= W || iy >= H) continue; | |
| 231 | const t = iy * W + ix; | |
| 232 | if (shadowMask[t] < shade[n + 1]) shadowMask[t] = shade[n + 1]; | |
| 233 | } | |
| 234 | } | |
| 235 | const cache = new Map(); | |
| 236 | const sprite = (key, drawIt) => { let s = cache.get(key); if (!s) cache.set(key, s = record(drawIt)); return s; }; | |
| 237 | // steps from the camera to a sprite drawn at base (a multiple-of-STEP-free offset) for world distance X | |
| 238 | const stepsTo = (X, n) => Math.round((X - mod(X, STEP)) / STEP) - n; | |
| 239 | const visible = (m, ahead, behind) => m > -behind && m < ahead; | |
| 240 | ||
| 241 | /* ---------- the cart ---------- */ | |
| 242 | function cart(x, y, flash) { | |
| 243 | const x0 = x - 1.5, x1 = x + .1, w = .55; | |
| 244 | for (const wx of [x0 + .35, x1 - .4]) for (const wy of [y - w - .08, y + w - .02]) box(wx - .22, wy, 0, wx + .22, wy + .1, .44, DARK, 7); | |
| 245 | box(x0, y - w, .3, x1, y + w, .62, flash ? [236, 120, 100] : WOOD, 11); | |
| 246 | box(x0, y - w, .62, x0 + .08, y + w, .95, WOOD_DARK, 13); // the back board | |
| 247 | box(x1 - .5, y - w, .62, x1, y + w, .9, WOOD_DARK, 15); // the seat front | |
| 248 | box(x1 - .08, y - w, .3, x1 + .12, y + w, .5, RED, 17); // the nose | |
| 249 | sphere(x0 + .75, y, 1.05, .22, [236, 196, 150], 'solid'); | |
| 250 | box(x0 + .55, y - .22, .62, x0 + .95, y + .22, .98, [74, 122, 170], 19); | |
| 251 | box(x0 + .5, y - .26, 1.2, x0 + 1, y + .26, 1.32, RED, 21); // helmet crown | |
| 252 | castShadow(x0 + .75, y, 1.1, .35, 1, 0); | |
| 253 | for (let t = x0; t <= x1; t += .5) for (const dy of [-w, w]) castShadow(t, y + dy, .5, .3, 1, 0); | |
| 254 | } | |
| 255 | function draw() { | |
| 256 | const n = Math.round(R.x / STEP) + LEAD_STEPS, cam = n * STEP; // the camera moves in whole steps so the ground scrolls in whole pixels | |
| 257 | pix.set(phases[mod(n, PHASES)]); | |
| 258 | zb.set(baseZ); | |
| 259 | strips(cam); | |
| 260 | finishLine(cam); | |
| 261 | const j0 = Math.floor((cam - 16) / (KERB_SPACE * STEP)), j1 = Math.ceil((cam + 36) / (KERB_SPACE * STEP)); | |
| 262 | for (let j = j0; j <= j1; j++) for (const side of [-1, 1]) { | |
| 263 | const v = (hash(j, side) > .5) | 0; | |
| 264 | blit(sprite(`k${side}${v}`, () => kerbBale(side, v)), j * KERB_SPACE - n); | |
| 265 | } | |
| 266 | for (let i = 0; i < Cart.GATES; i++) { | |
| 267 | const g = Cart.gateAt(i, R.seed); | |
| 268 | if (visible(g.x - cam, 36, 16)) blit(sprite(`g${R.seed}:${i}`, () => gate(g)), stepsTo(g.x, n)); | |
| 269 | const b = g.x + Cart.GATE_GAP / 2 + 4; | |
| 270 | if (visible(b - cam, 36, 16)) blit(sprite(`b${STILL ? 0 : Math.floor(G.time * 8) & 1}`, () => bunting(STILL ? 0 : Math.floor(G.time * 8) & 1)), Math.round(b / STEP) - n); | |
| 271 | } | |
| 272 | if (visible(Cart.LENGTH - cam, 36, 16)) blit(sprite('banner', banner), Math.round(Cart.LENGTH / STEP) - n); | |
| 273 | if (!(R.clear > 0 && Math.floor(R.clear * 10) % 2)) cart(R.x - cam, -R.lane, R.clear > .6); | |
| 274 | applyShadows(groundZ); | |
| 275 | shadeEdges(); | |
| 276 | ctx.putImageData(image, 0, 0); | |
| 277 | } | |
| 278 | ||
| 279 | /* ---------- game ---------- */ | |
| 280 | function act(events) { | |
| 281 | for (const e of events) { | |
| 282 | if (e.type === 'hit') { note(e.lives ? `a bale: ${e.lives} ${e.lives === 1 ? 'life' : 'lives'} left` : 'the third bale'); sound('thud'); } | |
| 283 | if (e.type === 'boost') { note('flagstones: boost'); sound('chime'); } | |
| 284 | if (e.type === 'won') { | |
| 285 | if (R.record) try { localStorage.setItem(BEST_KEY, String(R.best)); } catch (err) { /* private window: keep it for this visit */ } | |
| 286 | setStatus(`banner! ${R.time.toFixed(1)} s${R.record ? ' · new best' : ` · best ${R.best.toFixed(1)} s`} · tap or press space to roll again`); | |
| 287 | sound('chime'); | |
| 288 | } | |
| 289 | if (e.type === 'lost') { setStatus(`wrecked at ${Math.round(R.x)} m · tap or press space to roll again`); sound('buzz'); } | |
| 290 | } | |
| 291 | renderHud(); | |
| 292 | } | |
| 293 | function restart() { | |
| 294 | const next = Cart.again(R); | |
| 295 | if (!next) return false; | |
| 296 | R = next; | |
| 297 | cache.clear(); | |
| 298 | G.steer = 0; | |
| 299 | note(HINT); | |
| 300 | renderHud(); | |
| 301 | return true; | |
| 302 | } | |
| 303 | const KEY_RATE = 1.8; // full lock in about half a second | |
| 304 | const keys = new Set(); | |
| 305 | function update(dt) { | |
| 306 | G.time += dt; | |
| 307 | if (keys.size) G.steer = Math.max(-1, Math.min(1, G.steer + ((keys.has('right') ? 1 : 0) - (keys.has('left') ? 1 : 0)) * KEY_RATE * dt)); | |
| 308 | act(Cart.advance(R, dt, { steer: G.steer })); | |
| 309 | if (R.phase === 'play' && G.time >= G.noteUntil) setStatus(`${Math.ceil(Cart.distanceLeft(R))} m to the banner`); | |
| 310 | } | |
| 311 | ||
| 312 | /* ---------- input ---------- */ | |
| 313 | const KEYMAP = { ArrowLeft: 'left', a: 'left', A: 'left', ArrowRight: 'right', d: 'right', D: 'right' }; | |
| 314 | canvas.addEventListener('keydown', e => { | |
| 315 | const k = KEYMAP[e.key]; | |
| 316 | if (!k && e.key !== ' ') return; | |
| 317 | e.preventDefault(); | |
| 318 | ensureAudio(); | |
| 319 | if (e.repeat) return; | |
| 320 | if (restart()) return; | |
| 321 | if (k) keys.add(k); | |
| 322 | }); | |
| 323 | canvas.addEventListener('keyup', e => { const k = KEYMAP[e.key]; if (k) keys.delete(k); }); | |
| 324 | let drag = null; | |
| 325 | canvas.addEventListener('blur', () => { keys.clear(); drag = null; }); | |
| 326 | canvas.addEventListener('pointerdown', e => { | |
| 327 | ensureAudio(); | |
| 328 | canvas.focus({ preventScroll: true }); | |
| 329 | if (restart()) return; | |
| 330 | drag = { id: e.pointerId, x: e.clientX, steer: G.steer }; | |
| 331 | try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* synthetic pointers have nothing to capture */ } | |
| 332 | }); | |
| 333 | canvas.addEventListener('pointermove', e => { | |
| 334 | if (!drag || drag.id !== e.pointerId) return; | |
| 335 | const rect = canvas.getBoundingClientRect(), dx = (e.clientX - drag.x) / (rect.width || W) * W; | |
| 336 | G.steer = Math.max(-1, Math.min(1, drag.steer + dx / 100)); // 100 canvas pixels of drag is full lock | |
| 337 | }); | |
| 338 | for (const type of ['pointerup', 'pointercancel']) canvas.addEventListener(type, e => { if (drag && drag.id === e.pointerId) drag = null; }); | |
| 339 | ||
| 340 | /* ---------- sound ---------- */ | |
| 341 | let audio = null, muted = false; | |
| 342 | function ensureAudio() { | |
| 343 | if (audio) { if (audio.state === 'suspended') audio.resume(); return; } | |
| 344 | const AC = window.AudioContext || window.webkitAudioContext; | |
| 345 | if (AC) audio = new AC(); | |
| 346 | } | |
| 347 | function sound(kind) { | |
| 348 | if (!audio || muted) return; | |
| 349 | const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator(); | |
| 350 | const spec = { | |
| 351 | thud: [160, 60, .18, .09, 'square'], | |
| 352 | chime: [520, 880, .25, .06, 'sine'], | |
| 353 | buzz: [150, 60, .4, .06, 'sawtooth'], | |
| 354 | }[kind]; | |
| 355 | osc.type = spec[4]; | |
| 356 | osc.frequency.setValueAtTime(spec[0], now); | |
| 357 | osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]); | |
| 358 | gain.gain.setValueAtTime(spec[3], now); | |
| 359 | gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]); | |
| 360 | osc.connect(gain).connect(audio.destination); | |
| 361 | osc.start(now); osc.stop(now + spec[2] + .01); | |
| 362 | } | |
| 363 | const muteButton = document.getElementById('mute'); | |
| 364 | muteButton.addEventListener('click', () => { | |
| 365 | muted = !muted; | |
| 366 | muteButton.textContent = muted ? 'sound off' : 'sound on'; | |
| 367 | muteButton.setAttribute('aria-pressed', String(muted)); | |
| 368 | }); | |
| 369 | ||
| 370 | /* ---------- fit and boot ---------- */ | |
| 371 | addEventListener('resize', fit); | |
| 372 | fit(); | |
| 373 | bakeGround(); | |
| 374 | note(HINT); | |
| 375 | renderHud(); | |
| 376 | canvas.focus({ preventScroll: true }); | |
| 377 | let last = performance.now(); | |
| 378 | function frame(now) { | |
| 379 | update(Math.min(.04, (now - last) / 1000)); | |
| 380 | last = now; | |
| 381 | draw(); | |
| 382 | requestAnimationFrame(frame); | |
| 383 | } | |
| 384 | requestAnimationFrame(frame); | |
| 385 | </script> | |
| 386 | </body> | |
| 387 | </html> |
soapbox-derby/page.test.mjs added +29
| @@ -0,0 +1,29 @@ | ||
| 1 | import vm from 'node:vm'; | |
| 2 | import { test, expect } from 'bun:test'; | |
| 3 | import { boot } from '../playtest.mjs'; | |
| 4 | ||
| 5 | const state = g => vm.runInContext('R', g.window); | |
| 6 | ||
| 7 | test('dragging steers the cart and the HUD follows the run', () => { | |
| 8 | const g = boot('soapbox-derby'); | |
| 9 | g.run(.5); | |
| 10 | expect(String(g.el('lives').textContent)).toBe('3'); | |
| 11 | g.down(180, 140); | |
| 12 | for (let x = 180; x <= 280; x += 10) { g.move(x, 140); g.run(.04); } | |
| 13 | g.run(1.5); | |
| 14 | expect(state(g).lane).toBeGreaterThan(1); | |
| 15 | g.up(280, 140); | |
| 16 | expect(Number(g.el('left').textContent)).toBeLessThan(360); | |
| 17 | expect(g.errors).toEqual([]); | |
| 18 | }); | |
| 19 | ||
| 20 | test('the arrow keys steer both ways', () => { | |
| 21 | const g = boot('soapbox-derby'); | |
| 22 | g.keyDown('ArrowLeft'); g.run(1.2); g.keyUp('ArrowLeft'); | |
| 23 | g.run(.8); | |
| 24 | expect(state(g).lane).toBeLessThan(-1); | |
| 25 | g.keyDown('ArrowRight'); g.run(2.2); g.keyUp('ArrowRight'); | |
| 26 | g.run(.8); | |
| 27 | expect(state(g).lane).toBeGreaterThan(1); | |
| 28 | expect(g.errors).toEqual([]); | |
| 29 | }); |
new above
offline