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

Migrated from github.com/amirmushichge/pixel-plays

Coconut Shy rules: a tested `coconut-shy/shy.js` that plays a whole game from plain data #119

Merged opened this

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

Merged

torque/pixel-plays:torque/105-coconut-shy-rules-a-tested-coconut-shy-s → main 1 commit fork

  • Merged. torque/105-coconut-shy-rules-a-tested-coconut-shy-s was merged into main as a6f45f0.

Review

Sign in to review this change.
2 files changed +236 −0
coconut-shy/shy.js added +89
@@ -0,0 +1,89 @@
1 'use strict';
2 // The coconut shy rules: five coconuts on posts, balls thrown from the line. Metres, seconds, degrees. A throw is a
3 // power (0..1) and an angle; the rules say where the ball lands along the line of posts. Plain data in, plain data
4 // out, no DOM, no timers, no Math.random: the little scatter on every throw comes from the seed.
5 (function (root) {
6 const ROUNDS = 3, BALLS = 5, COCONUTS = 5, WIN_AT = 9; // a game is three rounds of five balls; 9 down or more wins
7 const GRAVITY = 9.81, MAX_SPEED = 14; // m/s^2; m/s at full power
8 const COCONUT_WIDTH = .6, SQUARE_FRACTION = .4; // m; the square window is 40% of the width (the brief asks for at least a third)
9 const SQUARE_WINDOW = COCONUT_WIDTH * SQUARE_FRACTION; // m, centred on the coconut: a hit inside it knocks the coconut off
10 const WOBBLES_TO_FALL = 2; // a coconut wobbled twice falls
11 const POST_FIRST = 6, POST_STEP = 2, POST_GAP = 1.5; // m: nearest post in round 1, how far back each round moves them, gap between posts
12 const SCATTER = .05; // m: the most a throw drifts either way, from the seed
13 const BONUS_BALLS = 1;
14
15 const finite = v => (Number.isFinite(v) ? v : 0);
16 const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
17 // a repeatable number in [0, 1) for this seed and slot
18 function noise(seed, n) {
19 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
20 h = Math.imul(h ^ (h >>> 13), 1274126177);
21 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
22 }
23 // distance of the nearest post in this round (1..3): posts move back POST_STEP metres per round
24 const postDistance = round => POST_FIRST + (clamp(Math.floor(finite(round)), 1, ROUNDS) - 1) * POST_STEP;
25 // flat-ground projectile range R = v^2 sin(2a) / g, v = power * MAX_SPEED (metres)
26 function landing(power, angle) {
27 const v = clamp(finite(power), 0, 1) * MAX_SPEED, a = clamp(finite(angle), 0, 90) * Math.PI / 180;
28 return v * v * Math.sin(2 * a) / GRAVITY;
29 }
30 // the power that lands a ball this far at this angle (inverse of landing), for aim helpers and tests
31 function powerFor(distance, angle = 45) {
32 const s = Math.sin(2 * clamp(finite(angle), 0, 90) * Math.PI / 180);
33 return s <= 0 ? 1 : clamp(Math.sqrt(Math.max(0, finite(distance)) * GRAVITY / s) / MAX_SPEED, 0, 1);
34 }
35 const rack = round => Array.from({ length: COCONUTS }, (_, i) => ({ x: postDistance(round) + i * POST_GAP, wobbles: 0, down: false }));
36 const standing = s => s.coconuts.filter(c => !c.down).length;
37 const copy = s => ({ ...s, coconuts: s.coconuts.map(c => ({ ...c })) });
38
39 function newGame(best = 0, seed = 0) {
40 return { phase: 'aim', round: 1, ballsLeft: BALLS, down: 0, past: 0, banked: 0, bonusGiven: false, thrown: 0, best: Math.max(0, finite(best)),
41 over: false, outcome: '', line: 'Round 1 of ' + ROUNDS + ': five balls.', seed: finite(seed) >>> 0, coconuts: rack(1) };
42 }
43 // throw a ball: returns { state, event } and leaves the state you passed untouched
44 function throwBall(state, input = {}) {
45 if (state.phase !== 'aim' || state.ballsLeft <= 0) return { state, event: null };
46 const s = copy(state), power = clamp(finite(input.power), 0, 1), angle = clamp(finite(input.angle), 0, 90);
47 const land = Math.max(0, landing(power, angle) + (noise(s.seed, s.thrown) * 2 - 1) * SCATTER);
48 s.ballsLeft--; s.thrown++;
49 let result = 'miss', target = -1, best = Infinity;
50 s.coconuts.forEach((c, i) => { const d = Math.abs(land - c.x); if (!c.down && d <= COCONUT_WIDTH / 2 && d < best) { best = d; target = i; } });
51 if (target >= 0) {
52 const c = s.coconuts[target];
53 if (best <= SQUARE_WINDOW / 2) { c.down = true; result = 'knocked'; }
54 else if (++c.wobbles >= WOBBLES_TO_FALL) { c.down = true; result = 'fell'; }
55 else result = 'wobbled';
56 }
57 let bonus = false;
58 if (standing(s) === 0 && !s.bonusGiven) { // every coconut down: one bonus ball on a fresh rack, this rack's score kept
59 bonus = true; s.bonusGiven = true; s.ballsLeft += BONUS_BALLS; s.banked += COCONUTS; s.coconuts = rack(s.round);
60 s.line = 'Clean sweep! A bonus ball.';
61 }
62 s.down = s.past + s.banked + s.coconuts.filter(c => c.down).length; // coconuts down in the game so far
63 if (s.ballsLeft <= 0) { s.phase = 'between'; endRound(s); }
64 return { state: s, event: { type: result, land, target, bonus, round: s.round, ballsLeft: s.ballsLeft } };
65 }
66 function endRound(s) {
67 if (s.round >= ROUNDS) {
68 s.phase = 'over'; s.over = true; s.outcome = s.down >= WIN_AT ? 'won' : 'lost';
69 s.best = Math.max(s.best, s.down);
70 s.line = s.outcome === 'won' ? 'You win with ' + s.down + ' down!' : 'Only ' + s.down + ' down: you need ' + WIN_AT + '.';
71 } else s.line = 'Round ' + s.round + ' done: ' + s.down + ' down in all.';
72 }
73 // move on from a finished round: posts go further back, a fresh rack and five balls; null when not between rounds
74 function nextRound(state) {
75 if (state.phase !== 'between') return null;
76 const s = copy(state);
77 s.round++; s.phase = 'aim'; s.ballsLeft = BALLS; s.past = s.down; s.banked = 0; s.bonusGiven = false; s.coconuts = rack(s.round);
78 s.line = 'Round ' + s.round + ' of ' + ROUNDS + ': posts moved back.';
79 return s;
80 }
81 // a fresh game after one has finished (new seed, best kept); null while one is in play
82 const again = state => (state.over ? newGame(state.best, state.seed + 1) : null);
83
84 const api = {
85 ROUNDS, BALLS, COCONUTS, WIN_AT, GRAVITY, MAX_SPEED, COCONUT_WIDTH, SQUARE_WINDOW, WOBBLES_TO_FALL, POST_FIRST, POST_STEP, POST_GAP, SCATTER, BONUS_BALLS,
86 postDistance, landing, powerFor, rack, newGame, throwBall, nextRound, again,
87 };
88 if (typeof module !== 'undefined') module.exports = api; else root.Shy = api;
89 })(typeof window !== 'undefined' ? window : globalThis);
coconut-shy/shy.test.mjs added +147
@@ -0,0 +1,147 @@
1 import { test, expect } from 'bun:test';
2 import { ROUNDS, BALLS, COCONUTS, WIN_AT, COCONUT_WIDTH, SQUARE_WINDOW, SCATTER, POST_STEP, postDistance, landing, powerFor, rack, newGame, throwBall, nextRound, again } from './shy.js';
3
4 // throw so the ball lands `offset` metres past the middle of coconut i, at 45 degrees
5 const aim = (s, i, offset = 0) => ({ power: powerFor(s.coconuts[i].x + offset), angle: 45 });
6 const shoot = (s, i, offset = 0) => throwBall(s, aim(s, i, offset));
7 // play one round: knock the coconuts in `hit` square, throw the rest wide
8 const playRound = (s, hit) => {
9 for (let k = 0; k < hit && s.phase === 'aim'; k++) s = shoot(s, k).state;
10 while (s.phase === 'aim') s = throwBall(s, { power: 0, angle: 45 }).state;
11 return s;
12 };
13
14 test('the range is v^2 sin(2a) / g, and the angle and power matter', () => {
15 expect(landing(1, 45)).toBeCloseTo(14 * 14 / 9.81, 9);
16 expect(landing(.5, 45)).toBeCloseTo(landing(1, 45) / 4, 9);
17 expect(landing(1, 30)).toBeCloseTo(landing(1, 45) * Math.sin(Math.PI / 3), 9);
18 expect(landing(1, 0)).toBeCloseTo(0, 9);
19 expect(landing(NaN, NaN)).toBe(0);
20 expect(powerFor(8)).toBeCloseTo(Math.sqrt(8 * 9.81) / 14, 9);
21 });
22
23 test('the square window is stated and at least a third of the coconut', () => {
24 expect(SQUARE_WINDOW).toBeGreaterThanOrEqual(COCONUT_WIDTH / 3);
25 expect(SQUARE_WINDOW).toBeLessThan(COCONUT_WIDTH);
26 });
27
28 test('a hit inside the square window knocks the coconut off', () => {
29 const s = newGame(0, 3);
30 const { state, event } = shoot(s, 0, SQUARE_WINDOW / 2 - SCATTER - .01);
31 expect(event.type).toBe('knocked');
32 expect(state.coconuts[0].down).toBe(true);
33 expect(state.down).toBe(1);
34 expect(s.coconuts[0].down).toBe(false); // the state passed in is untouched
35 });
36
37 test('a glancing hit only wobbles; the second wobble falls', () => {
38 const off = SQUARE_WINDOW / 2 + SCATTER + .02; // outside the window, inside the coconut
39 expect(off + SCATTER).toBeLessThan(COCONUT_WIDTH / 2);
40 let r = shoot(newGame(0, 3), 2, off);
41 expect(r.event.type).toBe('wobbled');
42 expect(r.state.coconuts[2]).toMatchObject({ down: false, wobbles: 1 });
43 expect(r.state.down).toBe(0);
44 r = shoot(r.state, 2, -off);
45 expect(r.event.type).toBe('fell');
46 expect(r.state.coconuts[2].down).toBe(true);
47 expect(r.state.down).toBe(1);
48 });
49
50 test('a ball beside the coconut misses', () => {
51 const { state, event } = shoot(newGame(0, 3), 1, COCONUT_WIDTH);
52 expect(event.type).toBe('miss');
53 expect(state.down).toBe(0);
54 expect(state.ballsLeft).toBe(BALLS - 1);
55 });
56
57 test('a round is five balls, then it waits for the next round', () => {
58 let s = playRound(newGame(), 0);
59 expect(s.ballsLeft).toBe(0);
60 expect(s.phase).toBe('between');
61 expect(throwBall(s, { power: 1, angle: 45 }).event).toBeNull();
62 s = nextRound(s);
63 expect(s).toMatchObject({ phase: 'aim', round: 2, ballsLeft: BALLS });
64 expect(nextRound(s)).toBeNull();
65 });
66
67 test('every coconut down earns one bonus ball on a fresh rack', () => {
68 let s = newGame(0, 5);
69 for (let i = 0; i < COCONUTS; i++) s = shoot(s, i).state;
70 expect(s.ballsLeft).toBe(1);
71 expect(s.phase).toBe('aim');
72 expect(s.down).toBe(COCONUTS);
73 expect(s.coconuts.every(c => !c.down)).toBe(true);
74 s = shoot(s, 0).state; // the bonus ball scores too, and no second bonus follows
75 expect(s.down).toBe(COCONUTS + 1);
76 expect(s.ballsLeft).toBe(0);
77 expect(s.phase).toBe('between');
78 });
79
80 test('without a clean sweep there is no bonus ball', () => {
81 const s = playRound(newGame(), 4);
82 expect(s.down).toBe(4);
83 expect(s.phase).toBe('between');
84 });
85
86 test('posts move further back each round', () => {
87 expect(postDistance(2) - postDistance(1)).toBe(POST_STEP);
88 expect(postDistance(3) - postDistance(2)).toBe(POST_STEP);
89 let s = newGame();
90 const first = s.coconuts[0].x;
91 s = nextRound(playRound(s, 0));
92 expect(s.coconuts[0].x).toBe(first + POST_STEP);
93 s = nextRound(playRound(s, 0));
94 expect(s.coconuts[0].x).toBe(first + 2 * POST_STEP);
95 expect(rack(3)[0].x).toBeLessThan(landing(1, 45)); // still within reach of a full throw
96 expect(rack(3)[COCONUTS - 1].x).toBeLessThan(landing(1, 45));
97 });
98
99 test('the game reports round, balls left, down and best, and ends after round three', () => {
100 let s = newGame(2, 1);
101 expect(s).toMatchObject({ round: 1, ballsLeft: BALLS, down: 0, best: 2, over: false, outcome: '' });
102 s = nextRound(playRound(s, 3));
103 s = nextRound(playRound(s, 3));
104 expect(s.down).toBe(6);
105 s = playRound(s, 3);
106 expect(s).toMatchObject({ round: ROUNDS, over: true, phase: 'over', down: 9, best: 9 });
107 expect(nextRound(s)).toBeNull();
108 expect(throwBall(s, { power: 1, angle: 45 }).event).toBeNull();
109 });
110
111 test('9 down wins', () => {
112 let s = nextRound(playRound(newGame(), 3));
113 s = nextRound(playRound(s, 3));
114 s = playRound(s, 3);
115 expect(s.down).toBe(WIN_AT);
116 expect(s.outcome).toBe('won');
117 expect(s.line).toContain('win');
118 });
119
120 test('8 down loses, and best keeps a better earlier game', () => {
121 let s = nextRound(playRound(newGame(12), 3));
122 s = nextRound(playRound(s, 3));
123 s = playRound(s, 2);
124 expect(s.down).toBe(WIN_AT - 1);
125 expect(s.outcome).toBe('lost');
126 expect(s.line).toContain('9');
127 expect(s.best).toBe(12);
128 });
129
130 test('again starts a new game once over, keeping best, and the seed changes the scatter', () => {
131 expect(again(newGame())).toBeNull();
132 let s = nextRound(playRound(newGame(), 3));
133 s = playRound(nextRound(playRound(s, 3)), 3);
134 const n = again(s);
135 expect(n).toMatchObject({ round: 1, down: 0, best: 9, over: false });
136 const a = throwBall(newGame(0, 1), { power: .8, angle: 40 }).event.land;
137 expect(throwBall(newGame(0, 1), { power: .8, angle: 40 }).event.land).toBe(a);
138 expect(Math.abs(a - landing(.8, 40))).toBeLessThanOrEqual(SCATTER);
139 const lands = [1, 2, 3, 4, 5, 6].map(seed => throwBall(newGame(0, seed), { power: .8, angle: 40 }).event.land);
140 expect(new Set(lands).size).toBeGreaterThan(1);
141 });
142
143 test('bad input is clamped, not trusted', () => {
144 const { event } = throwBall(newGame(), { power: 'x', angle: Infinity });
145 expect(Number.isFinite(event.land)).toBe(true);
146 expect(throwBall(newGame(), undefined).event.type).toBe('miss');
147 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs