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

Migrated from github.com/amirmushichge/pixel-plays

Bird Watch rules: a tested `bird-watch/watch.js` that shows birds on perches for a moment and asks where each one sat, from plain data #195

Merged opened this

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

Merged

torque/pixel-plays:torque/180-bird-watch-rules-a-tested-bird-watch-wat → main 2 commits fork

  • Merged. torque/180-bird-watch-rules-a-tested-bird-watch-wat was merged into main as 815381d.

Review

Sign in to review this change.
2 files changed +224 −0
bird-watch/watch.js added +105
@@ -0,0 +1,105 @@
1 'use strict';
2 // The Bird Watch rules: birds land on the perches of a garden for a moment, fly off, and the game names a bird and you
3 // point at the perch where it sat. Plain data in, plain data out, no DOM, no timers, no Math.random: every round comes
4 // from the seed and the round number. A refused move returns the very same state and says why. The page draws this.
5 //
6 // Round n shows n + 1 birds (FIRST_BIRDS in round 1, one more each round, MOST_BIRDS in the last round, LAST_ROUND), each
7 // of a distinct species on a distinct perch. After the show there are as many questions as birds, one per bird, in a
8 // seeded order. A wrong answer costs one of BINOCULARS pairs; losing the last ends the game. Clearing round LAST_ROUND
9 // ends it too. The win line is WIN_ROUND rounds cleared.
10 (function (root) {
11 const PERCHES = ['oak-low', 'oak-high', 'oak-tip', 'fence-1', 'fence-2', 'fence-3', 'roof-left', 'roof-ridge', 'roof-right', 'feeder'];
12 const SPECIES = ['robin', 'wren', 'finch', 'jay', 'sparrow', 'owl', 'magpie', 'starling'];
13 const FIRST_BIRDS = 2, MOST_BIRDS = 6, LAST_ROUND = MOST_BIRDS - FIRST_BIRDS + 1;
14 const BINOCULARS = 3, WIN_ROUND = 4;
15
16 const finite = v => (Number.isFinite(v) ? v : 0);
17 const birdsIn = round => FIRST_BIRDS + round - 1;
18 // a repeatable number in [0, 1) for this seed and slot
19 function noise(seed, n) {
20 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
21 h = Math.imul(h ^ (h >>> 13), 1274126177);
22 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
23 }
24 // the first `count` of a seeded shuffle of the list (Fisher-Yates), leaving the list alone
25 function pick(list, count, seed, base) {
26 const a = list.slice();
27 for (let i = a.length - 1; i > 0; i--) {
28 const j = Math.floor(noise(seed, base + i) * (i + 1));
29 [a[i], a[j]] = [a[j], a[i]];
30 }
31 return a.slice(0, count);
32 }
33
34 // The birds of a round for a seed: [{ species, perch }], distinct on both counts.
35 function birds(seed, round) {
36 seed = finite(seed) >>> 0;
37 round = Math.min(LAST_ROUND, Math.max(1, Math.floor(finite(round)) || 1));
38 const n = birdsIn(round), base = round * 1009;
39 const perches = pick(PERCHES, n, seed, base), species = pick(SPECIES, n, seed, base + 101);
40 return perches.map((perch, i) => ({ species: species[i], perch }));
41 }
42
43 const copy = s => ({ ...s, birds: s.birds.map(b => ({ ...b })), order: s.order.slice(), asking: s.asking && { ...s.asking } });
44 const plural = (n, one, many) => (n === 1 ? one : many);
45 const verdict = s => (s.cleared >= WIN_ROUND ? 'won' : 'lost');
46 function refresh(s) {
47 if (s.status === 'over') {
48 s.line = verdict(s) === 'won'
49 ? `Sharp eyes: ${s.cleared} ${plural(s.cleared, 'round', 'rounds')} cleared, ${s.right} ${plural(s.right, 'answer', 'answers')} right`
50 : `The birds got away: ${s.cleared} of ${LAST_ROUND} rounds cleared, ${s.right} ${plural(s.right, 'answer', 'answers')} right`;
51 } else {
52 s.line = `Round ${s.round} of ${LAST_ROUND}: ${s.order.length - s.answered} to ask, ${s.binoculars} ${plural(s.binoculars, 'pair', 'pairs')} of binoculars`;
53 }
54 return s;
55 }
56
57 // start(seed): round 0, nothing shown yet; call round() for the first flock
58 const start = (seed = 1) => refresh({
59 seed: finite(seed) >>> 0, perches: PERCHES.slice(), species: SPECIES.slice(), round: 0, last: LAST_ROUND,
60 binoculars: BINOCULARS, status: 'playing', birds: [], order: [], answered: 0, asking: null, cleared: 0, right: 0, line: '',
61 });
62
63 // round(state) -> { ok, why, state }: the next flock lands. Refused while questions are still open or once the game is over.
64 function round(s) {
65 if (s.status !== 'playing') return { ok: false, why: 'over', state: s };
66 if (s.round > 0 && s.answered < s.order.length) return { ok: false, why: 'unanswered', state: s };
67 const n = copy(s), r = s.round + 1;
68 n.round = r; n.birds = birds(s.seed, r); n.answered = 0; n.asking = null;
69 n.order = pick(n.birds.map((_, i) => i), n.birds.length, s.seed, r * 1009 + 503); // one question per bird
70 return { ok: true, why: '', state: refresh(n) };
71 }
72
73 // ask(state) -> { ok, why, species, state }: names the next bird of the round just shown. Asking again repeats the question.
74 function ask(s) {
75 if (s.status !== 'playing') return { ok: false, why: 'over', species: '', state: s };
76 if (s.round === 0 || s.answered >= s.order.length) return { ok: false, why: 'no-question', species: '', state: s };
77 if (s.asking) return { ok: true, why: '', species: s.asking.species, state: s };
78 const n = copy(s);
79 n.asking = { ...n.birds[n.order[n.answered]] };
80 return { ok: true, why: '', species: n.asking.species, state: n };
81 }
82
83 // answer(state, perch) -> { ok, why, correct, event, state }; event is '', 'cleared' (round done) or 'over'.
84 function answer(s, perch) {
85 const no = why => ({ ok: false, why, correct: false, event: '', state: s });
86 if (s.status !== 'playing') return no('over');
87 if (typeof perch !== 'string' || !s.perches.includes(perch)) return no('bad-perch');
88 if (!s.asking) return no('not-asked');
89 const correct = perch === s.asking.perch, n = copy(s);
90 n.answered += 1; n.asking = null;
91 if (correct) n.right += 1; else n.binoculars -= 1;
92 let event = '';
93 if (n.binoculars <= 0) { n.status = 'over'; event = 'over'; }
94 else if (n.answered >= n.order.length) {
95 n.cleared += 1; event = 'cleared';
96 if (n.round >= LAST_ROUND) { n.status = 'over'; event = 'over'; }
97 }
98 return { ok: true, why: '', correct, event, state: refresh(n) };
99 }
100
101 const api = {
102 PERCHES, SPECIES, FIRST_BIRDS, MOST_BIRDS, LAST_ROUND, BINOCULARS, WIN_ROUND, birdsIn, birds, start, round, ask, answer, verdict,
103 };
104 if (typeof module !== 'undefined') module.exports = api; else root.BirdWatch = api;
105 })(typeof window !== 'undefined' ? window : globalThis);
bird-watch/watch.test.mjs added +119
@@ -0,0 +1,119 @@
1 import { test, expect } from 'bun:test';
2 import { PERCHES, SPECIES, FIRST_BIRDS, MOST_BIRDS, LAST_ROUND, BINOCULARS, WIN_ROUND, birdsIn, birds, start, round, ask, answer, verdict } from './watch.js';
3
4 // play one round, answering every question with the right perch (or a wrong one when `wrong` says so)
5 function play(s, wrong = () => false) {
6 let r = round(s); expect(r.ok).toBe(true); s = r.state;
7 let last;
8 for (let i = 0; i < s.birds.length; i++) {
9 const q = ask(s); expect(q.ok).toBe(true); s = q.state;
10 const sat = s.asking.perch;
11 const perch = wrong(i) ? PERCHES.find(p => p !== sat) : sat;
12 last = answer(s, perch); expect(last.ok).toBe(true); s = last.state;
13 if (s.status === 'over') break;
14 }
15 return { s, last };
16 }
17
18 test('start states its perches and species, and the same seed gives the same rounds', () => {
19 const s = start(7);
20 expect(s.perches).toEqual(PERCHES);
21 expect(s.species).toEqual(SPECIES);
22 expect(s.binoculars).toBe(BINOCULARS);
23 expect(start(7)).toEqual(start(7));
24 expect(round(s).state.birds).toEqual(round(start(7)).state.birds);
25 expect(round(s).state.order).toEqual(round(start(7)).state.order);
26 expect(birds(7, 3)).toEqual(birds(7, 3));
27 const seen = new Set();
28 for (let seed = 1; seed <= 20; seed++) seen.add(JSON.stringify(birds(seed, 2)));
29 expect(seen.size).toBeGreaterThan(5);
30 });
31
32 test('no two birds share a perch or a species in a round, for many seeds', () => {
33 for (let seed = 0; seed < 100; seed++) for (let r = 1; r <= LAST_ROUND; r++) {
34 const b = birds(seed, r);
35 expect(new Set(b.map(x => x.perch)).size).toBe(b.length);
36 expect(new Set(b.map(x => x.species)).size).toBe(b.length);
37 for (const x of b) { expect(PERCHES).toContain(x.perch); expect(SPECIES).toContain(x.species); }
38 }
39 });
40
41 test('each round shows one more bird than the last, from FIRST_BIRDS up to MOST_BIRDS', () => {
42 let s = start(3), prev = 0;
43 for (let r = 1; r <= LAST_ROUND; r++) {
44 ({ s } = play(s));
45 expect(s.birds).toHaveLength(r === 1 ? FIRST_BIRDS : prev + 1);
46 expect(s.birds).toHaveLength(birdsIn(r));
47 prev = s.birds.length;
48 }
49 expect(prev).toBe(MOST_BIRDS);
50 });
51
52 test('a round has as many questions as birds, each bird asked once', () => {
53 let s = round(start(5)).state;
54 expect(round(s).why).toBe('unanswered');
55 const asked = [];
56 for (let i = 0; i < s.birds.length; i++) {
57 const q = ask(s); s = q.state;
58 expect(ask(s).species).toBe(q.species); // asking again repeats the question
59 asked.push(q.species);
60 s = answer(s, s.asking.perch).state;
61 }
62 expect(asked.sort()).toEqual(s.birds.map(b => b.species).sort());
63 expect(ask(s).why).toBe('no-question');
64 });
65
66 test('an unknown perch is refused and changes nothing', () => {
67 let s = ask(round(start(2)).state).state;
68 for (const bad of ['moon', '', 7, null, undefined, '__proto__']) {
69 const r = answer(s, bad);
70 expect(r.ok).toBe(false); expect(r.why).toBe('bad-perch'); expect(r.state).toBe(s);
71 }
72 expect(answer(round(start(2)).state, PERCHES[0]).why).toBe('not-asked');
73 });
74
75 test('a wrong answer costs one pair of binoculars, a right one costs none', () => {
76 let s = ask(round(start(4)).state).state;
77 const right = answer(s, s.asking.perch);
78 expect(right.correct).toBe(true); expect(right.state.binoculars).toBe(BINOCULARS); expect(right.state.right).toBe(1);
79 const wrong = answer(s, PERCHES.find(p => p !== s.asking.perch));
80 expect(wrong.correct).toBe(false); expect(wrong.state.binoculars).toBe(BINOCULARS - 1); expect(wrong.state.right).toBe(0);
81 });
82
83 test('the game ends at zero binoculars and refuses more', () => {
84 let s = start(9), last;
85 for (let i = 0; i < BINOCULARS; i++) {
86 expect(s.status).toBe('playing');
87 ({ s, last } = play(s, j => j === 0));
88 }
89 expect(s.binoculars).toBe(0);
90 expect(s.status).toBe('over'); expect(last.event).toBe('over');
91 expect(round(s).why).toBe('over'); expect(ask(s).why).toBe('over'); expect(answer(s, PERCHES[0]).why).toBe('over');
92 });
93
94 test('a perfect game clears every round, ends, and reports the win line', () => {
95 let s = start(11), last;
96 for (let r = 1; r <= LAST_ROUND; r++) { expect(s.status).toBe('playing'); ({ s, last } = play(s)); }
97 expect(s.status).toBe('over'); expect(last.event).toBe('over');
98 expect(s.cleared).toBe(LAST_ROUND);
99 expect(s.right).toBe([...Array(LAST_ROUND)].reduce((a, _, i) => a + birdsIn(i + 1), 0));
100 expect(verdict(s)).toBe('won');
101 expect(s.line).toBe(`Sharp eyes: ${LAST_ROUND} rounds cleared, ${s.right} answers right`);
102 });
103
104 test('the win line starts at WIN_ROUND rounds cleared; fewer is the loss line', () => {
105 let s = start(13);
106 for (let r = 1; r < WIN_ROUND; r++) ({ s } = play(s));
107 s = { ...s, status: 'over' };
108 expect(s.cleared).toBe(WIN_ROUND - 1);
109 expect(verdict(s)).toBe('lost');
110 let t = start(13);
111 for (let r = 1; r <= WIN_ROUND; r++) ({ s: t } = play(t));
112 expect(t.cleared).toBe(WIN_ROUND);
113 expect(verdict({ ...t, status: 'over' })).toBe('won');
114 // a loss: lose all binoculars in round 1
115 let l = start(13);
116 for (let i = 0; i < BINOCULARS; i++) ({ s: l } = play(l, j => j === 0));
117 expect(verdict(l)).toBe('lost');
118 expect(l.line).toBe(`The birds got away: ${l.cleared} of ${LAST_ROUND} rounds cleared, ${l.right} ${l.right === 1 ? 'answer' : 'answers'} right`);
119 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs