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

Migrated from github.com/amirmushichge/pixel-plays

Add Go-Kart Fete: three laps of a hay-bale oval, holding the throttle on the straights and lifting for the bends #81

Parked opened this
Closed without merging

quill/pixel-plays:quill/77-add-go-kart-fete-three-laps-of-a-hay-bal → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +728 −3
README.md +3 −2
@@ -40,6 +40,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
4040 | [Tram Line](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 |
4141 | [Espresso Bar](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 |
4242 | [Goalkeeper](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 | [Go-Kart Fete](go-kart/) | Three races of three laps round an oval of hay bales on a school field against three rival karts: hold to accelerate along the racing line and let go to brake; every bend has a safe speed on a marker board beside the track, and entering faster runs the kart wide into the hay for a second; finishing first scores 3, second 2, third 1, last 0, rivals are a little quicker each race, and 6 points or more over the three races wins (forged by the crew on the engine and shell above, not by the original creators) | Hold space or up, or press and hold the canvas |
4344 | [Soapbox Derby](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 |
4445
4546 ## Run
@@ -60,7 +61,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is
6061 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.
6162
6263 ## Add a game
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`.
64 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, Soapbox Derby and Go-Kart Fete 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`.
6465
6566 - `shell.js` provides the game menu, the Rules popup, the credits and the background music.
6667 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
@@ -76,7 +77,7 @@ Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules
7677 - Depth-buffer edges: darker where an object sits in front, a warm rim on upper-left edges.
7778 - Large flat surfaces use closely spaced tones; wide steps make the dither read as a checkerboard.
7879 - Characters stay sharp: flat bands with no dither, a dark silhouette on their own pixels, patterns at least 3px wide.
79 - Ambient motion only where the scene names it: grass and leaves sway in whole pixels at 8 fps, Tram Line's waiting passengers shift their weight, and Espresso Bar's machine steam and awning fringe move; all of it stops under `prefers-reduced-motion`.
80 - Ambient motion only where the scene names it: grass and leaves sway in whole pixels at 8 fps, Tram Line's waiting passengers shift their weight, and Espresso Bar's machine steam and awning fringe move, and Go-Kart Fete's chequered flag and spectators' waving move (each bend's safe-speed board stays up); all of it stops under `prefers-reduced-motion`.
8081
8182 ## License
8283 The code is under the [MIT License](LICENSE). The music is not: see [MUSIC.md](MUSIC.md).
bell-tower/page.test.mjs +1 −1
@@ -6,7 +6,7 @@ import { boot } from '../playtest.mjs';
66 const state = g => vm.runInContext('P', g.window);
77 function untilTurn(g) { for (let n = 0; state(g).phase !== 'ring' && n < 400; n++) g.run(.05); expect(state(g).phase).toBe('ring'); }
88
9 test('the HUD peal length follows the peal the tower is ringing', () => {
9 test('the HUD peal length follows the peal the tower is ringing', { timeout: 60000 }, () => {
1010 const g = boot('bell-tower');
1111 g.run(1);
1212 untilTurn(g);
go-kart/index.html added +362
@@ -0,0 +1,362 @@
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>Go-Kart Fete</title>
7 <!-- og:begin -->
8 <meta name="description" content="Hold to race, let go for the bends: three laps round the hay bales against three rivals">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/go-kart/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Go-Kart Fete">
13 <meta property="og:description" content="Hold to race, let go for the bends: three laps round the hay bales against three rivals">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/go-kart/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/go-kart.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="Go-Kart Fete: the opening scene of the game">
20 <meta name="twitter:card" content="summary_large_image">
21 <!-- og:end -->
22 <style>
23 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; --accent: #e0a526; }
24 * { box-sizing: border-box; }
25 html, body { height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
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(--accent); }
33 .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; }
34 .row span { color: var(--muted); }
35 #status { color: var(--muted); min-height: 1.35em; }
36 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
37 button:hover, button:focus-visible { color: var(--ink); }
38 </style>
39 </head>
40 <body>
41 <div id="stage"><canvas id="c" tabindex="0" aria-label="A school field with an oval track edged with hay bales, a chequered flag on a pole and four go-karts on the line: yours and three rivals. Hold space or the up arrow, or press and hold anywhere on the canvas, to accelerate; let go to brake. Every bend has a safe speed shown on a board beside the track before it: enter faster and the kart runs wide into the hay and stops for a second. Three laps a race, three races: first place scores 3, second 2, third 1, last 0, and 6 points or more wins."></canvas></div>
42 <div id="scores">
43 <div class="row"><b id="race">1</b><span>race of 3</span></div>
44 <div class="row"><b id="lap">1</b><span>lap of 3</span></div>
45 <div class="row"><b id="pos">1st</b><span>of 4</span></div>
46 <div class="row"><b id="speed">0</b><span>speed</span></div>
47 <div class="row"><b id="total">0</b><span>total</span></div>
48 <div class="row"><b id="best">0</b><span>best</span></div>
49 </div>
50 <div class="hud" id="bottom">
51 <div id="status" role="status" aria-live="polite"></div>
52 <button id="mute" type="button" aria-pressed="false">sound on</button>
53 </div>
54 <script src="../shell.js"></script>
55 <script>
56 PixelPlays.mount({
57 id: 'go-kart',
58 rules: [
59 'Hold space or up, or press and hold the canvas, to accelerate; let go to brake.',
60 'Each bend has a safe speed on the board before it: enter faster and the kart runs wide into the hay for a second.',
61 'Three laps a race, three races. First scores 3, second 2, third 1, last 0; 6 or more wins.',
62 ],
63 });
64 </script>
65 <script>window.PP_SCENE = { originY: 6, shadowX: 1.3, shadowY: -.12 };</script>
66 <script src="../engine.js"></script>
67 <script src="lap.js"></script>
68 <script>
69 'use strict';
70
71 const BEST_KEY = 'pixel-plays-go-kart-best';
72 const HALF = Lap.STRAIGHT / 2, R = Lap.RADIUS, TRACK = 1.8, BALE_LANE = 2.35, BOARD_LANE = -3.9, BOARD_Z = 2.7;
73 const FIELD = { x: 17.5, y: 10.8 };
74 const LANES = [-1.05, -.35, .35, 1.05], MINE = 2, RIVAL_LANES = [0, 1, 3], WIDE_LANE = -1.85;
75 const DIRT = [206, 178, 130], GRASS_PX = [96, 144, 66], LINE_PX = [238, 234, 222], YELLOW_PX = rgb(255, 214, 10);
76 const HAYS = [[224, 186, 86], [212, 170, 70], [232, 198, 104]];
77 const KARTS = [[212, 62, 50], [58, 112, 196], [64, 158, 98], [150, 98, 170]];
78 const FRAME_DARK = [48, 48, 56], WHEEL = [38, 38, 44], STEEL = [150, 154, 164], POST = [74, 78, 88];
79 const SHIRTS = [[200, 92, 74], [74, 120, 170], [214, 168, 70], [96, 150, 104], [140, 100, 160]];
80 const INK_PX = rgb(28, 27, 25), PAPER_PX = rgb(255, 255, 255);
81 const ORDINAL = ['1st', '2nd', '3rd', '4th'];
82
83 /* ---------- state ---------- */
84 const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })();
85 let S_ = Lap.newGame(best0);
86 const G = { time: 0, status: '', noteUntil: 0, lane: LANES[MINE], yaw: 0 };
87 const nodes = {};
88 for (const id of ['race', 'lap', 'pos', 'speed', 'total', 'best', 'status']) nodes[id] = document.getElementById(id);
89 function renderHud() {
90 nodes.race.textContent = S_.race + 1;
91 nodes.lap.textContent = Lap.lapOf(S_.dist);
92 nodes.pos.textContent = ORDINAL[Math.max(1, Math.min(4, S_.position)) - 1];
93 nodes.speed.textContent = Math.round(S_.v * 10);
94 nodes.total.textContent = S_.total;
95 nodes.best.textContent = Math.max(S_.best, S_.total);
96 }
97 function setStatus(text) {
98 if (text === G.status) return;
99 G.status = text;
100 nodes.status.textContent = text;
101 }
102 function note(text) { setStatus(text); G.noteUntil = G.time + 2.2; }
103 const HINT = 'hold space or press to drive · lift before each bend, its board shows the safe speed';
104 const boardNumber = n => Math.round(Lap.safeSpeed(n) * 10);
105
106 /* ---------- baked scene: the field, the track, the hay bales and the posts ---------- */
107 const mod = (a, n) => ((a % n) + n) % n;
108 // how far outside the racing line a point is: negative inside the oval
109 function outside(x, y) {
110 const ax = Math.abs(x);
111 return ax <= HALF ? Math.abs(y) - R : Math.hypot(ax - HALF, y) - R;
112 }
113 function groundColor(x, y) {
114 const o = outside(x, y), ao = Math.abs(o);
115 if (ao <= TRACK) {
116 if (ao > TRACK - .14) return rgb(...LINE_PX);
117 if (y < 0 && Math.abs(x) <= HALF && x > -HALF - .3 && x < -HALF + .3) {
118 const on = (Math.floor((x + HALF + .3) / .3) + Math.floor((y + R + TRACK) / .45)) & 1;
119 return on ? rgb(30, 30, 36) : rgb(...LINE_PX);
120 }
121 if (y < 0 && Math.abs(x - HALF) < .12 || y > 0 && Math.abs(x + HALF) < .12) return YELLOW_PX;
122 const t = .94 + hash(Math.floor(x * 5), Math.floor(y * 5)) * .1;
123 return rgb(DIRT[0] * t, DIRT[1] * t, DIRT[2] * t);
124 }
125 if (ao <= TRACK + 1.1) { const t = .74 + hash(Math.floor(x * 4), Math.floor(y * 4)) * .1; return rgb(DIRT[0] * t, DIRT[1] * t, DIRT[2] * t); }
126 const stripe = Math.floor((x + y) / 1.5) & 1, t = (stripe ? .93 : 1) + hash(Math.floor(x * 3), Math.floor(y * 3)) * .07;
127 return rgb(GRASS_PX[0] * t, GRASS_PX[1] * t, GRASS_PX[2] * t);
128 }
129 function bakeGround() {
130 zb.fill(-1e9); groundZ.fill(-1e9); pix.fill(PAPER_PX);
131 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
132 const g = unproject(ix + .5, iy + .5), i = iy * W + ix;
133 const e = (g.x / FIELD.x) ** 4 + (g.y / FIELD.y) ** 4 + (hash(ix, iy) - .5) * .1;
134 if (e > 1.02 || (e > .93 && hash(iy, ix) < (e - .93) / .1)) continue;
135 zb[i] = groundZ[i] = (g.x + g.y) / R2 * COS;
136 ground[i] = 1;
137 pix[i] = groundColor(g.x, g.y);
138 }
139 }
140 // round bales lying on their sides in a ring, one lane out from the racing line
141 function ring(lane, tag) {
142 const bendScale = (R - lane) / R;
143 let n = 0;
144 for (let d = 0; d < Lap.LENGTH; n++) {
145 const p = Lap.pointAt(d, lane), tx = Math.cos(p.heading) * .45, ty = Math.sin(p.heading) * .45, hay = HAYS[(n + tag) % 3];
146 capsule([p.x - tx, p.y - ty, .5], [p.x + tx, p.y + ty, .5], .5, .5, () => hay, 'rough');
147 if (hash(n, tag) < .3) capsule([p.x - tx * .8, p.y - ty * .8, 1.3], [p.x + tx * .8, p.y + ty * .8, 1.3], .4, .4, () => HAYS[(n + 1) % 3], 'rough');
148 for (const k of [-.5, 0, .5]) castShadow(p.x + tx * k * 2, p.y + ty * k * 2, 1, .5, 1, 0);
149 const bend = (d >= Lap.STRAIGHT && d < Lap.STRAIGHT + Lap.ARC) || d >= 2 * Lap.STRAIGHT + Lap.ARC;
150 d += .95 / (bend ? bendScale : 1);
151 }
152 }
153 function boardSpot(n) {
154 return Lap.pointAt(Lap.bendDistance(n) - 2.8, BOARD_LANE);
155 }
156 function bakeBoards() {
157 for (let n = 0; n < 2; n++) {
158 const p = boardSpot(n);
159 capsule([p.x, p.y, 0], [p.x, p.y, BOARD_Z], .08, .08, () => POST, 'solid');
160 for (let z = .5; z < BOARD_Z; z += .8) castShadow(p.x, p.y, z, .12, 1, 0);
161 }
162 const pole = [-HALF - .5, -R - 4.2];
163 capsule([pole[0], pole[1], 0], [pole[0], pole[1], 5.6], .1, .1, () => POST, 'solid');
164 for (let z = .5; z < 5.6; z += .7) castShadow(pole[0], pole[1], z, .12, 1, 0);
165 }
166 function bake() {
167 bakeGround();
168 ring(-BALE_LANE, 0);
169 ring(BALE_LANE, 5);
170 bakeBoards();
171 bakeOcclusion();
172 applyShadows(groundZ);
173 bakedPix.set(pix);
174 bakedZ.set(zb);
175 }
176
177 /* ---------- drawing ---------- */
178 const DIGITS = [
179 ['111', '101', '101', '101', '111'], ['010', '110', '010', '010', '111'], ['111', '001', '111', '100', '111'],
180 ['111', '001', '111', '001', '111'], ['101', '101', '111', '001', '001'], ['111', '100', '111', '001', '111'],
181 ['111', '100', '111', '101', '111'], ['111', '001', '010', '010', '010'], ['111', '101', '111', '101', '111'],
182 ['111', '101', '111', '001', '111'],
183 ];
184 function px(ix, iy, color) { if (ix >= 0 && iy >= 0 && ix < W && iy < H) pix[iy * W + ix] = color; }
185 // a yellow marker board with the safe speed in black, drawn flat so it reads without any motion
186 function board(n) {
187 const p = boardSpot(n), c = project(p.x, p.y, BOARD_Z), left = Math.round(c.sx) - 8, top = Math.round(c.sy) - 12;
188 for (let dy = 0; dy < 13; dy++) for (let dx = 0; dx < 17; dx++) px(left + dx, top + dy, dx === 0 || dy === 0 || dx === 16 || dy === 12 ? INK_PX : YELLOW_PX);
189 [...String(boardNumber(n))].forEach((ch, k) => DIGITS[+ch].forEach((row, dy) => [...row].forEach((on, dx) => {
190 if (on === '1') px(left + 3 + k * 6 + dx, top + 3 + dy, INK_PX);
191 })));
192 for (let dx = 0; dx < 11; dx++) px(left + 3 + dx, top + 9, INK_PX);
193 }
194 // a go-kart seen from above and the side: tub, four wheels, a driver in a helmet; yaw is the way it faces
195 function kart(x, y, yaw, colour, driver) {
196 const fx = Math.cos(yaw), fy = Math.sin(yaw), sx = -fy, sy = fx, k = 1.3;
197 const at = (a, b, z) => [x + (fx * a + sx * b) * k, y + (fy * a + sy * b) * k, z * k];
198 for (const a of [-.4, .4]) for (const b of [-.34, .34]) {
199 const w = at(a, b, .22);
200 sphere(w[0], w[1], w[2], .22 * k, WHEEL, 'solid');
201 castShadow(w[0], w[1], .2, .2 * k, 1, 0);
202 }
203 capsule(at(-.45, 0, .34), at(.5, 0, .34), .27 * k, .2 * k, () => colour, 'solid');
204 capsule(at(-.1, 0, .46), at(-.3, 0, .62), .12 * k, .2 * k, () => FRAME_DARK, 'solid');
205 const h = at(-.12, 0, .78);
206 sphere(h[0], h[1], h[2], .22 * k, driver, 'gloss');
207 const f = at(.5, 0, .3);
208 sphere(f[0], f[1], f[2], .24 * k, colour, 'solid');
209 castShadow(x, y, .4 * k, .45 * k, 1, 0); castShadow(h[0], h[1], h[2], .22 * k, 1, 0);
210 }
211 // the chequered flag: columns of squares that lift and fall a step at a time
212 function flag(t) {
213 const step = STILL ? 0 : Math.floor(t * 8), x0 = -HALF - .5, y0 = -R - 4.2;
214 for (let col = 0; col < 7; col++) for (let row = 0; row < 4; row++) {
215 const sway = STILL ? 0 : Math.sin(step * .9 + col * 1.1) * .06 * col, z = 5.6 - (row + 1) * .38;
216 box(x0 + .1 + col * .38, y0 + sway - .04, z, x0 + .1 + (col + 1) * .38, y0 + sway + .04, z + .38, (col + row) & 1 ? FLAG_LIGHT : FLAG_DARK, col * 4 + row);
217 }
218 }
219 const FLAG_LIGHT = [240, 236, 224], FLAG_DARK = [34, 34, 40];
220 const SPECTATORS = [[-3.4, .3], [-1.2, -.9], [1.3, .6], [3.5, -.3], [-4, -9.3], [-1.5, -9.6], [1, -9.3]];
221 // the spectators wave an arm at 6 fps; under reduced motion they stand with their arms down
222 function spectators(t) {
223 const step = STILL ? 0 : Math.floor(t * 6);
224 SPECTATORS.forEach(([x, y], i) => {
225 const shirt = SHIRTS[i % SHIRTS.length], wave = STILL ? .1 : 2.3 + ((step + i) % 2) * .6;
226 figure(x, y, y < -4 ? Math.PI / 2 : -Math.PI / 2 * (y > 0 ? .4 : 0) - .4, { stance: .1, armR: wave, armL: .08 },
227 { shirt, stripe: shirt.map(v => v * .8), legs: [60, 62, 78], skin: [226, 178, 140], hair: [58, 44, 36] }, dynamicAdd);
228 });
229 }
230 function draw() {
231 pix.set(bakedPix);
232 zb.set(bakedZ);
233 flag(G.time);
234 spectators(G.time);
235 RIVAL_LANES.forEach((lane, i) => {
236 const p = Lap.pointAt(Lap.rivalDistance(i, S_.race, S_.time), LANES[lane]);
237 kart(p.x, p.y, p.heading, KARTS[i + 1], DRIVERS[i + 1]);
238 });
239 const me = Lap.pointAt(S_.dist, G.lane);
240 kart(me.x, me.y, me.heading + G.yaw, KARTS[0], DRIVERS[0]);
241 flushShadows();
242 pendingShadows.length = 0;
243 applyShadows(groundZ);
244 shadeEdges();
245 board(0); board(1);
246 ctx.putImageData(image, 0, 0);
247 }
248 const DRIVERS = [[250, 246, 232], [240, 214, 70], [240, 240, 244], [60, 60, 70]];
249
250 /* ---------- game ---------- */
251 const hold = { key: false, pointers: new Set() };
252 const holding = () => hold.key || hold.pointers.size > 0;
253 function act(events) {
254 for (const e of events) {
255 if (e.type === 'start') { note('go!'); sound('chime'); }
256 if (e.type === 'lap') { note(`lap ${e.lap} of ${Lap.LAPS}`); sound('thud'); }
257 if (e.type === 'crash') { note(`too fast for the bend (${Math.round(e.speed * 10)}, safe ${Math.round(e.safe * 10)}): into the hay`); sound('buzz'); }
258 if (e.type === 'finish' && S_.phase === 'finished') {
259 setStatus(`race ${e.race + 1}: ${ORDINAL[e.position - 1]} place, +${e.points} · tap or press space for race ${e.race + 2}`);
260 sound(e.points ? 'chime' : 'buzz');
261 }
262 if (e.type === 'over') {
263 if (S_.record) try { localStorage.setItem(BEST_KEY, String(S_.best)); } catch (err) { /* private window: keep it for this visit */ }
264 const last = S_.results[S_.results.length - 1];
265 const verdict = e.win ? `you win the fete: ${e.total} points` : `not this time: ${e.total} points, ${Lap.WIN_AT} wins`;
266 setStatus(`${ORDINAL[last.position - 1]} place, +${last.points} · ${verdict}${S_.record ? ' · new best' : ` · best ${S_.best}`} · tap or press space to race again`);
267 sound(e.win ? 'chime' : 'buzz');
268 }
269 }
270 renderHud();
271 }
272 function restart() {
273 const next = Lap.again(S_);
274 if (!next) return false;
275 S_ = next;
276 hold.key = false; hold.pointers.clear();
277 G.lane = LANES[MINE]; G.yaw = 0;
278 note(HINT);
279 renderHud();
280 return true;
281 }
282 function update(dt) {
283 G.time += dt;
284 act(Lap.advance(S_, dt, holding()));
285 const k = Math.min(1, dt * 9);
286 G.lane += ((S_.wide ? WIDE_LANE : LANES[MINE]) - G.lane) * k;
287 G.yaw += ((S_.wide ? .7 : 0) - G.yaw) * k;
288 renderHud();
289 if (S_.phase === 'race' && G.time >= G.noteUntil) {
290 const next = S_.nextBend < Lap.BENDS ? `next bend safe ${boardNumber(S_.nextBend)}` : 'last straight';
291 setStatus(S_.inBend ? `in the bend · safe ${boardNumber(S_.nextBend - 1)}` : `lap ${Lap.lapOf(S_.dist)} of ${Lap.LAPS} · ${next}`);
292 }
293 }
294
295 /* ---------- input ---------- */
296 canvas.addEventListener('keydown', e => {
297 if (e.key !== ' ' && e.key !== 'ArrowUp') return;
298 e.preventDefault();
299 ensureAudio();
300 if (e.repeat) return;
301 if (restart()) return;
302 hold.key = true;
303 });
304 canvas.addEventListener('keyup', e => { if (e.key === ' ' || e.key === 'ArrowUp') hold.key = false; });
305 canvas.addEventListener('blur', () => { hold.key = false; hold.pointers.clear(); });
306 canvas.addEventListener('pointerdown', e => {
307 ensureAudio();
308 canvas.focus({ preventScroll: true });
309 if (restart()) return;
310 hold.pointers.add(e.pointerId);
311 try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* synthetic pointers have nothing to capture */ }
312 });
313 for (const type of ['pointerup', 'pointercancel']) canvas.addEventListener(type, e => hold.pointers.delete(e.pointerId));
314
315 /* ---------- sound ---------- */
316 let audio = null, muted = false;
317 function ensureAudio() {
318 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
319 const AC = window.AudioContext || window.webkitAudioContext;
320 if (AC) audio = new AC();
321 }
322 function sound(kind) {
323 if (!audio || muted) return;
324 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
325 const spec = {
326 thud: [180, 90, .12, .08, 'sine'],
327 chime: [660, 990, .3, .07, 'sine'],
328 buzz: [150, 70, .3, .06, 'sawtooth'],
329 }[kind];
330 osc.type = spec[4];
331 osc.frequency.setValueAtTime(spec[0], now);
332 osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]);
333 gain.gain.setValueAtTime(spec[3], now);
334 gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]);
335 osc.connect(gain).connect(audio.destination);
336 osc.start(now); osc.stop(now + spec[2] + .01);
337 }
338 const muteButton = document.getElementById('mute');
339 muteButton.addEventListener('click', () => {
340 muted = !muted;
341 muteButton.textContent = muted ? 'sound off' : 'sound on';
342 muteButton.setAttribute('aria-pressed', String(muted));
343 });
344
345 /* ---------- fit and boot ---------- */
346 addEventListener('resize', fit);
347 fit();
348 bake();
349 note(HINT);
350 renderHud();
351 canvas.focus({ preventScroll: true });
352 let last = performance.now();
353 function frame(now) {
354 update(Math.min(.04, (now - last) / 1000));
355 last = now;
356 draw();
357 requestAnimationFrame(frame);
358 }
359 requestAnimationFrame(frame);
360 </script>
361 </body>
362 </html>
go-kart/lap.js added +132
@@ -0,0 +1,132 @@
1 'use strict';
2 // The go-kart rules: three races of three laps round a hay-bale oval. Holding accelerates the kart along the racing
3 // line and letting go brakes; each bend has a safe speed, and entering one faster sends the kart wide into the hay,
4 // where it stops for a second. Three rival karts lap at fixed paces. Distances are in world units along the racing
5 // line, speeds in units per second. Plain numbers in, plain numbers out, no DOM. The page draws what this decides.
6 (function (root) {
7 const RACES = 3, LAPS = 3, RIVALS = 3;
8 const STRAIGHT = 14, RADIUS = 5; // the oval: two straights joined by two half circles
9 const ARC = Math.PI * RADIUS, LENGTH = 2 * STRAIGHT + 2 * ARC;
10 const BEND_START = [STRAIGHT, 2 * STRAIGHT + ARC]; // where each bend of a lap begins, along the line
11 const SAFE = [6.5, 5.8]; // the safe speed of each bend of a lap
12 const TOP = 10, ACCEL = 5, BRAKE = 9;
13 const CRASH_TIME = 1; // seconds stopped in the hay
14 const RIVAL_PACE = [5.4, 5.9, 6.3], RIVAL_UP = .05; // average speeds in race one, and how much quicker each later race is
15 const POINTS = [3, 2, 1, 0]; // by finishing position, first to last
16 const WIN_AT = 6;
17 const RESTART_AFTER = .6, EPS = 1e-9;
18
19 const finite = v => (Number.isFinite(v) ? v : 0);
20 const TOTAL = LAPS * LENGTH;
21 const pointsFor = position => POINTS[Math.max(1, Math.min(POINTS.length, Math.round(finite(position)))) - 1];
22 const rivalPace = (i, race) => RIVAL_PACE[Math.max(0, Math.min(RIVALS - 1, i | 0))] * (1 + RIVAL_UP * Math.max(0, finite(race)));
23 const rivalDistance = (i, race, time) => Math.min(TOTAL, rivalPace(i, race) * Math.max(0, finite(time)));
24 const safeSpeed = n => SAFE[((n % 2) + 2) % 2]; // n counts the bends of a race: 0, 1 are the first lap
25 const bendDistance = n => Math.floor(n / 2) * LENGTH + BEND_START[((n % 2) + 2) % 2];
26 const BENDS = LAPS * 2;
27 const isWin = total => finite(total) >= WIN_AT;
28 const lapOf = dist => Math.min(LAPS, Math.floor(Math.max(0, finite(dist)) / LENGTH) + 1);
29
30 // where the racing line is: a point and a heading for a distance along it, `lane` metres to the inside
31 function pointAt(dist, lane = 0) {
32 const d = ((finite(dist) % LENGTH) + LENGTH) % LENGTH, h = STRAIGHT / 2;
33 if (d < STRAIGHT) return { x: -h + d, y: -RADIUS + lane, heading: 0 };
34 if (d < STRAIGHT + ARC) {
35 const a = -Math.PI / 2 + (d - STRAIGHT) / RADIUS, r = RADIUS - lane;
36 return { x: h + Math.cos(a) * r, y: Math.sin(a) * r, heading: a + Math.PI / 2 };
37 }
38 if (d < 2 * STRAIGHT + ARC) return { x: h - (d - STRAIGHT - ARC), y: RADIUS - lane, heading: Math.PI };
39 const a = Math.PI / 2 + (d - 2 * STRAIGHT - ARC) / RADIUS, r = RADIUS - lane;
40 return { x: -h + Math.cos(a) * r, y: Math.sin(a) * r, heading: a + Math.PI / 2 };
41 }
42
43 function newRace(s) {
44 Object.assign(s, {
45 phase: 'ready', race: s.race, dist: 0, v: 0, time: 0, nextBend: 0, inBend: false, stopped: 0, wide: false,
46 crashes: 0, position: 1, timer: 0, result: null,
47 });
48 return s;
49 }
50 function newGame(best = 0) {
51 return newRace({ race: 0, total: 0, results: [], best: Math.max(0, finite(best)), record: false, reason: '' });
52 }
53 // how many rivals are ahead of the kart right now
54 function rivalsAhead(s, dist = s.dist, time = s.time) {
55 let n = 0;
56 for (let i = 0; i < RIVALS; i++) if (rivalDistance(i, s.race, time) > dist + EPS) n++;
57 return n;
58 }
59 const rankOf = s => 1 + rivalsAhead(s);
60
61 function finishRace(s, over, events) {
62 // the kart crossed the line `over` units ago: take back that bit of time to find when
63 const time = s.time - (s.v > EPS ? over / s.v : 0);
64 let ahead = 0;
65 for (let i = 0; i < RIVALS; i++) if (TOTAL / rivalPace(i, s.race) < time - EPS) ahead++;
66 const position = 1 + ahead, points = pointsFor(position);
67 s.position = position; s.total += points; s.timer = 0;
68 s.result = { race: s.race, position, points, time, crashes: s.crashes };
69 s.results.push(s.result);
70 s.phase = 'finished';
71 events.push({ type: 'finish', ...s.result });
72 if (s.race >= RACES - 1) {
73 s.phase = 'over'; s.reason = 'races';
74 if (s.total > s.best) { s.best = s.total; s.record = true; }
75 events.push({ type: 'over', total: s.total, win: isWin(s.total), record: s.record });
76 }
77 }
78 // move the kart and the rivals over dt; `hold` is whether the player holds the throttle
79 function advance(s, dt, hold) {
80 const events = [];
81 dt = Math.max(0, Math.min(.1, finite(dt)));
82 if (s.phase === 'over' || s.phase === 'finished') {
83 s.timer += dt;
84 if (s.phase === 'finished') { s.time += dt; s.v = Math.max(0, s.v - BRAKE * dt); s.dist += s.v * dt; }
85 return events;
86 }
87 if (s.phase === 'ready') {
88 if (!hold) return events;
89 s.phase = 'race';
90 events.push({ type: 'start', race: s.race });
91 }
92 s.time += dt;
93 const lap = lapOf(s.dist);
94 if (s.stopped > 0) {
95 s.stopped = Math.max(0, s.stopped - dt);
96 if (s.stopped <= EPS) { s.stopped = 0; s.wide = false; }
97 s.v = 0;
98 } else {
99 s.v = hold ? Math.min(TOP, s.v + ACCEL * dt) : Math.max(0, s.v - BRAKE * dt);
100 if (s.inBend) s.v = Math.min(s.v, safeSpeed(s.nextBend - 1)); // grip: a kart already round the bend cannot go faster
101 const step = s.v * dt, next = s.nextBend < BENDS ? bendDistance(s.nextBend) : Infinity;
102 if (s.dist + step >= next - EPS) {
103 const safe = safeSpeed(s.nextBend);
104 s.dist = next; s.nextBend++; s.inBend = true;
105 if (s.v > safe + EPS) {
106 events.push({ type: 'crash', bend: s.nextBend - 1, speed: s.v, safe });
107 s.v = 0; s.stopped = CRASH_TIME; s.wide = true; s.crashes++;
108 } else s.v = Math.min(s.v, safe);
109 } else s.dist += step;
110 if (s.inBend && s.dist >= bendDistance(s.nextBend - 1) + ARC) s.inBend = false;
111 }
112 const now = lapOf(s.dist);
113 if (now > lap) events.push({ type: 'lap', lap: now });
114 if (s.dist >= TOTAL - EPS) { finishRace(s, Math.max(0, s.dist - TOTAL), events); return events; }
115 s.position = rankOf(s);
116 return events;
117 }
118 // a press once the race or the game is over starts the next race, or a new game; otherwise null
119 function again(s) {
120 if (s.timer <= RESTART_AFTER) return null;
121 if (s.phase === 'finished') return newRace({ ...s, race: s.race + 1 });
122 if (s.phase === 'over') return newGame(s.best);
123 return null;
124 }
125
126 const api = {
127 RACES, LAPS, RIVALS, STRAIGHT, RADIUS, ARC, LENGTH, TOTAL, BEND_START, BENDS, SAFE, TOP, ACCEL, BRAKE, CRASH_TIME,
128 RIVAL_PACE, RIVAL_UP, POINTS, WIN_AT,
129 pointsFor, rivalPace, rivalDistance, safeSpeed, bendDistance, isWin, lapOf, pointAt, rankOf, newGame, advance, again,
130 };
131 if (typeof module !== 'undefined') module.exports = api; else root.Lap = api;
132 })(typeof window !== 'undefined' ? window : globalThis);
go-kart/lap.test.mjs added +221
@@ -0,0 +1,221 @@
1 import { test, expect } from 'bun:test';
2 import {
3 RACES, LAPS, LENGTH, TOTAL, ARC, SAFE, TOP, ACCEL, BRAKE, CRASH_TIME, RIVAL_PACE, POINTS, WIN_AT,
4 pointsFor, rivalPace, rivalDistance, safeSpeed, bendDistance, isWin, lapOf, pointAt, newGame, advance, again,
5 } from './lap.js';
6
7 const DT = 1 / 60;
8 const run = (s, seconds, hold) => { const out = []; for (let t = 0; t < seconds - 1e-9; t += DT) out.push(...advance(s, DT, hold)); return out; };
9 // a driver who lifts early enough to meet every bend at its safe speed
10 function perfect(s) {
11 const events = [];
12 for (let n = 0; n < 20000 && s.phase !== 'finished' && s.phase !== 'over'; n++) {
13 const ahead = s.nextBend < 6 ? bendDistance(s.nextBend) - s.dist : Infinity, safe = safeSpeed(s.nextBend);
14 const braking = s.v > safe ? (s.v * s.v - safe * safe) / (2 * BRAKE) : 0;
15 events.push(...advance(s, DT, s.inBend || ahead > braking + s.v * DT * 3 + .05 || s.v < safe - ACCEL * DT * 2));
16 }
17 return events;
18 }
19 // a driver who never lifts
20 const flatOut = s => { const out = []; for (let n = 0; n < 40000 && s.phase !== 'finished' && s.phase !== 'over'; n++) out.push(...advance(s, DT, true)); return out; };
21 test('a race is three laps and a game is three races', () => {
22 expect(LAPS).toBe(3);
23 expect(RACES).toBe(3);
24 expect(lapOf(0)).toBe(1);
25 expect(lapOf(LENGTH + 1)).toBe(2);
26 expect(lapOf(TOTAL + 5)).toBe(3);
27 });
28
29 test('the kart waits on the grid until the throttle is held', () => {
30 const s = newGame();
31 run(s, 2, false);
32 expect(s.phase).toBe('ready');
33 expect(s.dist).toBe(0);
34 expect(s.time).toBe(0);
35 run(s, .2, true);
36 expect(s.phase).toBe('race');
37 });
38
39 test('holding accelerates at the stated rate up to the top speed, and letting go brakes', () => {
40 const s = newGame();
41 run(s, .5, true);
42 expect(s.v).toBeCloseTo(ACCEL * .5, 1);
43 s.v = TOP - .2;
44 run(s, .2, true);
45 expect(s.v).toBe(TOP);
46 const before = s.v;
47 run(s, .3, false);
48 expect(s.v).toBeCloseTo(before - BRAKE * .3, 1);
49 run(s, 2, false);
50 expect(s.v).toBe(0);
51 expect(s.dist).toBeGreaterThan(0);
52 });
53
54 test('each bend has its own safe speed, round the lap', () => {
55 expect(safeSpeed(0)).toBe(SAFE[0]);
56 expect(safeSpeed(1)).toBe(SAFE[1]);
57 expect(safeSpeed(2)).toBe(SAFE[0]);
58 expect(bendDistance(1)).toBeGreaterThan(bendDistance(0));
59 expect(bendDistance(2)).toBeCloseTo(LENGTH + bendDistance(0), 6);
60 });
61
62 test('entering a bend at its safe speed or less carries on, and the bend then caps the speed', () => {
63 const s = newGame();
64 s.phase = 'race'; s.dist = bendDistance(0) - .05; s.v = SAFE[0] - .1;
65 const events = run(s, .3, true);
66 expect(events.some(e => e.type === 'crash')).toBe(false);
67 expect(s.stopped).toBe(0);
68 expect(s.v).toBeLessThanOrEqual(SAFE[0] + 1e-9);
69 expect(s.dist).toBeGreaterThan(bendDistance(0));
70 });
71
72 test('entering a bend faster than its safe speed sends the kart wide into the hay for a second', () => {
73 const s = newGame();
74 s.phase = 'race'; s.dist = bendDistance(0) - .05; s.v = SAFE[0] + 1;
75 const events = run(s, DT * 3, false);
76 const crash = events.find(e => e.type === 'crash');
77 expect(crash).toBeTruthy();
78 expect(crash.safe).toBe(SAFE[0]);
79 expect(s.wide).toBe(true);
80 expect(s.v).toBe(0);
81 const at = s.dist;
82 run(s, CRASH_TIME - .1, true);
83 expect(s.dist).toBe(at); // still stopped, whatever the throttle
84 expect(s.wide).toBe(true);
85 run(s, .2, true);
86 expect(s.wide).toBe(false);
87 run(s, .3, true);
88 expect(s.dist).toBeGreaterThan(at);
89 });
90
91 test('the same bend does not crash the kart twice', () => {
92 const s = newGame();
93 s.phase = 'race'; s.dist = bendDistance(0) - .05; s.v = TOP;
94 const events = run(s, 4, true);
95 expect(events.filter(e => e.type === 'crash').length).toBe(1);
96 expect(s.crashes).toBe(1);
97 });
98
99 test('rival karts lap at fixed, slightly varied paces, and each race they are a little quicker', () => {
100 expect(new Set(RIVAL_PACE).size).toBe(3);
101 expect(rivalDistance(0, 0, 10)).toBeCloseTo(rivalPace(0, 0) * 10, 6);
102 expect(rivalDistance(0, 0, 10)).toBe(RIVAL_PACE[0] * 10);
103 for (let i = 0; i < 3; i++) {
104 expect(rivalPace(i, 1)).toBeGreaterThan(rivalPace(i, 0));
105 expect(rivalPace(i, 2)).toBeGreaterThan(rivalPace(i, 1));
106 expect(rivalPace(i, 2)).toBeLessThan(rivalPace(i, 0) * 1.2);
107 }
108 expect(rivalDistance(2, 0, 1000)).toBe(TOTAL);
109 for (let race = 0; race < 5; race++) for (let i = 0; i < 3; i++) expect(rivalDistance(i, race, 1e6)).toBe(TOTAL);
110 });
111
112 test('finishing position scores first 3, second 2, third 1, last 0', () => {
113 expect(POINTS).toEqual([3, 2, 1, 0]);
114 expect([1, 2, 3, 4].map(pointsFor)).toEqual([3, 2, 1, 0]);
115 });
116
117 test('a clean drive wins the first race, and the finish takes its points from the position', () => {
118 const s = newGame();
119 run(s, .1, true);
120 const events = perfect(s);
121 expect(events.some(e => e.type === 'crash')).toBe(false);
122 const done = events.find(e => e.type === 'finish');
123 expect(done.position).toBe(1);
124 expect(done.points).toBe(3);
125 expect(s.total).toBe(3);
126 expect(events.filter(e => e.type === 'lap').length).toBe(2);
127 expect(s.phase).toBe('finished');
128 });
129
130 test('a driver who never lifts crashes at the first bends and finishes behind the rivals', () => {
131 const s = newGame();
132 const events = flatOut(s);
133 expect(events.filter(e => e.type === 'crash').length).toBeGreaterThan(1);
134 const done = events.find(e => e.type === 'finish');
135 expect(done.position).toBe(4);
136 expect(done.points).toBe(0);
137 });
138
139 test('a finish ahead of some rivals but not all takes the matching position', () => {
140 const s = newGame();
141 s.phase = 'race'; s.dist = TOTAL - .001; s.v = 5; s.nextBend = 6;
142 s.time = TOTAL / RIVAL_PACE[1] + .5; // later than the middle rival's finish, earlier than the slowest's
143 const done = advance(s, DT, true).find(e => e.type === 'finish');
144 expect(done.position).toBe(3);
145 expect(done.points).toBe(1);
146 const t = newGame();
147 t.phase = 'race'; t.dist = TOTAL - .001; t.v = 5; t.nextBend = 6;
148 t.time = TOTAL / RIVAL_PACE[2] + .5;
149 expect(advance(t, DT, true).find(e => e.type === 'finish').position).toBe(2);
150 });
151
152 test('the next race starts on the same oval, after the pause, with quicker rivals', () => {
153 const s = newGame();
154 perfect(s);
155 expect(again(s)).toBe(null); // too soon
156 run(s, 1, false);
157 const next = again(s);
158 expect(next.race).toBe(1);
159 expect(next.phase).toBe('ready');
160 expect(next.dist).toBe(0);
161 expect(next.total).toBe(3); // points carry over
162 expect(rivalPace(0, next.race)).toBeGreaterThan(rivalPace(0, 0));
163 });
164
165 test('after the third race the game is over, and a press starts a fresh game keeping the best', () => {
166 let s = newGame();
167 const events = [];
168 for (let r = 0; r < RACES; r++) {
169 events.push(...perfect(s));
170 if (s.phase === 'over') break;
171 run(s, 1, false);
172 s = again(s);
173 }
174 expect(s.phase).toBe('over');
175 expect(s.results.length).toBe(3);
176 const over = events.find(e => e.type === 'over');
177 expect(over.total).toBe(s.total);
178 expect(over.total).toBeGreaterThanOrEqual(WIN_AT);
179 expect(over.win).toBe(true);
180 expect(s.record).toBe(true);
181 run(s, 1, false);
182 const fresh = again(s);
183 expect(fresh.race).toBe(0);
184 expect(fresh.total).toBe(0);
185 expect(fresh.best).toBe(s.total);
186 });
187
188 test('six or more is a win and anything below is a loss', () => {
189 expect(WIN_AT).toBe(6);
190 expect(isWin(6)).toBe(true);
191 expect(isWin(9)).toBe(true);
192 expect(isWin(5)).toBe(false);
193 expect(isWin(0)).toBe(false);
194 // through the real finish of the last race with 5 banked: third place adds 1 and wins, last adds 0 and loses
195 const fin = i => TOTAL / rivalPace(i, 2);
196 const last = time => {
197 const s = newGame(); s.race = 2; s.total = 5; s.phase = 'race'; s.dist = TOTAL - .001; s.v = 5; s.nextBend = 6; s.time = time;
198 return advance(s, DT, true).find(e => e.type === 'over');
199 };
200 expect(last((fin(0) + fin(1)) / 2).win).toBe(true);
201 expect(last(fin(0) + 1).win).toBe(false);
202 });
203
204 test('the racing line closes into an oval and turns with its bends', () => {
205 const a = pointAt(0), b = pointAt(LENGTH);
206 expect(b.x).toBeCloseTo(a.x, 6);
207 expect(b.y).toBeCloseTo(a.y, 6);
208 const mid = pointAt(bendDistance(0) + ARC / 2);
209 expect(mid.heading).toBeCloseTo(Math.PI / 2, 6);
210 expect(pointAt(10, 1).y).toBeGreaterThan(pointAt(10, 0).y);
211 });
212
213 test('bad numbers never break a race', () => {
214 const s = newGame();
215 advance(s, NaN, true);
216 advance(s, -1, true);
217 advance(s, Infinity, true);
218 expect(Number.isFinite(s.dist)).toBe(true);
219 expect(Number.isFinite(s.v)).toBe(true);
220 expect(pointsFor(NaN)).toBe(3);
221 });
index.html +1
@@ -90,6 +90,7 @@ footer a::after { content: none; }
9090 <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>
9191 <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>
9292 <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="Hold" style="--accent:#e0a526"><a href="go-kart/">Go-Kart Fete</a><span>Hold to race, let go for the bends: three laps round the hay bales against three rivals</span><span>Game forged by the crew</span><span class="tags">Racing · Hold</span></li>
9394 <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>
9495 </ul>
9596 <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>
og/go-kart.png added
Binary file not shown.
og/home.png
Binary file not shown.
serve.test.mjs +7
@@ -422,3 +422,10 @@ test('Espresso Bar and its rules script are served without a track', async () =>
422422 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
423423 expect((await fetch(base + '/espresso-bar/pour.js')).status).toBe(200);
424424 });
425
426 test('Go-Kart Fete and its rules script are served without a track', async () => {
427 const page = await fetch(base + '/go-kart/');
428 expect(page.status).toBe(200);
429 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
430 expect((await fetch(base + '/go-kart/lap.js')).status).toBe(200);
431 });
shell.js +1
@@ -34,6 +34,7 @@ window.PixelPlays = (() => {
3434 { 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 },
3535 { 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 },
3636 { 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: 'go-kart', title: 'Go-Kart Fete', blurb: 'Hold to race, let go for the bends: three laps round the hay bales against three rivals', kind: 'Racing', input: 'Hold', accent: '#e0a526', music: false, forged: true },
3738 { 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 },
3839 ];
3940 const MUSIC_VOLUME = .4;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs