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

Migrated from github.com/amirmushichge/pixel-plays

Hoopla Stall rules: a tested `hoopla/hoop.js` that plays a whole game from plain data #147

Merged opened this

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

Merged

torque/pixel-plays:torque/134-hoopla-stall-rules-a-tested-hoopla-hoop → main 2 commits fork 1 thread · 1 unresolved

  • Merged. torque/134-hoopla-stall-rules-a-tested-hoopla-hoop was merged into main as 3f33d3f.

Review

Sign in to review this change.
2 files changed +205 −0
hoopla/hoop.js added +84
@@ -0,0 +1,84 @@
1 'use strict';
2 // The hoopla stall rules: nine prize blocks on a stepped table, eight wooden rings. Metres, degrees. A toss is an aim
3 // (degrees left of straight ahead negative, right positive) and a power (0..1). The ring lands at distance
4 // power * MAX_REACH along the aim bearing: x = d sin(aim), z = d cos(aim), z measured from the stall line.
5 // Plain data in, plain data out, no DOM, no timers, no Math.random: the layout and the little scatter come from the seed.
6 (function (root) {
7 const RINGS = 8, ROWS = 3, COLUMNS = 3, WIN_AT = 12; // a game is eight rings; a total of 12 or more wins
8 const ROW_VALUES = [1, 2, 3]; // points per row, nearest first: further back is worth more
9 const MAX_REACH = 6, MAX_AIM = 30; // m at full power; degrees either side
10 const RING_INNER = .2, RING_OUTER = .26; // m: radius of the hole and of the outside of the wooden ring
11 const BLOCK_RADIUS = .1; // m: a block's footprint, taken as a disc
12 const CLEARANCE = .04; // m: a block must fit inside the hole with this much to spare
13 const ROW_FIRST = 3, ROW_STEP = .8, COLUMN_STEP = .7, JITTER = .06; // m: nearest row, row spacing, column spacing, seeded drift
14 const STEP_HEIGHT = .15; // m: each row of the table stands this much higher than the one before
15 const SCATTER = .02; // m: the most a toss drifts either way on each axis, from the seed
16
17 const finite = v => (Number.isFinite(v) ? v : 0);
18 const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
19 // a repeatable number in [0, 1) for this seed and slot
20 function noise(seed, n) {
21 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
22 h = Math.imul(h ^ (h >>> 13), 1274126177);
23 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
24 }
25 // where a ring lands for this aim and power, before scatter: { x, z } in metres
26 function landing(aim, power) {
27 const d = clamp(finite(power), 0, 1) * MAX_REACH, a = clamp(finite(aim), -MAX_AIM, MAX_AIM) * Math.PI / 180;
28 return { x: d * Math.sin(a), z: d * Math.cos(a) };
29 }
30 // the aim and power that land a ring at (x, z), the inverse of landing, for aim helpers and tests
31 function aimFor(x, z) {
32 const d = Math.hypot(finite(x), finite(z));
33 return { aim: clamp(Math.atan2(finite(x), finite(z)) * 180 / Math.PI, -MAX_AIM, MAX_AIM), power: clamp(d / MAX_REACH, 0, 1) };
34 }
35 // the nine blocks, row by row, nearest row first; the same seed gives the same layout
36 function layout(seed = 0) {
37 const s = finite(seed) >>> 0, out = [];
38 for (let r = 0; r < ROWS; r++) for (let c = 0; c < COLUMNS; c++) {
39 const i = r * COLUMNS + c;
40 out.push({ row: r, value: ROW_VALUES[r], height: r * STEP_HEIGHT,
41 x: (c - 1) * COLUMN_STEP + (noise(s, i * 2) * 2 - 1) * JITTER,
42 z: ROW_FIRST + r * ROW_STEP + (noise(s, i * 2 + 1) * 2 - 1) * JITTER, gone: false });
43 }
44 return out;
45 }
46 // judge a ring settling at (x, z): 'scored' (block fits inside the hole with CLEARANCE), 'bounced' (the wood touches a
47 // block's edge), or 'miss' (touches nothing). The nearest block decides.
48 function judge(blocks, x, z) {
49 let hit = -1, best = Infinity;
50 blocks.forEach((b, i) => { const d = Math.hypot(b.x - x, b.z - z); if (!b.gone && d < best) { best = d; hit = i; } });
51 if (hit < 0) return { type: 'miss', block: -1 };
52 if (best + BLOCK_RADIUS + CLEARANCE <= RING_INNER) return { type: 'scored', block: hit };
53 if (best - BLOCK_RADIUS < RING_OUTER && best + BLOCK_RADIUS > RING_INNER - CLEARANCE) return { type: 'bounced', block: hit };
54 return { type: 'miss', block: -1 };
55 }
56
57 function newGame(best = 0, seed = 0) {
58 return { ringsLeft: RINGS, tossed: 0, score: 0, best: Math.max(0, finite(best)), over: false, outcome: '',
59 line: RINGS + ' rings: aim and power.', seed: finite(seed) >>> 0, blocks: layout(seed) };
60 }
61 // toss a ring: returns { state, event } and leaves the state you passed untouched
62 function toss(state, input = {}) {
63 if (state.over || state.ringsLeft <= 0) return { state, event: null };
64 const s = { ...state, blocks: state.blocks.map(b => ({ ...b })) };
65 const p = landing(input.aim, input.power);
66 const x = p.x + (noise(s.seed, 100 + s.tossed * 2) * 2 - 1) * SCATTER, z = Math.max(0, p.z + (noise(s.seed, 101 + s.tossed * 2) * 2 - 1) * SCATTER);
67 const j = judge(s.blocks, x, z);
68 s.ringsLeft--; s.tossed++;
69 let points = 0;
70 if (j.type === 'scored') { points = s.blocks[j.block].value; s.score += points; s.blocks[j.block].gone = true; s.line = 'Ring over a block: ' + points + '.'; }
71 else s.line = j.type === 'bounced' ? 'Bounced off a block.' : 'Missed everything.';
72 if (s.ringsLeft <= 0) {
73 s.over = true; s.outcome = s.score >= WIN_AT ? 'won' : 'lost'; s.best = Math.max(s.best, s.score);
74 s.line = s.outcome === 'won' ? 'You win with ' + s.score + '!' : 'Only ' + s.score + ': you need ' + WIN_AT + '.';
75 }
76 return { state: s, event: { type: j.type, block: j.block, points, x, z, ringsLeft: s.ringsLeft } };
77 }
78 // a fresh game after one has finished (new seed, best kept); null while one is in play
79 const again = state => (state.over ? newGame(state.best, state.seed + 1) : null);
80
81 const api = { RINGS, ROWS, COLUMNS, WIN_AT, ROW_VALUES, MAX_REACH, MAX_AIM, RING_INNER, RING_OUTER, BLOCK_RADIUS, CLEARANCE, SCATTER, STEP_HEIGHT,
82 landing, aimFor, layout, judge, newGame, toss, again };
83 if (typeof module !== 'undefined') module.exports = api; else root.Hoop = api;
84 })(typeof window !== 'undefined' ? window : globalThis);
hoopla/hoop.test.mjs added +121
@@ -0,0 +1,121 @@
1 import { test, expect } from 'bun:test';
2 import { RINGS, WIN_AT, ROW_VALUES, MAX_REACH, RING_INNER, RING_OUTER, BLOCK_RADIUS, CLEARANCE, SCATTER, landing, aimFor, layout, newGame, toss, again } from './hoop.js';
3
4 // toss so the ring lands `dx`, `dz` metres from the middle of block i
5 const at = (s, i, dx = 0, dz = 0) => aimFor(s.blocks[i].x + dx, s.blocks[i].z + dz);
6 const shot = (s, i, dx = 0, dz = 0) => toss(s, at(s, i, dx, dz));
7 const FIT = RING_INNER - BLOCK_RADIUS - CLEARANCE; // furthest off-centre that still scores
8
9 test('the landing point is set by aim and power', () => {
10 expect(landing(0, 1)).toEqual({ x: 0, z: MAX_REACH });
11 expect(landing(0, .5).z).toBeCloseTo(MAX_REACH / 2, 9);
12 const p = landing(30, 1);
13 expect(p.x).toBeCloseTo(MAX_REACH * .5, 9);
14 expect(p.z).toBeCloseTo(MAX_REACH * Math.cos(Math.PI / 6), 9);
15 expect(landing(-30, 1).x).toBeCloseTo(-p.x, 9);
16 expect(landing(NaN, NaN)).toEqual({ x: 0, z: 0 });
17 const back = aimFor(1, 4), q = landing(back.aim, back.power);
18 expect(q.x).toBeCloseTo(1, 9); expect(q.z).toBeCloseTo(4, 9);
19 });
20
21 test('nine blocks on a stepped table, the same seed the same layout', () => {
22 const a = layout(7);
23 expect(a.length).toBe(9);
24 expect(layout(7)).toEqual(a);
25 expect(layout(8)).not.toEqual(a);
26 expect(newGame(0, 7).blocks).toEqual(a);
27 expect(a[8].height).toBeGreaterThan(a[0].height);
28 for (const b of a) expect(b.z).toBeGreaterThan(0);
29 for (let i = 0; i < 9; i++) for (let j = i + 1; j < 9; j++)
30 expect(Math.hypot(a[i].x - a[j].x, a[i].z - a[j].z)).toBeGreaterThan(2 * RING_OUTER); // one ring can never reach two blocks
31 });
32
33 test('a ring fully over a block scores its row value', () => {
34 const s = newGame(0, 3);
35 const { state, event } = shot(s, 0, FIT - SCATTER * 1.5);
36 expect(event.type).toBe('scored');
37 expect(event.points).toBe(1);
38 expect(state.score).toBe(1);
39 expect(state.blocks[0].gone).toBe(true);
40 expect(s.blocks[0].gone).toBe(false); // the state passed in is untouched
41 });
42
43 test('a ring touching a block edge bounces off and scores nothing', () => {
44 const s = newGame(0, 3);
45 const off = (RING_INNER - BLOCK_RADIUS + RING_OUTER + BLOCK_RADIUS) / 2 - .05; // wood over the block's edge
46 const { state, event } = shot(s, 4, off);
47 expect(event.type).toBe('bounced');
48 expect(event.points).toBe(0);
49 expect(state.score).toBe(0);
50 expect(state.blocks[4].gone).toBe(false);
51 const tight = shot(s, 4, FIT + SCATTER * 1.5 + .01); // inside the clearance margin still bounces
52 expect(tight.event.type).toBe('bounced');
53 });
54
55 test('a ring that touches nothing is a miss', () => {
56 const r = toss(newGame(0, 3), { aim: 0, power: 0 });
57 expect(r.event.type).toBe('miss');
58 expect(r.state.ringsLeft).toBe(RINGS - 1);
59 });
60
61 test('blocks further back are worth more', () => {
62 expect(ROW_VALUES[0]).toBeLessThan(ROW_VALUES[1]);
63 expect(ROW_VALUES[1]).toBeLessThan(ROW_VALUES[2]);
64 const s = newGame(0, 5);
65 [[0, 1], [4, 2], [8, 3]].forEach(([i, v]) => expect(shot(s, i, 0).event.points).toBe(v));
66 });
67
68 test('eight rings end the game and further tosses do nothing', () => {
69 let s = newGame(0, 2);
70 for (let k = 0; k < RINGS; k++) { expect(s.over).toBe(false); s = toss(s, { aim: 0, power: 0 }).state; }
71 expect(s.over).toBe(true);
72 expect(s.ringsLeft).toBe(0);
73 const r = toss(s, { aim: 0, power: .5 });
74 expect(r.event).toBe(null);
75 expect(r.state).toBe(s);
76 });
77
78 test('the end reports total and best; win at the target, loss below', () => {
79 // score the back row blocks (3 each) and one more
80 const play = n => { let s = newGame(5, 1); const order = [8, 7, 6, 5, 4, 3, 2, 1]; for (let k = 0; k < RINGS; k++) s = (k < n ? shot(s, order[k]) : toss(s, { aim: 0, power: 0 })).state; return s; };
81 const short = play(4); // 3+3+3+2
82 expect(short.score).toBe(11);
83 expect(short.outcome).toBe('lost');
84 const win = play(5); // + 2
85 expect(win.score).toBe(13);
86 expect(win.score).toBeGreaterThanOrEqual(WIN_AT);
87 expect(win.outcome).toBe('won');
88 expect(win.best).toBe(13);
89 expect(win.line).toContain('win');
90 const lost = play(0);
91 expect(lost.outcome).toBe('lost');
92 expect(lost.best).toBe(5); // best kept when beaten by nothing
93 expect(lost.line).toContain(String(WIN_AT));
94 let s = newGame(0, 1); // 3+3+3+2+2+2 = 15 in six rings
95 for (const i of [8, 7, 6, 5, 4, 3]) s = shot(s, i).state;
96 expect(s.score).toBe(15);
97 });
98
99 test('again keeps the best and changes the seed, only after the end', () => {
100 expect(again(newGame(0, 1))).toBe(null);
101 let s = newGame(5, 1);
102 for (const i of [8, 7]) s = shot(s, i).state;
103 while (!s.over) s = toss(s, { aim: 0, power: 0 }).state;
104 expect(s.score).toBe(6);
105 const n = again(s);
outdated

The test title says again keeps the best, but nothing checks it. Start from newGame(5, 1), play it out, and assert again(s).best equals Math.max(5, s.score). Also assert that n.score is 0, n.over is false and n.blocks has no gone block. Without these, deleting state.best from again still passes.

106 expect(n.best).toBe(Math.max(5, s.score));
107 expect(n.seed).toBe(2);
108 expect(n.ringsLeft).toBe(RINGS);
109 expect(n.score).toBe(0);
110 expect(n.over).toBe(false);
111 expect(n.blocks.some(b => b.gone)).toBe(false);
112 });
113
114 test('a toss with NaN or missing input does not throw and lands at the line', () => {
115 for (const input of [{ aim: NaN, power: NaN }, {}, undefined]) {
116 const { event } = toss(newGame(0, 1), input);
117 expect(event.type).toBe('miss');
118 expect(Math.abs(event.x)).toBeLessThanOrEqual(SCATTER);
119 expect(event.z).toBeLessThanOrEqual(SCATTER);
120 }
121 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs