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

Migrated from github.com/amirmushichge/pixel-plays

Duck Race rules: a tested `duck-race/stream.js` where you steer a rubber duck across stream lanes past rocks and eddies against three rivals, from plain data, in a two-file pull with a test file that runs in under a second #260

Merged opened this

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

Merged

vesper/pixel-plays:vesper/248-duck-race-rules-a-tested-duck-race-strea → main 2 commits fork 1 thread · 1 unresolved

  • Merged. vesper/248-duck-race-rules-a-tested-duck-race-strea was merged into main as 366d3b1.

Review

Sign in to review this change.
2 files changed +352 −0
duck-race/stream.js added +183
@@ -0,0 +1,183 @@
1 'use strict';
2 // The Duck Race rules: four rubber ducks race down a stream, and you steer yours across the lanes around rocks and
3 // out of eddies to reach the bridge first.
4 // Plain data in, plain data out, no DOM, no timers, no Math.random: the stream and the rivals come from the seed.
5 // A rejected call returns the very same state and says why.
6 //
7 // Time is in seconds, distance in stream units from the start line (0) to the bridge (LENGTH). Lanes are numbered
8 // 0 to LANES - 1 across the stream. Every duck drifts downstream at BASE_SPEED times its pace; fast water in its lane
9 // multiplies that by FAST_FACTOR. An eddy holds a duck, spinning in place, for EDDY_HOLD seconds. A rock stops a duck
10 // where it hits until it changes lane. Obstacles sit on their own 5-unit slots, so no two share a spot.
11 (function (root) {
12 const LENGTH = 100; // stream units from the start line to the bridge
13 const LANES = 5; // lanes across the stream
14 const TIME_LIMIT = 60; // seconds, then the race ends with whoever has passed
15 const BASE_SPEED = 5; // stream units per second at pace 1
16 const FAST_FACTOR = 1.5; // speed multiplier in fast water
17 const FAST_LENGTH = 12; // length of a patch of fast water
18 const FAST_PATCHES = 8; // patches of fast water in the stream
19 const EDDY_HOLD = 1.5; // seconds an eddy holds a duck
20 const STEER_COOLDOWN = 0.4; // seconds steering is refused after a lane change
21 const SLOT = 5; // spacing of obstacle slots
22 const FIRST_SLOT = 2; // no obstacle before this slot, so the start is clear
23 const OBSTACLE_CHANCE = 0.6; // chance a slot holds a rock or an eddy
24 const ROCK_SHARE = 0.6; // of the obstacles, the share that are rocks
25 const LOOKAHEAD = 7; // units ahead a rival looks for trouble
26 const RIVALS = 3; // rival ducks
27 const PACE_MIN = 0.9; // slowest rival pace
28 const PACE_MAX = 1.1; // fastest rival pace
29 const WIN_SCORE = 100; // points for first place
30 const CLEAN_BONUS = 50; // extra points for first place without touching a rock
31 const STEP = 0.05; // seconds, the finest slice a tick is cut into
32 const START_LANES = [2, 0, 4, 1]; // you, then the rivals
33
34 const finite = v => (Number.isFinite(v) ? v : 0);
35 // a repeatable number in [0, 1) for this seed and slot
36 function noise(seed, n) {
37 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
38 h = Math.imul(h ^ (h >>> 13), 1274126177);
39 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
40 }
41 const round3 = v => Math.round(v * 1000) / 1000;
42 const ordinal = n => ['1st', '2nd', '3rd', '4th'][n - 1] || `${n}th`;
43
44 // layout(seed) -> { obstacles: [{ id, kind: 'rock' | 'eddy', lane, at }], fast: [{ lane, from, to }], paces: [..] }
45 // paces holds one pace per rival; the same seed always gives the same layout.
46 function layout(seed) {
47 const obstacles = [], fast = [], paces = [];
48 let slot = 0;
49 for (let k = FIRST_SLOT; k < LENGTH / SLOT; k++) {
50 if (noise(seed, slot++) >= OBSTACLE_CHANCE) continue;
51 const kind = noise(seed, slot++) < ROCK_SHARE ? 'rock' : 'eddy';
52 const lane = Math.floor(noise(seed, slot++) * LANES);
53 obstacles.push({ id: obstacles.length, kind, lane, at: k * SLOT });
54 }
55 for (let i = 0; i < FAST_PATCHES; i++) {
56 const lane = Math.floor(noise(seed, 500 + i * 2) * LANES);
57 const from = round3(noise(seed, 501 + i * 2) * (LENGTH - FAST_LENGTH));
58 fast.push({ lane, from, to: round3(from + FAST_LENGTH) });
59 }
60 for (let r = 0; r < RIVALS; r++) paces.push(round3(PACE_MIN + noise(seed, 900 + r) * (PACE_MAX - PACE_MIN)));
61 return { obstacles, fast, paces };
62 }
63
64 // the way rival id (1 to RIVALS) turns on its nth lane change: -1 or 1, a pure function of the seed
65 const rivalTurn = (seed, id, n) => (noise(seed, 1000 + id * 100 + n) < 0.5 ? -1 : 1);
66
67 const inFast = (s, d) => s.fast.some(f => f.lane === d.lane && d.x >= f.from && d.x < f.to);
68 const speedOf = (s, d) => BASE_SPEED * d.pace * (inFast(s, d) ? FAST_FACTOR : 1);
69
70 // change lanes: returns '' when it moved, else why not
71 function shift(d, dir, cooldown) {
72 if (d.cooldown > 0) return 'cooldown';
73 const lane = d.lane + dir;
74 if (lane < 0 || lane >= LANES) return 'bank';
75 d.lane = lane; d.cooldown = cooldown; d.stuck = false;
76 return '';
77 }
78
79 // a rival turns away by its seeded rule, the other way if that is the bank, when it is stuck on a rock or sees the
80 // next unhit rock or eddy in its lane within LOOKAHEAD; it waits out its cooldown first
81 function rivalThink(s, d) {

Excludes the rock the rival is already stuck on, so a stuck rival has no ahead and never changes lane. Let a stuck rival turn when its cooldown is 0, whether or not an unhit obstacle is ahead, and test it.

82 if (d.cooldown > 0) return;
83 const ahead = s.obstacles.find(o => o.lane === d.lane && o.at >= d.x && o.at - d.x <= LOOKAHEAD && !d.hit.includes(o.id));
84 if (!ahead && !d.stuck) return;
85 const dir = rivalTurn(s.seed, d.id, d.turns);
86 if (shift(d, dir, STEER_COOLDOWN) === 'bank') shift(d, -dir, STEER_COOLDOWN);
87 d.turns += 1;
88 }
89
90 // move one duck for h seconds starting at time t0; returns nothing, sets finishTime when it crosses the bridge
91 function advance(s, d, h, t0) {
92 d.cooldown = Math.max(0, d.cooldown - h);
93 if (d.id !== 0) rivalThink(s, d);
94 if (d.held > 0) { d.held = Math.max(0, d.held - h); return; }
95 if (d.stuck) return;
96 const x0 = d.x, x1 = x0 + speedOf(s, d) * h;
97 const o = s.obstacles.find(q => q.lane === d.lane && q.at > x0 && q.at <= x1 && !d.hit.includes(q.id));
98 if (o && o.at < LENGTH) {
99 d.x = o.at; d.hit.push(o.id);
100 if (o.kind === 'rock') { d.stuck = true; d.rocks += 1; } else d.held = EDDY_HOLD;
101 return;
102 }
103 d.x = x1;
104 if (x1 >= LENGTH) { d.x = LENGTH; d.finishTime = t0 + h * ((LENGTH - x0) / (x1 - x0)); }
105 }
106
107 // the finishing order: ducks that passed the bridge by finish time, then the rest by how far they got
108 function ranking(s) {
109 return s.ducks.slice().sort((a, b) =>
110 (a.finishTime === null) - (b.finishTime === null) ||
111 (a.finishTime !== null ? a.finishTime - b.finishTime : b.x - a.x) || a.id - b.id).map(d => d.id);
112 }
113
114 function refresh(s) {
115 s.order = ranking(s);
116 s.place = s.order.indexOf(0) + 1;
117 const me = s.ducks[0];
118 if (s.status === 'over') {
119 s.won = s.place === 1;
120 s.score = s.won ? WIN_SCORE + (me.rocks === 0 ? CLEAN_BONUS : 0) : 0;
121 s.line = s.won
122 ? `You win: ${ordinal(s.place)} of ${s.ducks.length}, ${s.score} points${me.rocks === 0 ? ' with the clean-run bonus' : ''}`
123 : `You lose: ${ordinal(s.place)} of ${s.ducks.length}, ${s.score} points`;
124 } else {
125 s.line = `${ordinal(s.place)} of ${s.ducks.length}, ${round3(Math.max(0, LENGTH - me.x))} units to the bridge`;
126 }
127 return s;
128 }
129
130 const duck = (id, lane, pace) => ({
131 id, lane, x: 0, pace, cooldown: 0, held: 0, stuck: false, rocks: 0, hit: [], turns: 0, finishTime: null,
132 });
133
134 const start = (seed = 1) => {
135 const sd = finite(seed) >>> 0;
136 const { obstacles, fast, paces } = layout(sd);
137 const ducks = [duck(0, START_LANES[0], 1)];
138 for (let r = 0; r < RIVALS; r++) ducks.push(duck(r + 1, START_LANES[r + 1], paces[r]));
139 return refresh({
140 seed: sd, length: LENGTH, lanes: LANES, timeLimit: TIME_LIMIT, obstacles, fast, ducks,
141 time: 0, status: 'playing', won: false, score: 0, place: 1, order: [], line: '',
142 });
143 };
144
145 const copy = s => Object.assign({}, s, { ducks: s.ducks.map(d => Object.assign({}, d, { hit: d.hit.slice() })) });
146 const refuse = (s, why) => ({ ok: false, why, event: '', state: s });
147
148 // tick(state, dt) -> { ok, why, event, state }: dt seconds pass and every duck is carried downstream. event is '',
149 // 'won' or 'lost' on the tick that ends the race. dt must be a finite number above 0.
150 function tick(s, dt) {
151 if (s.status !== 'playing') return refuse(s, 'over');
152 if (typeof dt !== 'number' || !Number.isFinite(dt) || dt <= 0) return refuse(s, 'bad-dt');
153 const n = copy(s);
154 let left = dt;
155 while (left > 1e-9 && n.status === 'playing') {
156 const h = Math.min(STEP, left, n.timeLimit - n.time);
157 for (const d of n.ducks) if (d.finishTime === null) advance(n, d, h, n.time);
158 n.time += h; left -= h;
159 if (n.ducks.every(d => d.finishTime !== null) || n.time >= n.timeLimit - 1e-9) n.status = 'over';
160 }
161 n.time = round3(n.time);
162 refresh(n);
163 return { ok: true, why: '', event: n.status === 'over' ? (n.won ? 'won' : 'lost') : '', state: n };
164 }
165
166 // steer(state, dir) -> { ok, why, event, state }: your duck moves one lane, -1 towards lane 0 or 1 away from it.
167 // Refused past the banks, during the cooldown after a lane change, and once your duck is across the bridge.
168 function steer(s, dir) {
169 if (s.status !== 'playing') return refuse(s, 'over');
170 if (dir !== -1 && dir !== 1) return refuse(s, 'bad-dir');
171 if (s.ducks[0].finishTime !== null) return refuse(s, 'finished');
172 const n = copy(s);
173 const why = shift(n.ducks[0], dir, STEER_COOLDOWN);
174 if (why) return refuse(s, why);
175 return { ok: true, why: '', event: 'steered', state: refresh(n) };
176 }
177
178 const api = {
179 LENGTH, LANES, TIME_LIMIT, BASE_SPEED, FAST_FACTOR, EDDY_HOLD, STEER_COOLDOWN, RIVALS, LOOKAHEAD, WIN_SCORE,
180 CLEAN_BONUS, layout, rivalTurn, start, tick, steer,
181 };
182 if (typeof module !== 'undefined') module.exports = api; else root.DuckRace = api;
183 })(typeof window !== 'undefined' ? window : globalThis);
duck-race/stream.test.mjs added +169
@@ -0,0 +1,169 @@
1 import { test, expect } from 'bun:test';
2 import {
3 LENGTH, LANES, TIME_LIMIT, BASE_SPEED, FAST_FACTOR, EDDY_HOLD, STEER_COOLDOWN, RIVALS, LOOKAHEAD, WIN_SCORE,
4 CLEAN_BONUS, layout, rivalTurn, start, tick, steer,
5 } from './stream.js';
6
7 // a stream with hand-placed obstacles, so each rule is checked against a count done by hand
8 const rigged = (obstacles = [], fast = [], over = {}) => {
9 const s = start(1);
10 return { ...s, obstacles, fast, ...over, ducks: s.ducks.map(d => ({ ...d, pace: 1 })) };
11 };
12 const run = (s, t) => tick(s, t).state;
13 const me = s => s.ducks[0];
14
15 test('the same seed gives the same stream and rivals, other seeds differ, and the stated sizes hold', () => {
16 expect(start(7)).toEqual(start(7));
17 expect(run(start(7), 12)).toEqual(run(start(7), 12));
18 const seen = new Set();
19 for (let seed = 1; seed <= 20; seed++) seen.add(JSON.stringify(layout(seed)));
20 expect(seen.size).toBeGreaterThan(10);
21 const s = start(3);
22 expect([s.length, s.lanes, s.timeLimit, s.ducks.length]).toEqual([LENGTH, LANES, TIME_LIMIT, RIVALS + 1]);
23 for (const d of s.ducks) { expect(d.x).toBe(0); expect(d.lane).toBeGreaterThanOrEqual(0); expect(d.lane).toBeLessThan(LANES); }
24 expect(new Set(s.ducks.map(d => d.lane)).size).toBe(4);
25 for (const o of s.obstacles) { expect(['rock', 'eddy']).toContain(o.kind); expect(o.at).toBeGreaterThan(5); expect(o.at).toBeLessThan(LENGTH); }
26 expect(new Set(s.obstacles.map(o => o.at)).size).toBe(s.obstacles.length);
27 });
28
29 test('a duck drifts at its lane current, and fast water speeds it up by the stated factor', () => {
30 const plain = run(rigged(), 2);
31 expect(me(plain).x).toBeCloseTo(2 * BASE_SPEED, 9);
32 const fastLane = me(rigged()).lane;
33 const quick = run(rigged([], [{ lane: fastLane, from: 0, to: 50 }]), 2);
34 expect(me(quick).x).toBeCloseTo(2 * BASE_SPEED * FAST_FACTOR, 9);
35 const other = run(rigged([], [{ lane: (fastLane + 1) % LANES, from: 0, to: 50 }]), 2);
36 expect(me(other).x).toBeCloseTo(2 * BASE_SPEED, 9);
37 });
38
39 test('an eddy holds a duck, spinning, for the stated time and then lets it go', () => {
40 const lane = me(rigged()).lane;
41 const s = rigged([{ id: 0, kind: 'eddy', lane, at: 10 }]);
42 const held = run(s, 2 + EDDY_HOLD - 0.1); // reaches 10 at t = 2
43 expect(me(held).x).toBe(10);
44 expect(me(held).held).toBeGreaterThan(0);
45 const freed = run(held, 0.5);
46 expect(me(freed).held).toBe(0);
47 expect(me(freed).x).toBeGreaterThan(10);
48 expect(me(freed).rocks).toBe(0);
49 });
50
51 test('a rock stops a duck until it changes lane, and counts as a touch', () => {
52 const lane = me(rigged()).lane;
53 const s = rigged([{ id: 0, kind: 'rock', lane, at: 10 }]);
54 const stopped = run(s, 10);
55 expect(me(stopped).x).toBe(10);
56 expect(me(stopped).stuck).toBe(true);
57 expect(me(stopped).rocks).toBe(1);
58 expect(me(run(stopped, 5)).x).toBe(10);
59 const free = run(steer(stopped, 1).state, 1);
60 expect(me(free).stuck).toBe(false);
61 expect(me(free).x).toBeCloseTo(10 + BASE_SPEED, 9);
62 expect(me(free).rocks).toBe(1);
63 });
64
65 test('steering moves one lane, and is refused at a bank, in the cooldown, and for a bad direction', () => {
66 let s = rigged();
67 const lane = me(s).lane;
68 const r = steer(s, -1);
69 expect([r.ok, me(r.state).lane]).toEqual([true, lane - 1]);
70 expect(steer(r.state, -1)).toMatchObject({ ok: false, why: 'cooldown' });
71 expect(steer(r.state, -1).state).toBe(r.state);
72 s = run(r.state, STEER_COOLDOWN + 0.01);
73 s = steer(s, -1).state; // lane 0
74 s = run(s, STEER_COOLDOWN + 0.01);
75 expect(steer(s, -1)).toMatchObject({ ok: false, why: 'bank' });
76 const top = { ...s, ducks: s.ducks.map((d, i) => (i === 0 ? { ...d, lane: LANES - 1, cooldown: 0 } : d)) };
77 expect(steer(top, 1)).toMatchObject({ ok: false, why: 'bank' });
78 expect(steer(top, 2)).toMatchObject({ ok: false, why: 'bad-dir' });
79 expect(tick(top, 0)).toMatchObject({ ok: false, why: 'bad-dt' });
80 });
81
82 test('a rival turns away from a rock ahead by a seeded rule the test can predict', () => {
83 const s0 = rigged();
84 const rival = s0.ducks[1]; // lane 0, at the bank
85 const s = { ...s0, obstacles: [{ id: 0, kind: 'rock', lane: rival.lane, at: LOOKAHEAD - 1 }] };
86 const after = run(s, 0.05).ducks[1];
87 expect(after.lane).toBe(1); // lane 0: a turn towards the bank is reversed
88 expect(after.turns).toBe(1);
89 const mid = s0.ducks[3]; // lane 1
90 const s2 = { ...s0, obstacles: [{ id: 0, kind: 'rock', lane: mid.lane, at: LOOKAHEAD - 1 }] };
91 expect(run(s2, 0.05).ducks[3].lane).toBe(mid.lane + rivalTurn(s0.seed, 3, 0));
92 expect(rivalTurn(5, 2, 0)).toBe(rivalTurn(5, 2, 0));
93 expect(run(s2, 6)).toEqual(run(s2, 6));
94 });
95
96 test('the race ends when every duck has passed the bridge, and reports the finishing order', () => {
97 const s = rigged();
98 const mk = (i, pace) => ({ ...s.ducks[i], pace });
99 const fixed = { ...s, ducks: [mk(0, 1), mk(1, 1.1), mk(2, 0.9), mk(3, 1.05)] };
100 const mid = tick(fixed, 10);
101 expect(mid.event).toBe('');
102 expect(mid.state.status).toBe('playing');
103 const done = tick(fixed, LENGTH / BASE_SPEED / 0.9 + 1);
104 expect(done.state.status).toBe('over');
105 expect(done.state.order).toEqual([1, 3, 0, 2]);
106 expect(done.state.place).toBe(3);
107 expect(done.state.time).toBeLessThan(TIME_LIMIT);
108 expect(done.state.ducks[1].finishTime).toBeCloseTo(LENGTH / (BASE_SPEED * 1.1), 6);
109 expect(tick(done.state, 1)).toMatchObject({ ok: false, why: 'over' });
110 expect(steer(done.state, 1)).toMatchObject({ ok: false, why: 'over' });
111 });
112
113 test('the time limit ends the race too, ranking the unfinished by how far they got', () => {
114 const lane = me(rigged()).lane;
115 const s = rigged([{ id: 0, kind: 'rock', lane, at: 10 }]);
116 const end = tick(s, TIME_LIMIT + 5);
117 expect(end.state.time).toBe(TIME_LIMIT);
118 expect(end.state.status).toBe('over');
119 expect(end.state.order.slice(0, 3)).not.toContain(0);
120 expect(end.state.order[3]).toBe(0);
121 expect(end.event).toBe('lost');
122 const stalled = { ...s, ducks: s.ducks.map(d => ({ ...d, pace: 0.1 })) };
123 const slow = tick(stalled, TIME_LIMIT + 1).state;
124 expect(slow.ducks.every(d => d.finishTime === null)).toBe(true);
125 expect(slow.order[0]).toBe(1); // lane 0 rival, no rock, furthest on ties by id
126 });
127
128 test('first place scores a stated amount with a bonus for never touching a rock, and the lines say your place', () => {
129 const s = rigged();
130 const lead = { ...s, ducks: s.ducks.map((d, i) => ({ ...d, pace: i === 0 ? 1.2 : 1 })) };
131 const clean = tick(lead, 40);
132 expect(clean.event).toBe('won');
133 expect(clean.state.score).toBe(WIN_SCORE + CLEAN_BONUS);
134 expect(clean.state.line).toBe(`You win: 1st of 4, ${WIN_SCORE + CLEAN_BONUS} points with the clean-run bonus`);
135 const touched = tick({ ...lead, ducks: lead.ducks.map((d, i) => (i === 0 ? { ...d, rocks: 1 } : d)) }, 40);
136 expect(touched.state.score).toBe(WIN_SCORE);
137 expect(touched.state.line).toBe(`You win: 1st of 4, ${WIN_SCORE} points`);
138 const lag = { ...s, ducks: s.ducks.map((d, i) => ({ ...d, pace: i === 0 ? 0.95 : 1.05 - i * 0.01 })) };
139 const lost = tick(lag, 40);
140 expect(lost.event).toBe('lost');
141 expect(lost.state.place).toBe(4);
142 expect(lost.state.score).toBe(0);
143 expect(lost.state.line).toBe('You lose: 4th of 4, 0 points');
144 });
145
146 test('a rival stuck on a rock turns away once its cooldown is over, and finishes', () => {
147 const s0 = rigged();
148 const rival = s0.ducks[3]; // lane 1
149 const s = {
150 ...s0, obstacles: [{ id: 0, kind: 'rock', lane: rival.lane, at: 10 }],
151 ducks: s0.ducks.map((d, i) => (i === 3 ? { ...d, x: 10, stuck: true, rocks: 1, hit: [0], cooldown: 0.2 } : d)),
152 };
153 const waiting = run(s, 0.1).ducks[3];
154 expect([waiting.stuck, waiting.lane, waiting.x]).toEqual([true, rival.lane, 10]);
155 const freed = run(s, 0.3).ducks[3];
156 expect(freed.stuck).toBe(false);
157 expect(freed.lane).toBe(rival.lane + rivalTurn(s0.seed, 3, 0));
158 expect(tick(s, TIME_LIMIT).state.ducks[3].finishTime).not.toBeNull();
159 });
160
161 test('across seeds, no rival is left stuck on a rock at the end of a long run', () => {
162 for (let seed = 1; seed <= 40; seed++) {
163 const end = run(start(seed), TIME_LIMIT);
164 for (const d of end.ducks.slice(1)) {
165 if (d.stuck) throw new Error(`seed ${seed}: rival ${d.id} stuck at ${d.x}`);
166 }
167 expect(end.ducks.slice(1).every(d => d.finishTime !== null)).toBe(true);
168 }
169 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs