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

Migrated from github.com/amirmushichge/pixel-plays

Curling Rink rules: a tested `curling/rink.js` that slides stones down the ice with sweeping and collisions, from plain data #194

Merged opened this

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

Merged

torque/pixel-plays:torque/178-curling-rink-rules-a-tested-curling-rink → main 3 commits fork

  • Merged. torque/178-curling-rink-rules-a-tested-curling-rink was merged into main as 2b8d368.

Review

Sign in to review this change.
2 files changed +317 −0
curling/rink.js added +151
@@ -0,0 +1,151 @@
1 'use strict';
2 // The Curling Rink rules: slide eight stones down a sheet of ice toward the house, sweeping to carry them further,
3 // against a seeded set of opponent stones already in play. Plain data in, plain data out, no DOM, no timers, no
4 // Math.random: the opponent stones come from the seed. A refused throw returns the very same state and says why.
5 //
6 // Units: metres, seconds, degrees. x runs across the sheet (0 = left side line), y runs down the ice (0 = where you
7 // release, LENGTH = the back line). The button (the centre of the house) is at (WIDTH / 2, BUTTON_Y).
8 // Physics: constant kinetic friction, a = mu * g (Coulomb), so a stone slides v^2 / (2a) before it stops; sweeping
9 // lowers mu. Curl is a small acceleration at right angles to the velocity. Collisions are elastic between equal
10 // masses: the velocity components along the line of centres are exchanged (momentum and energy are conserved).
11 (function (root) {
12 const WIDTH = 4.75; // m, the sheet between the side lines
13 const LENGTH = 38; // m, release point to the back line
14 const BUTTON_Y = 34; // m, the button
15 const HOUSE = 1.83; // m, radius of the house (12 ft)
16 const RADIUS = 0.145; // m, radius of a stone
17 const STONES = 8; // stones you throw
18 const WIN = 2; // points at or above this win the end
19 const FRICTION = 0.12; // m/s^2 deceleration on plain ice
20 const SWEPT = 0.08; // m/s^2 deceleration while sweeping
21 const CURL = 0.004; // m/s^2 sideways at curl = 1
22 const MAX_SPEED = 4.5; // m/s at power = 1
23 const MAX_ANGLE = 5; // degrees either side of straight down the ice
24 const STOP = 0.02; // m/s, slower than this a stone is at rest
25 const MAX_DT = 0.1; // s, the longest step tick takes (longer is clamped)
26 const SUB = 0.01; // s, the substep that keeps a fast stone from skipping another
27 const RANGE = { angle: [-MAX_ANGLE, MAX_ANGLE], power: [0, 1], curl: [-1, 1] };
28
29 const finite = v => (Number.isFinite(v) ? v : 0);
30 // a repeatable number in [0, 1) for this seed and slot
31 function noise(seed, n) {
32 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
33 h = Math.imul(h ^ (h >>> 13), 1274126177);
34 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
35 }
36 const lerp = (a, b, t) => a + (b - a) * t;
37 const round = v => Math.round(v * 1e6) / 1e6;
38 const clamp = (v, [lo, hi]) => Math.min(hi, Math.max(lo, v));
39 const toButton = s => Math.hypot(s.x - WIDTH / 2, s.y - BUTTON_Y);
40 const moving = s => s.stones.some(t => t.vx !== 0 || t.vy !== 0);
41 const copy = s => Object.assign({}, s, { stones: s.stones.map(t => Object.assign({}, t)) });
42
43 // Four opponent stones for a seed: two guards in front of the house and two inside it, on opposite sides of the
44 // centre line through the button so they never overlap.
45 function opponents(seed) {
46 const at = (id, x, y) => ({ id, team: 'opp', x: round(x), y: round(y), vx: 0, vy: 0, curl: 0 });
47 const out = [];
48 out.push(at('o0', lerp(1.6, WIDTH - 1.6, noise(seed, 1)), lerp(22, 25, noise(seed, 2))));
49 out.push(at('o1', lerp(1.6, WIDTH - 1.6, noise(seed, 3)), lerp(27, 30, noise(seed, 4))));
50 for (let i = 0; i < 2; i++) {
51 const a = lerp(0.3, Math.PI - 0.3, noise(seed, 5 + 2 * i)) + i * Math.PI;
52 const r = lerp(0.6, 1.5, noise(seed, 6 + 2 * i));
53 out.push(at('o' + (2 + i), WIDTH / 2 + r * Math.cos(a), BUTTON_Y + r * Math.sin(a)));
54 }
55 return out;
56 }
57
58 // Points as curling counts them: your stones inside the house nearer the button than every opponent stone inside
59 // the house. A stone counts as in the house when any part of it touches the ring (centre within HOUSE + RADIUS).
60 function score(stones) {
61 const inHouse = stones.filter(s => toButton(s) <= HOUSE + RADIUS);
62 const best = Math.min(Infinity, ...inHouse.filter(s => s.team === 'opp').map(toButton));
63 return inHouse.filter(s => s.team === 'you' && toButton(s) < best).length;
64 }
65
66 function refresh(s) {
67 s.thrown = s.stones.filter(t => t.id[0] === 'y').length + s.lost;
68 s.left = STONES - s.thrown;
69 if (s.status !== 'playing') {
70 s.line = s.status === 'won' ? `You scored ${s.points}: a win (${WIN} or more needed)`
71 : `You scored ${s.points}: a loss (${WIN} or more needed)`;
72 } else {
73 s.line = moving(s) ? 'A stone is sliding: sweep to carry it further' : `${s.left} of ${STONES} stones left to throw`;
74 }
75 return s;
76 }
77 function start(seed = 1) {
78 seed = finite(seed) >>> 0;
79 return refresh({ seed, stones: opponents(seed), lost: 0, status: 'playing', points: 0, why: '', line: '', thrown: 0, left: 0 });
80 }
81
82 const refuse = (s, why) => ({ ok: false, why, state: s });
83 // Release a stone from the middle of the sheet. Each value is clamped to its range; anything but a finite number is refused.
84 function throwStone(state, { angle, power, curl } = {}) {
85 if (state.status !== 'playing') return refuse(state, 'over');
86 for (const [k, v] of Object.entries({ angle, power, curl })) {
87 if (typeof v !== 'number' || !Number.isFinite(v)) return refuse(state, 'not-a-number:' + k);
88 }
89 if (moving(state)) return refuse(state, 'sliding');
90 if (state.left <= 0) return refuse(state, 'no-stones');
91 const a = clamp(angle, RANGE.angle) * Math.PI / 180, speed = clamp(power, RANGE.power) * MAX_SPEED;
92 const s = copy(state);
93 s.stones.push({ id: 'y' + s.thrown, team: 'you', x: WIDTH / 2, y: 0, vx: speed * Math.sin(a), vy: speed * Math.cos(a), curl: clamp(curl, RANGE.curl) });
94 if (speed < STOP) { const t = s.stones[s.stones.length - 1]; t.vx = t.vy = 0; }
95 return { ok: true, why: '', state: refresh(s) };
96 }
97
98 // One substep: friction, curl, motion, collisions, then the lines.
99 function step(s, h, sweeping) {
100 const a = sweeping ? SWEPT : FRICTION;
101 for (const t of s.stones) {
102 const v = Math.hypot(t.vx, t.vy);
103 if (v === 0) continue;
104 const nv = v - a * h;
105 if (nv < STOP) { t.vx = t.vy = 0; continue; }
106 const ux = t.vx / v, uy = t.vy / v;
107 t.vx = ux * nv + -uy * t.curl * CURL * h; // curl pushes at right angles to the direction of travel
108 t.vy = uy * nv + ux * t.curl * CURL * h;
109 t.x += t.vx * h; t.y += t.vy * h;
110 }
111 const n = s.stones.length;
112 for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) {
113 const p = s.stones[i], q = s.stones[j];
114 const dx = q.x - p.x, dy = q.y - p.y, d = Math.hypot(dx, dy);
115 if (d >= 2 * RADIUS || d === 0) continue;
116 const nx = dx / d, ny = dy / d;
117 const rel = (p.vx - q.vx) * nx + (p.vy - q.vy) * ny; // closing speed along the line of centres
118 if (rel > 0) { // equal masses, elastic: swap the normal components
119 p.vx -= rel * nx; p.vy -= rel * ny; q.vx += rel * nx; q.vy += rel * ny;
120 }
121 const push = (2 * RADIUS - d) / 2; // unstick the overlap
122 p.x -= nx * push; p.y -= ny * push; q.x += nx * push; q.y += ny * push;
123 }
124 // past the back line or over a side line (centre beyond it): out of play
125 const out = s.stones.filter(t => t.y > LENGTH || t.x < 0 || t.x > WIDTH);
126 if (out.length) {
127 s.lost += out.filter(t => t.team === 'you').length;
128 s.stones = s.stones.filter(t => !out.includes(t));
129 }
130 }
131
132 // Advance every moving stone by dt seconds (clamped to MAX_DT). Deterministic for a fixed dt and sweeping.
133 // When the last stone has stopped after the last throw, the end is scored.
134 function tick(state, dt, sweeping = false) {
135 if (state.status !== 'playing') return state;
136 dt = Number.isFinite(dt) ? Math.min(MAX_DT, Math.max(0, dt)) : 0;
137 const s = refresh(copy(state));
138 if (moving(s) && dt > 0) {
139 for (let left = dt; left > 1e-12; left -= SUB) step(s, Math.min(SUB, left), !!sweeping);
140 for (const t of s.stones) { t.x = round(t.x); t.y = round(t.y); }
141 }
142 if (!moving(s) && s.left <= 0) {
143 s.points = score(s.stones);
144 s.status = s.points >= WIN ? 'won' : 'lost';
145 }
146 return refresh(s);
147 }
148
149 const api = { WIDTH, LENGTH, BUTTON_Y, HOUSE, RADIUS, STONES, WIN, FRICTION, SWEPT, CURL, MAX_SPEED, MAX_ANGLE, STOP, RANGE, start, throw: throwStone, tick, score };
150 if (typeof module !== 'undefined') module.exports = api; else root.Curling = api;
151 })(typeof window !== 'undefined' ? window : globalThis);
curling/rink.test.mjs added +166
@@ -0,0 +1,166 @@
1 import { test, expect } from 'bun:test';
2 import * as C from './rink.js';
3 const { WIDTH, BUTTON_Y, HOUSE, STONES, WIN, RANGE, start, tick, score } = C;
4 const cast = C.default ?? C;
5 const throwStone = cast.throw;
6
7 const bare = () => Object.assign(start(1), { stones: [] });
8 const stone = (id, team, x, y) => ({ id, team, x, y, vx: 0, vy: 0, curl: 0 });
9 const run = (s, sweeping = () => false, max = 6000) => { for (let i = 0; i < max && s.stones.some(t => t.vx || t.vy); i++) s = tick(s, 0.05, sweeping(i)); return s; };
10 const lastY = s => s.stones[s.stones.length - 1].y;
11
12 test('the same seed gives the same sheet, other seeds differ, and no stones overlap', () => {
13 expect(start(7).stones).toEqual(start(7).stones);
14 expect(start(7).stones).not.toEqual(start(8).stones);
15 for (const seed of [1, 2, 3, 99, 12345]) {
16 const o = start(seed).stones;
17 expect(o).toHaveLength(4);
18 for (const a of o) { expect(a.x).toBeGreaterThan(0); expect(a.x).toBeLessThan(WIDTH); expect(a.team).toBe('opp'); }
19 for (let i = 0; i < 4; i++) for (let j = i + 1; j < 4; j++) expect(Math.hypot(o[i].x - o[j].x, o[i].y - o[j].y)).toBeGreaterThan(2 * C.RADIUS);
20 }
21 });
22
23 test('a throw that is not a finite number is refused and leaves the state alone', () => {
24 const s = start(1);
25 for (const bad of [{ angle: 'x', power: 0.5, curl: 0 }, { angle: 0, power: NaN, curl: 0 }, { angle: 0, power: 0.5, curl: Infinity }, { angle: 0, power: 0.5 }, undefined]) {
26 const r = throwStone(s, bad);
27 expect(r.ok).toBe(false);
28 expect(r.state).toBe(s);
29 }
30 });
31
32 test('angle, power and curl are clamped to their ranges', () => {
33 const r = throwStone(bare(), { angle: 90, power: 5, curl: -9 });
34 const t = r.state.stones[0];
35 expect(r.ok).toBe(true);
36 expect(t.curl).toBe(RANGE.curl[0]);
37 expect(Math.hypot(t.vx, t.vy)).toBeCloseTo(C.MAX_SPEED, 9);
38 expect(Math.atan2(t.vx, t.vy) * 180 / Math.PI).toBeCloseTo(C.MAX_ANGLE, 9);
39 });
40
41 test('tick is deterministic for a fixed dt', () => {
42 const s = throwStone(start(3), { angle: 0.4, power: 0.8, curl: 0.5 }).state;
43 expect(run(s)).toEqual(run(s));
44 });
45
46 test('a plain stone slides v^2 / (2a): the hand calculation', () => {
47 const s = run(throwStone(bare(), { angle: 0, power: 0.6, curl: 0 }).state);
48 const v = 0.6 * C.MAX_SPEED;
49 expect(lastY(s)).toBeCloseTo(v * v / (2 * C.FRICTION), 0); // 2.7 m/s -> 30.4 m
50 });
51
52 test('sweeping carries a stone further than not sweeping', () => {
53 const t = throwStone(bare(), { angle: 0, power: 0.5, curl: 0 }).state;
54 expect(lastY(run(t, () => true))).toBeGreaterThan(lastY(run(t)) + 5);
55 });
56
57 test('curl bends the path sideways', () => {
58 const t = throwStone(bare(), { angle: 0, power: 0.6, curl: 1 }).state;
59 expect(Math.abs(run(t).stones[0].x - WIDTH / 2)).toBeGreaterThan(0.3);
60 });
61
62 test('a collision moves the struck stone and slows the striker', () => {
63 const s = bare(); s.stones.push(stone('o0', 'opp', WIDTH / 2, 20));
64 const r = run(throwStone(s, { angle: 0, power: 0.6, curl: 0 }).state);
65 const opp = r.stones.find(t => t.id === 'o0'), you = r.stones.find(t => t.id === 'y0');
66 expect(opp.y).toBeGreaterThan(25);
67 expect(you.y).toBeLessThan(opp.y);
68 });
69
70 test('a stone over the back line or a side line is removed and still counts as thrown', () => {
71 const back = run(throwStone(bare(), { angle: 0, power: 1, curl: 0 }).state, () => true);
72 expect(back.stones).toHaveLength(0);
73 expect(back.left).toBe(STONES - 1);
74 const side = run(throwStone(bare(), { angle: 5, power: 0.6, curl: 0 }).state);
75 expect(side.stones).toHaveLength(0);
76 });
77
78 test('scoring: your stones nearer the button than every opponent stone in the house', () => {
79 const cx = WIDTH / 2;
80 const set = [stone('y0', 'you', cx, BUTTON_Y + 0.2), stone('y1', 'you', cx + 0.5, BUTTON_Y), stone('y2', 'you', cx - 1, BUTTON_Y),
81 stone('o0', 'opp', cx, BUTTON_Y - 0.7), stone('o1', 'opp', cx, BUTTON_Y - 5)];
82 expect(score(set)).toBe(2); // y0 and y1 beat 0.7; y2 is behind it
83 expect(score([stone('y0', 'you', cx, BUTTON_Y + HOUSE + 1), stone('o0', 'opp', cx, BUTTON_Y + 1)])).toBe(0);
84 expect(score([stone('y0', 'you', cx, BUTTON_Y + 1)])).toBe(1); // no opponent in the house
85 });
86
87 test('the end reports a win at WIN points and a loss below', () => {
88 const cx = WIDTH / 2;
89 const ended = stones => tick(Object.assign(bare(), { stones, lost: STONES - stones.filter(t => t.team === 'you').length }), 0.05);
90 const win = ended([stone('y0', 'you', cx, BUTTON_Y), stone('y1', 'you', cx + 0.3, BUTTON_Y), stone('o0', 'opp', cx, BUTTON_Y - 1)]);
91 expect(win.points).toBe(WIN);
92 expect(win.status).toBe('won');
93 expect(win.line).toContain('win');
94 const loss = ended([stone('y0', 'you', cx, BUTTON_Y), stone('o0', 'opp', cx, BUTTON_Y - 1)]);
95 expect(loss.points).toBe(1);
96 expect(loss.status).toBe('lost');
97 expect(loss.line).toContain('loss');
98 expect(throwStone(loss, { angle: 0, power: 0.5, curl: 0 }).why).toBe('over');
99 });
100
101 test('a whole end of eight throws plays through to a verdict', () => {
102 let s = start(5);
103 for (let i = 0; i < STONES; i++) {
104 const r = throwStone(s, { angle: 0, power: 0.62, curl: 0 });
105 expect(r.ok).toBe(true);
106 s = run(r.state);
107 }
108 expect(['won', 'lost']).toContain(s.status);
109 expect(throwStone(s, { angle: 0, power: 0.5, curl: 0 }).ok).toBe(false);
110 });
111
112 const shot = { angle: 0, power: 0.5, curl: 0 };
113
114 test('a throw while a stone is sliding is refused as sliding and returns the same state', () => {
115 const s = throwStone(bare(), shot).state;
116 const r = throwStone(s, shot);
117 expect(r.ok).toBe(false);
118 expect(r.why).toBe('sliding');
119 expect(r.state).toBe(s);
120 });
121
122 test('a throw with no stones left in a game still playing is refused as no-stones', () => {
123 const s = Object.assign(bare(), { lost: STONES });
124 expect(s.status).toBe('playing');
125 const r = throwStone(refreshed(s), shot);
126 expect(r.ok).toBe(false);
127 expect(r.why).toBe('no-stones');
128 expect(r.state.left).toBe(0);
129 });
130 function refreshed(s) { return Object.assign(s, { left: STONES - s.lost - s.stones.filter(t => t.team === 'you').length }); }
131
132 test('tick clamps a long dt to 0.1 s, and a NaN, infinite or negative dt changes nothing', () => {
133 const s = throwStone(bare(), { angle: 0, power: 0.5, curl: 0.3 }).state;
134 expect(tick(s, 5)).toEqual(tick(s, 0.1));
135 expect(tick(s, 0.1).stones[0].y).toBeGreaterThan(0);
136 for (const dt of [NaN, -1, Infinity, -Infinity, undefined]) expect(tick(s, dt)).toEqual(tick(s, 0));
137 expect(tick(s, 0).stones[0].y).toBe(0);
138 });
139
140 test('tick leaves a finished end untouched', () => {
141 const s = Object.assign(bare(), { status: 'won', points: 2 });
142 s.stones.push(Object.assign(stone('y0', 'you', 2, 10), { vy: 1 }));
143 expect(tick(s, 0.1)).toBe(s);
144 expect(s.stones[0].y).toBe(10);
145 });
146
147 test('throw and tick return new state and do not mutate their input', () => {
148 const s = start(4);
149 const before = structuredClone(s);
150 const r = throwStone(s, shot);
151 expect(s).toEqual(before);
152 expect(r.state).not.toBe(s);
153 expect(r.state.stones).not.toBe(s.stones);
154 const moving = r.state, snap = structuredClone(moving);
155 const next = tick(moving, 0.1, true);
156 expect(moving).toEqual(snap);
157 expect(next).not.toBe(moving);
158 expect(next.stones[next.stones.length - 1].y).toBeGreaterThan(0);
159 });
160
161 test('the refusal reason names the key that is not a number', () => {
162 const s = start(1);
163 expect(throwStone(s, { angle: 'x', power: 0.5, curl: 0 }).why).toBe('not-a-number:angle');
164 expect(throwStone(s, { angle: 0, power: NaN, curl: 0 }).why).toBe('not-a-number:power');
165 expect(throwStone(s, { angle: 0, power: 0.5 }).why).toBe('not-a-number:curl');
166 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs