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

Migrated from github.com/amirmushichge/pixel-plays

Dinghy Race rules: a tested `dinghy-race/dinghy.js` that plays a whole game from plain data #121

Merged opened this

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

Merged

torque/pixel-plays:torque/109-dinghy-race-rules-a-tested-dinghy-race-d → main 1 commit fork

  • Merged. torque/109-dinghy-race-rules-a-tested-dinghy-race-d was merged into main as 0e7807c.

Review

Sign in to review this change.
2 files changed +320 −0
dinghy-race/dinghy.js added +126
@@ -0,0 +1,126 @@
1 'use strict';
2 // The dinghy race rules: one boat, two seeded rivals, three buoys and back over the line.
3 // Metres, seconds, degrees. Compass bearings: 0 is north (+y), 90 is east (+x). Wind is the bearing it blows FROM.
4 // Plain data in, plain data out, no DOM, no timers, no Math.random: every chance comes from the seed.
5 (function (root) {
6 const TOP_SPEED = 7; // m/s: the boat at the best sail angle on its best point of sail
7 const NO_GO = 25; // degrees off the wind inside which the sail only luffs: zero speed
8 // speed factor by angle to the wind (degrees): dead to windward, close-hauled, beam reach, broad reach (best), dead downwind
9 const POLAR = [[NO_GO, 0], [45, .55], [90, .9], [135, 1], [180, .8]];
10 const TRIM_WIDTH = 40; // degrees of sail error at which the boat is stopped: factor 1 - (err/40)^2
11 const SAIL_MAX = 90;
12 const BASE_WIND = 135, MAX_SHIFT = 10; // wind from the south-east; each buoy shifts it by up to +/-10 degrees
13 const LEG = 120, BUOY_RADIUS = 6, MAX_TIME = 300; // metres per leg; rounding radius; the race is called off after this long
14 const START = { x: 0, y: 0 };
15 const BUOYS = [{ x: 0, y: LEG }, { x: -LEG, y: LEG }, { x: -LEG, y: 0 }]; // then back east over the line at START
16 const TARGETS = [...BUOYS, START];
17 const RIVAL_BASE = 3.7, RIVAL_SPREAD = .5; // m/s: rival pace is fixed for the race, in [3.7, 4.2)
18 const RIVALS = 2;
19 const RESTART_AFTER = .6;
20
21 const finite = v => (Number.isFinite(v) ? v : 0);
22 const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
23 // a repeatable number in [0, 1) for this seed and slot
24 function noise(seed, n) {
25 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
26 h = Math.imul(h ^ (h >>> 13), 1274126177);
27 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
28 }
29 const norm = d => ((finite(d) % 360) + 360) % 360;
30 // the angle between a heading and the wind's bearing, 0 (head to wind) to 180 (dead downwind)
31 function windAngle(heading, wind) {
32 const d = Math.abs(norm(heading) - norm(wind));
33 return d > 180 ? 360 - d : d;
34 }
35 // bearing from a to b
36 const bearing = (a, b) => norm(Math.atan2(b.x - a.x, b.y - a.y) * 180 / Math.PI);
37 const dist = (a, b) => Math.hypot(b.x - a.x, b.y - a.y);
38
39 // how much of TOP_SPEED the hull offers at this angle to the wind: straight lines through POLAR
40 function polar(angle) {
41 const a = clamp(finite(angle), 0, 180);
42 if (a <= NO_GO) return 0;
43 for (let i = 1; i < POLAR.length; i++) {
44 const [a1, f1] = POLAR[i], [a0, f0] = POLAR[i - 1];
45 if (a <= a1) return f0 + (f1 - f0) * (a - a0) / (a1 - a0);
46 }
47 return POLAR[POLAR.length - 1][1];
48 }
49 // the sail angle (degrees from the centreline) that drives best at this angle to the wind: half of it
50 const bestSail = angle => clamp(finite(angle), 0, 180) / 2;
51 // boat speed in m/s: a pure function of sail angle, heading and wind
52 function boatSpeed(sail, heading, wind) {
53 const angle = windAngle(heading, wind), err = clamp(finite(sail), 0, SAIL_MAX) - bestSail(angle);
54 return TOP_SPEED * polar(angle) * Math.max(0, 1 - (err / TRIM_WIDTH) ** 2);
55 }
56 // the wind after buoy n (1..3 are the buoys, 0 is the start): the base wind turned by a seeded amount in [-10, 10)
57 const windAt = (n, seed = 0) => (n <= 0 ? BASE_WIND : BASE_WIND + (noise(seed, 200 + n) * 2 - 1) * MAX_SHIFT);
58 const rivalPace = (i, seed = 0) => RIVAL_BASE + noise(seed, 300 + i) * RIVAL_SPREAD;
59
60 // course distance up to the start of each leg, and the whole course
61 const LEG_START = [0]; { let p = START; for (const t of TARGETS) { LEG_START.push(LEG_START[LEG_START.length - 1] + dist(p, t)); p = t; } }
62 const COURSE = LEG_START[TARGETS.length];
63 const legFrom = n => (n === 0 ? START : TARGETS[n - 1]);
64 const progress = s => LEG_START[s.buoy] + dist(legFrom(s.buoy), TARGETS[s.buoy]) - dist(s, TARGETS[s.buoy]);
65
66 function newRound(best = 0, seed = 0) {
67 seed = finite(seed) >>> 0;
68 return {
69 phase: 'play', over: false, outcome: '', line: '', score: 0, timer: 0,
70 x: START.x, y: START.y, heading: bearing(START, TARGETS[0]), wind: windAt(0, seed), speed: 0, sail: 0,
71 buoy: 0, place: 1, time: 0, best: Math.max(0, finite(best)), record: false, seed,
72 rivals: Array.from({ length: RIVALS }, (_, i) => ({ pace: rivalPace(i, seed), progress: 0 })),
73 };
74 }
75 // 1 + the rivals strictly ahead, by distance along the course
76 function placeNow(s) {
77 const mine = progress(s);
78 return 1 + s.rivals.filter(r => r.progress > mine).length;
79 }
80 const PLACE_WORD = ['', 'First', 'Second', 'Third'];
81 function finish(s, events, called) {
82 if (called) s.place = placeNow(s);
83 s.phase = 'over'; s.over = true; s.timer = 0;
84 // a rival beats us if it crossed the line sooner; a called-off race is placed by distance
85 if (!called) s.place = 1 + s.rivals.filter(r => COURSE / r.pace < s.time).length;
86 s.outcome = s.place <= 2 ? 'won' : 'lost';
87 s.score = RIVALS + 1 - s.place; // 2 for first, 1 for second, 0 for third
88 s.line = `${PLACE_WORD[s.place]} place${called ? ', race called off' : ` in ${s.time.toFixed(1)} s`}: ${s.outcome === 'won' ? 'a win' : 'a loss'}`;
89 if (s.outcome === 'won' && !called && (!s.best || s.time < s.best)) { s.best = s.time; s.record = true; }
90 events.push({ type: s.outcome, place: s.place, time: s.time, record: s.record });
91 }
92 // sail for dt seconds; input.sail is the sail angle you trim to, 0 to 90 degrees
93 function advance(s, dt, input) {
94 const events = [];
95 dt = clamp(finite(dt), 0, .1);
96 if (s.phase !== 'play') { s.timer += dt; return events; }
97 s.time += dt;
98 s.sail = clamp(finite(input && input.sail), 0, SAIL_MAX);
99 for (const r of s.rivals) r.progress = Math.min(COURSE, r.pace * s.time);
100 const target = TARGETS[s.buoy], last = s.buoy === TARGETS.length - 1;
101 s.heading = bearing(s, target);
102 s.speed = boatSpeed(s.sail, s.heading, s.wind);
103 const d = dist(s, target), reach = last ? 0 : BUOY_RADIUS, step = Math.min(s.speed * dt, d);
104 if (d > 0) { s.x += (target.x - s.x) / d * step; s.y += (target.y - s.y) / d * step; }
105 if (d - step <= reach) {
106 if (last) { s.x = target.x; s.y = target.y; finish(s, events, false); return events; }
107 s.x = target.x; s.y = target.y; // rounded: the next leg starts from the buoy
108 s.buoy++;
109 s.wind = windAt(s.buoy, s.seed);
110 events.push({ type: 'buoy', buoy: s.buoy, wind: s.wind });
111 }
112 s.place = placeNow(s);
113 if (s.time >= MAX_TIME) finish(s, events, true);
114 return events;
115 }
116 // a tap after the race has been over for a moment starts the next one; otherwise null
117 function again(s) {
118 return s.phase === 'over' && s.timer > RESTART_AFTER ? newRound(s.best, s.seed + 1) : null;
119 }
120
121 const api = {
122 TOP_SPEED, NO_GO, POLAR, TRIM_WIDTH, SAIL_MAX, BASE_WIND, MAX_SHIFT, LEG, BUOY_RADIUS, MAX_TIME, BUOYS, COURSE, RIVALS, RESTART_AFTER,
123 windAngle, polar, bestSail, boatSpeed, windAt, rivalPace, progress, newRound, advance, again,
124 };
125 if (typeof module !== 'undefined') module.exports = api; else root.Dinghy = api;
126 })(typeof window !== 'undefined' ? window : globalThis);
dinghy-race/dinghy.test.mjs added +194
@@ -0,0 +1,194 @@
1 import { test, expect } from 'bun:test';
2 import { NO_GO, TOP_SPEED, BASE_WIND, MAX_SHIFT, MAX_TIME, COURSE, windAngle, polar, bestSail, boatSpeed, windAt, rivalPace, newRound, advance, again } from './dinghy.js';
3
4 // sail one race at 30 steps a second; trim(state) gives the sail angle to hold, null stops at the time limit
5 const race = (seed, trim, best = 0) => {
6 const s = newRound(best, seed), events = [];
7 for (let i = 0; i < 12000 && !s.over; i++) events.push(...advance(s, 1 / 30, { sail: trim(s) }));
8 return { s, events };
9 };
10 const perfect = s => bestSail(windAngle(s.heading, s.wind));
11 const stuck = () => 45; // a sail never touched, set for a beam reach and left there
12
13 test('the angle to the wind is folded to 0..180 whichever way round', () => {
14 expect(windAngle(10, 350)).toBe(20);
15 expect(windAngle(350, 10)).toBe(20);
16 expect(windAngle(0, 180)).toBe(180);
17 expect(windAngle(-90, 450)).toBe(180);
18 });
19
20 test('speed is greatest at the best sail angle for the heading, which is half the angle to the wind', () => {
21 for (const heading of [60, 90, 180, 270, 0]) {
22 const a = windAngle(heading, 135), best = bestSail(a);
23 expect(best).toBe(a / 2);
24 const top = boatSpeed(best, heading, 135);
25 expect(top).toBeCloseTo(TOP_SPEED * polar(a), 9);
26 for (const off of [-30, -10, -1, 1, 10, 30]) {
27 if (best + off >= 0 && best + off <= 90) expect(boatSpeed(best + off, heading, 135)).toBeLessThan(top);
28 }
29 }
30 });
31
32 test('speed falls off either side of the best angle, the further the slower', () => {
33 const h = 270, best = bestSail(windAngle(h, 135)); // 67.5 degrees of sail on a broad reach
34 const at = d => boatSpeed(best + d, h, 135);
35 expect(at(5)).toBeGreaterThan(at(15));
36 expect(at(15)).toBeGreaterThan(at(22));
37 expect(at(-5)).toBeGreaterThan(at(-15));
38 expect(at(-15)).toBeGreaterThan(at(-22));
39 expect(at(-10)).toBeCloseTo(at(10), 9);
40 // a sail sheeted right in stops the boat; let right out it is well short of full speed
41 expect(boatSpeed(0, h, 135)).toBe(0);
42 expect(boatSpeed(90, h, 135)).toBeLessThan(at(0) * .75);
43 });
44
45 test('pointing head to wind stops the boat dead, whatever the sail', () => {
46 for (const sail of [0, 5, 12, 45, 90]) expect(boatSpeed(sail, 135, 135)).toBe(0);
47 expect(boatSpeed(0, 135 + NO_GO, 135)).toBe(0); // the edge of the no-go zone
48 expect(boatSpeed(bestSail(NO_GO + 5), 135 + NO_GO + 5, 135)).toBeGreaterThan(0);
49 expect(polar(0)).toBe(0);
50 });
51
52 test('close-hauled is slower than a reach, and a broad reach is the fastest point of sail', () => {
53 const v = a => boatSpeed(bestSail(a), a, 0);
54 expect(v(45)).toBeLessThan(v(90));
55 expect(v(90)).toBeLessThan(v(135));
56 expect(v(180)).toBeLessThan(v(135));
57 });
58
59 test('junk input is held in range and never makes speed NaN', () => {
60 expect(boatSpeed(NaN, NaN, NaN)).toBe(0);
61 expect(Number.isFinite(boatSpeed(Infinity, 90, 135))).toBe(true);
62 const s = newRound(NaN, NaN);
63 advance(s, NaN, { sail: 'x' });
64 advance(s, 1, null);
65 expect(Number.isFinite(s.x) && Number.isFinite(s.y)).toBe(true);
66 });
67
68 test('the wind shifts by a seeded amount at each buoy, and not before', () => {
69 expect(windAt(0, 3)).toBe(BASE_WIND);
70 const s = newRound(0, 3);
71 expect(s.wind).toBe(BASE_WIND);
72 const winds = [];
73 for (let i = 0; i < 12000 && !s.over; i++) {
74 for (const e of advance(s, 1 / 30, { sail: perfect(s) })) if (e.type === 'buoy') winds.push(e.wind);
75 if (!winds.length) expect(s.wind).toBe(BASE_WIND);
76 }
77 expect(winds).toEqual([1, 2, 3].map(n => windAt(n, 3)));
78 for (const w of winds) expect(Math.abs(w - BASE_WIND)).toBeLessThanOrEqual(MAX_SHIFT);
79 expect(new Set(winds).size).toBe(3);
80 // same seed, same shifts; another seed, other shifts
81 expect(windAt(2, 3)).toBe(windAt(2, 3));
82 expect(windAt(2, 4)).not.toBe(windAt(2, 3));
83 });
84
85 test('no seed ever shifts the wind into the no-go zone on any leg', () => {
86 const legs = [0, 270, 180, 90]; // bearings of the four legs
87 for (let seed = 0; seed < 500; seed++) legs.forEach((h, i) => expect(windAngle(h, windAt(i, seed))).toBeGreaterThan(NO_GO + 5));
88 });
89
90 test('rivals sail a fixed seeded pace', () => {
91 expect(rivalPace(0, 7)).toBe(rivalPace(0, 7));
92 expect(rivalPace(0, 7)).not.toBe(rivalPace(1, 7));
93 const s = newRound(0, 7);
94 advance(s, .1, { sail: 0 }); advance(s, .1, { sail: 90 });
95 expect(s.rivals.map(r => r.progress)).toEqual([0, 1].map(i => rivalPace(i, 7) * .2)); // the player's trim does not touch them
96 });
97
98 test('a race is three buoys and back over the line, reporting buoy, place, time and best', () => {
99 const s = newRound(0, 2);
100 expect(s).toMatchObject({ phase: 'play', over: false, buoy: 0, place: 1, time: 0, best: 0, score: 0, outcome: '' });
101 const seen = [];
102 while (!s.over) { advance(s, 1 / 30, { sail: perfect(s) }); if (seen[seen.length - 1] !== s.buoy) seen.push(s.buoy); }
103 expect(seen).toEqual([0, 1, 2, 3]);
104 expect(s.phase).toBe('over');
105 expect(s.time).toBeGreaterThan(COURSE / TOP_SPEED);
106 expect([s.x, s.y]).toEqual([0, 0]);
107 });
108
109 test('a scripted trim that beats the rivals wins, takes first place and sets the best time', () => {
110 const { s, events } = race(2, perfect);
111 expect(s.place).toBe(1);
112 expect(s.outcome).toBe('won');
113 expect(s.score).toBe(2);
114 expect(s.line).toContain('First place');
115 expect(s.line).toContain('a win');
116 expect(s.record).toBe(true);
117 expect(s.best).toBe(s.time);
118 expect(s.time).toBeLessThan(COURSE / Math.max(rivalPace(0, 2), rivalPace(1, 2)));
119 expect(events.at(-1)).toMatchObject({ type: 'won', place: 1 });
120 });
121
122 test('second place is still a win and keeps a better earlier best', () => {
123 // find a seed where a mediocre trim lands second
124 let found = null;
125 for (let seed = 0; seed < 200 && !found; seed++) {
126 const { s } = race(seed, x => bestSail(windAngle(x.heading, x.wind)) + 12);
127 if (s.place === 2) found = { seed };
128 }
129 expect(found).not.toBeNull();
130 const { s } = race(found.seed, x => bestSail(windAngle(x.heading, x.wind)) + 12, 1);
131 expect(s.outcome).toBe('won');
132 expect(s.score).toBe(1);
133 expect(s.best).toBe(1);
134 expect(s.record).toBe(false);
135 });
136
137 test('a scripted trim that loses finishes third and is a loss', () => {
138 const { s, events } = race(0, stuck);
139 expect(s.over).toBe(true);
140 expect(s.place).toBe(3);
141 expect(s.outcome).toBe('lost');
142 expect(s.score).toBe(0);
143 expect(s.line).toContain('Third place');
144 expect(s.line).toContain('a loss');
145 expect(s.record).toBe(false);
146 expect(s.best).toBe(0);
147 expect(events.at(-1)).toMatchObject({ type: 'lost', place: 3 });
148 expect(s.time).toBeGreaterThan(COURSE / Math.min(rivalPace(0, 0), rivalPace(1, 0)));
149 });
150
151 test('place during the race follows the rivals by distance along the course', () => {
152 const s = newRound(0, 0);
153 for (let i = 0; i < 30 * 20; i++) advance(s, 1 / 30, { sail: perfect(s) });
154 expect(s.place).toBe(1); // fast trim leads after 20 s
155 const t = newRound(0, 0);
156 for (let i = 0; i < 30 * 20; i++) advance(t, 1 / 30, { sail: 0 });
157 expect(t.place).toBe(3); // sail sheeted in goes nowhere
158 });
159
160 test('a boat that never moves is called off at the time limit and placed by distance', () => {
161 const { s } = race(0, () => 0);
162 expect(s.over).toBe(true);
163 expect(s.time).toBeGreaterThanOrEqual(MAX_TIME);
164 expect(s.outcome).toBe('lost');
165 expect(s.line).toContain('called off');
166 expect(s.record).toBe(false);
167 });
168
169 test('the same seed and trim replay the same race', () => {
170 const a = race(5, perfect).s, b = race(5, perfect).s;
171 expect(b).toEqual(a);
172 });
173
174 test('a finished race ignores sailing, and a tap restarts it only after a moment', () => {
175 const { s } = race(2, perfect);
176 const time = s.time;
177 advance(s, .05, { sail: 40 });
178 expect(s.time).toBe(time);
179 expect(again(s)).toBeNull();
180 for (let i = 0; i < 40; i++) advance(s, .05, {});
181 const next = again(s);
182 expect(next.phase).toBe('play');
183 expect(next.best).toBe(s.best);
184 expect(next.seed).toBe(s.seed + 1);
185 expect(again(next)).toBeNull();
186 });
187
188 test('the rules load as a plain script with a window global and no DOM', async () => {
189 const src = await Bun.file(new URL('./dinghy.js', import.meta.url)).text();
190 const win = {};
191 new Function('window', 'module', src.replace("typeof window !== 'undefined' ? window : globalThis", 'window'))(win, undefined);
192 expect(typeof win.Dinghy.advance).toBe('function');
193 expect(src.replace(/\/\/.*$/gm, '')).not.toMatch(/Math\.random|document\.|setTimeout|setInterval|requestAnimationFrame/);
194 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs