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

Migrated from github.com/amirmushichge/pixel-plays

Snail Race rules: a tested `snail-race/race.js` where you pace a snail down a garden lane against three rivals, spending slime for bursts, from plain data, with a test file that runs in under a second #255

Merged opened this

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

Merged

torque/pixel-plays:torque/239-snail-race-rules-a-tested-snail-race-rac → main 1 commit fork

  • Merged. torque/239-snail-race-rules-a-tested-snail-race-rac was merged into main as 75183a4.

Review

Sign in to review this change.
2 files changed +258 −0
snail-race/race.js added +160
@@ -0,0 +1,160 @@
1 'use strict';
2 // The Snail Race rules: four snails race down a garden lane; you step in time with the beat to keep your snail moving
3 // and spend slime on bursts, while three seeded rivals keep their own pace.
4 // Plain data in, plain data out, no DOM, no timers, no Math.random: the rivals come from the seed.
5 // A rejected call returns the very same state and says why. The page (not yet written) draws what this decides.
6 //
7 // Time is in seconds, distance in centimetres, speed in cm/s. The beat falls at every multiple of BEAT seconds; a step
8 // is on the beat when it lands within WINDOW seconds of the nearest one. An on-beat step raises your speed by
9 // STEP_UP and refills REFILL slime; an off-beat step lowers your speed by STEP_DOWN. Speed stays between FLOOR and CAP.
10 // A burst costs BURST_COST slime and adds BURST_BOOST cm/s on top of your speed for BURST_TIME seconds (the boost is
11 // outside the cap); it is refused while one is running. A rival's speed is
12 // v(t) = base * (1 + swing * sin(2*pi*t/period + phase))
13 // whose integral is the closed form used in rivalPos, so a rival's place does not depend on how time is sliced.
14 (function (root) {
15 const LANE = 60; // cm, the lane length
16 const RIVALS = 3; // seeded rivals
17 const BEAT = 0.5; // seconds between beats
18 const WINDOW = 0.1; // seconds either side of a beat that count as on the beat
19 const START_SPEED = 1; // cm/s
20 const FLOOR = 0.5; // cm/s, slowest your snail goes
21 const CAP = 2; // cm/s, fastest from stepping alone
22 const STEP_UP = 0.15; // cm/s gained by an on-beat step
23 const STEP_DOWN = 0.25; // cm/s lost by an off-beat step
24 const SLIME = 100; // the slime supply
25 const BURST_COST = 40; // slime a burst spends
26 const BURST_BOOST = 1.5; // cm/s added while a burst runs
27 const BURST_TIME = 3; // seconds a burst runs
28 const REFILL = 5; // slime back per on-beat step, up to SLIME
29 const MIN_BASE = 1.1; // cm/s, slowest rival base pace
30 const MAX_BASE = 1.6; // cm/s, fastest rival base pace
31 const MAX_SWING = 0.4; // largest swing of a rival's pace (under 1: never moves backwards)
32 const MIN_PERIOD = 6; // seconds, shortest pace curve cycle
33 const MAX_PERIOD = 14; // seconds, longest pace curve cycle
34 const NAMES = ['Mossy', 'Dash', 'Pebble'];
35
36 const finite = v => (Number.isFinite(v) ? v : 0);
37 // a repeatable number in [0, 1) for this seed and slot
38 function noise(seed, n) {
39 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
40 h = Math.imul(h ^ (h >>> 13), 1274126177);
41 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
42 }
43 const round3 = v => Math.round(v * 1000) / 1000;
44 const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
45
46 // distance a rival has covered by time t: the integral of v(t) from 0 to t
47 function rivalPos(r, t) {
48 const w = 2 * Math.PI / r.period;
49 return r.base * t + (r.base * r.swing / w) * (Math.cos(r.phase) - Math.cos(w * t + r.phase));
50 }
51 // the time a rival crosses the line (rivalPos only rises, so bisection finds it)
52 function finishOf(r, lane) {
53 let lo = 0, hi = lane / (r.base * (1 - r.swing)) + 1;
54 for (let i = 0; i < 60; i++) { const m = (lo + hi) / 2; if (rivalPos(r, m) >= lane) hi = m; else lo = m; }
55 return round3(hi);
56 }
57
58 // rivals(seed) -> [{ id, name, base, swing, period, phase, finish }]
59 function rivals(seed) {
60 const out = [];
61 for (let i = 0; i < RIVALS; i++) {
62 const r = {
63 id: i + 1, name: NAMES[i],
64 base: round3(MIN_BASE + noise(seed, i * 4) * (MAX_BASE - MIN_BASE)),
65 swing: round3(noise(seed, i * 4 + 1) * MAX_SWING),
66 period: round3(MIN_PERIOD + noise(seed, i * 4 + 2) * (MAX_PERIOD - MIN_PERIOD)),
67 phase: round3(noise(seed, i * 4 + 3) * 2 * Math.PI),
68 };
69 r.finish = finishOf(r, LANE);
70 out.push(r);
71 }
72 return out;
73 }
74
75 // the places so far: finished snails in order of finish time (ties to the lower id), you are id 0
76 function refresh(s) {
77 s.snails = [{ id: 0, name: 'You', pos: round3(s.pos), finish: s.finish }].concat(
78 s.rivals.map(r => ({ id: r.id, name: r.name, pos: round3(Math.min(s.lane, rivalPos(r, s.time))), finish: s.time >= r.finish ? r.finish : null })));
79 const done = s.snails.filter(n => n.finish !== null).sort((a, b) => a.finish - b.finish || a.id - b.id);
80 s.places = s.status === 'over' ? done.map((n, i) => ({ place: i + 1, id: n.id, name: n.name, time: n.finish })) : [];
81 if (s.status === 'over') {
82 const mine = s.places.find(p => p.id === 0);
83 s.place = mine.place; s.yourTime = mine.time; s.won = mine.place === 1;
84 s.line = s.won ? `You win in ${s.yourTime} s` : `You lose: place ${s.place} of ${s.places.length} in ${s.yourTime} s`;
85 } else {
86 s.line = `${round3(s.pos)} of ${s.lane} cm, ${round3(s.speed)} cm/s, slime ${s.slime} of ${s.supply}`;
87 }
88 return s;
89 }
90
91 const start = (seed = 1) => {
92 const sd = finite(seed) >>> 0;
93 return refresh({
94 seed: sd, lane: LANE, supply: SLIME, beat: BEAT, window: WINDOW, floor: FLOOR, cap: CAP,
95 burstCost: BURST_COST, burstBoost: BURST_BOOST, burstTime: BURST_TIME, refill: REFILL,
96 rivals: rivals(sd), time: 0, pos: 0, speed: START_SPEED, slime: SLIME, boost: 0, finish: null,
97 status: 'racing', won: false, place: 0, yourTime: 0, places: [], snails: [], line: '',
98 });
99 };
100
101 const copy = s => Object.assign({}, s);
102 const refuse = (s, why) => ({ ok: false, why, event: '', state: s });
103
104 // tick(state, dt) -> { ok, why, event, state }: dt seconds pass and every snail moves. event is '', 'won' or 'lost'
105 // (the race ends when every snail has crossed the line). dt must be a finite number above 0.
106 function tick(s, dt) {
107 if (s.status !== 'racing') return refuse(s, 'over');
108 if (typeof dt !== 'number' || !Number.isFinite(dt) || dt <= 0) return refuse(s, 'bad-dt');
109 const n = copy(s);
110 let left = dt, t = n.time;
111 while (left > 1e-12 && n.finish === null) { // your snail, in stretches of constant speed
112 const seg = n.boost > 0 ? Math.min(left, n.boost) : left;
113 const v = n.speed + (n.boost > 0 ? n.burstBoost : 0);
114 if (n.pos + v * seg >= n.lane) { n.finish = round3(t + (n.lane - n.pos) / v); n.pos = n.lane; }
115 else n.pos += v * seg;
116 n.boost = Math.max(0, n.boost - seg); t += seg; left -= seg;
117 }
118 n.boost = Math.max(0, n.boost - left);
119 n.time = round3(s.time + dt);
120 let event = '';
121 if (n.finish !== null && n.rivals.every(r => n.time >= r.finish)) {
122 n.status = 'over';
123 n.time = Math.max(n.finish, ...n.rivals.map(r => r.finish));
124 }
125 refresh(n);
126 if (n.status === 'over') event = n.won ? 'won' : 'lost';
127 return { ok: true, why: '', event, state: n };
128 }
129
130 // step(state) -> { ok, why, event, state }: you step now. event is 'on-beat' (speed up, slime refilled) or 'off-beat'
131 // (speed down). Refused once your snail has crossed the line.
132 function step(s) {
133 if (s.status !== 'racing') return refuse(s, 'over');
134 if (s.finish !== null) return refuse(s, 'finished');
135 const n = copy(s);
136 const into = n.time % n.beat;
137 const on = Math.min(into, n.beat - into) <= n.window + 1e-9;
138 n.speed = round3(clamp(n.speed + (on ? STEP_UP : -STEP_DOWN), n.floor, n.cap));
139 if (on) n.slime = Math.min(n.supply, n.slime + n.refill);
140 return { ok: true, why: '', event: on ? 'on-beat' : 'off-beat', state: refresh(n) };
141 }
142
143 // burst(state) -> { ok, why, event, state }: spends burstCost slime for burstBoost cm/s for burstTime seconds.
144 // Refused with 'slime-short' when slime is short, and with 'bursting' while a burst is running.
145 function burst(s) {
146 if (s.status !== 'racing') return refuse(s, 'over');
147 if (s.finish !== null) return refuse(s, 'finished');
148 if (s.boost > 0) return refuse(s, 'bursting');
149 if (s.slime < s.burstCost) return refuse(s, 'slime-short');
150 const n = copy(s);
151 n.slime -= n.burstCost; n.boost = n.burstTime;
152 return { ok: true, why: '', event: 'burst', state: refresh(n) };
153 }
154
155 const api = {
156 LANE, RIVALS, BEAT, WINDOW, START_SPEED, FLOOR, CAP, STEP_UP, STEP_DOWN, SLIME, BURST_COST, BURST_BOOST, BURST_TIME,
157 REFILL, rivals, rivalPos, start, tick, step, burst,
158 };
159 if (typeof module !== 'undefined') module.exports = api; else root.SnailRace = api;
160 })(typeof window !== 'undefined' ? window : globalThis);
snail-race/race.test.mjs added +98
@@ -0,0 +1,98 @@
1 import { test, expect } from 'bun:test';
2 import {
3 LANE, RIVALS, BEAT, WINDOW, START_SPEED, FLOOR, CAP, STEP_UP, STEP_DOWN, SLIME, BURST_COST, BURST_BOOST, BURST_TIME,
4 REFILL, rivals, rivalPos, start, tick, step, burst,
5 } from './race.js';
6
7 const at = (s, time, over = {}) => ({ ...s, time, ...over });
8 const run = (s, secs, dt = 0.5) => { for (let t = 0; t < secs && s.status === 'racing'; t += dt) s = tick(s, dt).state; return s; };
9
10 test('the same seed gives the same rivals, other seeds differ, and the stated sizes hold', () => {
11 expect(start(7)).toEqual(start(7));
12 expect(rivals(7)).toHaveLength(RIVALS);
13 const seen = new Set();
14 for (let seed = 1; seed <= 20; seed++) seen.add(JSON.stringify(rivals(seed)));
15 expect(seen.size).toBeGreaterThan(10);
16 const s = start(3);
17 expect([s.lane, s.supply, s.slime, s.speed, s.rivals.length]).toEqual([LANE, SLIME, SLIME, START_SPEED, 3]);
18 for (const r of s.rivals) expect(rivalPos(r, r.finish)).toBeCloseTo(LANE, 1);
19 });
20
21 test('a rival matches the hand-worked pace curve and does not depend on how time is sliced', () => {
22 const r = { base: 1.5, swing: 0, period: 10, phase: 0 };
23 expect(rivalPos(r, 4)).toBeCloseTo(6, 9); // constant 1.5 cm/s for 4 s
24 const w = { base: 1, swing: 0.5, period: 2 * Math.PI, phase: 0 }; // v = 1 + 0.5 sin t, integral t + 0.5 (1 - cos t)
25 expect(rivalPos(w, Math.PI)).toBeCloseTo(Math.PI + 1, 9);
26 const a = run(start(5), 20, 0.5), b = run(start(5), 20, 0.25);
27 expect(a.snails.slice(1)).toEqual(b.snails.slice(1));
28 });
29
30 test('your snail moves at its speed, and a burst adds its boost only for its time', () => {
31 let s = tick(start(1), 2).state; // 1 cm/s for 2 s
32 expect(s.pos).toBeCloseTo(2, 9);
33 s = burst(s).state;
34 s = tick(s, BURST_TIME + 1).state; // (1 + 1.5) * 3 + 1 * 1
35 expect(s.pos).toBeCloseTo(2 + 2.5 * 3 + 1, 9);
36 expect(s.boost).toBe(0);
37 });
38
39 test('an on-beat step raises speed, an off-beat step lowers it, always within floor and cap', () => {
40 const s = start(1);
41 const on = step(at(s, BEAT * 3 + WINDOW)); // edge of the window still counts
42 expect([on.ok, on.event, on.state.speed]).toEqual([true, 'on-beat', START_SPEED + STEP_UP]);
43 expect(step(at(s, BEAT * 3 - WINDOW)).event).toBe('on-beat');
44 const off = step(at(s, BEAT / 2));
45 expect([off.event, off.state.speed]).toEqual(['off-beat', START_SPEED - STEP_DOWN]);
46 let hi = s; for (let i = 0; i < 20; i++) hi = step(at(hi, i * BEAT)).state;
47 expect(hi.speed).toBe(CAP);
48 let lo = s; for (let i = 0; i < 20; i++) lo = step(at(lo, i * BEAT + BEAT / 2)).state;
49 expect(lo.speed).toBe(FLOOR);
50 });
51
52 test('a burst spends slime for the boost, is refused when slime is short or one is running', () => {
53 const b = burst(start(1));
54 expect([b.ok, b.event, b.state.slime, b.state.boost]).toEqual([true, 'burst', SLIME - BURST_COST, BURST_TIME]);
55 expect(BURST_BOOST).toBe(b.state.burstBoost);
56 const again = burst(b.state);
57 expect([again.ok, again.why, again.state]).toEqual([false, 'bursting', b.state]);
58 const short = burst(at(start(1), 0, { slime: BURST_COST - 1 }));
59 expect([short.ok, short.why, short.state.slime]).toEqual([false, 'slime-short', BURST_COST - 1]);
60 expect(burst(at(start(1), 0, { slime: BURST_COST })).ok).toBe(true);
61 });
62
63 test('slime refills per on-beat step up to the supply, and not on an off-beat step', () => {
64 const low = at(start(1), 0, { slime: 10 });
65 expect(step(low).state.slime).toBe(10 + REFILL);
66 expect(step(at(low, BEAT / 2)).state.slime).toBe(10);
67 expect(step(at(start(1), 0, { slime: SLIME - 1 })).state.slime).toBe(SLIME);
68 });
69
70 test('bad calls are refused with the same state', () => {
71 const s = start(1);
72 for (const dt of [0, -1, NaN, Infinity, '1']) expect(tick(s, dt)).toEqual({ ok: false, why: 'bad-dt', event: '', state: s });
73 });
74
75 test('the race ends when every snail crosses: places in order, your time, win and loss lines', () => {
76 const slow = start(2);
77 const lost = run(slow, 1000);
78 expect(lost.status).toBe('over');
79 expect(lost.places.map(p => p.place)).toEqual([1, 2, 3, 4]);
80 const times = lost.places.map(p => p.time);
81 expect(times).toEqual([...times].sort((a, b) => a - b));
82 expect(lost.place).toBeGreaterThan(1);
83 expect([lost.won, lost.line.startsWith('You lose')]).toEqual([false, true]);
84 expect(tick(lost, 1).why).toBe('over');
85
86 // stand still at the floor: last; ride a huge speed: first
87 const fast = start(2);
88 fast.speed = 1000;
89 const r = tick(fast, 0.5).state; // you cross at once, rivals have not
90 expect(r.status).toBe('racing');
91 expect(r.snails[0].finish).toBe(0.06);
92 expect(step(r).why).toBe('finished');
93 const won = run(r, 1000);
94 expect([won.place, won.won, won.yourTime, won.line]).toEqual([1, true, 0.06, 'You win in 0.06 s']);
95 expect(tick(r, 0.5).event).toBe('');
96 expect(run(r, 1000).time).toBe(Math.max(...won.rivals.map(x => x.finish)));
97 expect(tick(at(run(r, 1000), 0), 1).why).toBe('over');
98 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs