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

Migrated from github.com/amirmushichge/pixel-plays

Rain Barrel rules: a tested `rain-barrel/gutter.js` where rain runs off a roof's gutters and you slide one barrel under each spout before it overflows the yard, from plain data #226

Merged opened this

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

Merged

torque/pixel-plays:torque/219-rain-barrel-rules-a-tested-rain-barrel-g → main 2 commits fork 4 threads · 4 unresolved

  • Merged. torque/219-rain-barrel-rules-a-tested-rain-barrel-g was merged into main as 773d6b9.

Review

Sign in to review this change.
2 files changed +240 −0
rain-barrel/gutter.js added +117
@@ -0,0 +1,117 @@
1 'use strict';
2 // The Rain Barrel rules: rain runs off a cottage roof through a row of gutter spouts, and one barrel slides along the
3 // wall to catch it before the yard floods.
4 // Plain data in, plain data out, no DOM, no timers, no Math.random: the rain comes from the seed.
5 // A rejected call returns the very same state and says why. The page draws what this decides.
6 //
7 // Time is in ticks. On each tick the schedule may drip from one spout (or stay dry). A drop from the spout above the

Non-blocking: this comment line runs well past the width of the others. Wrap it.

8 // barrel fills it by one; any other drop, or any drop while the barrel is full or being emptied (emptying happens inside empty()), adds one to the puddle.
9 (function (root) {
10 const SPOUTS = 5; // spouts in the row, numbered 0..SPOUTS - 1 from the left
11 const CAPACITY = 4; // drops a barrel holds before it is full
12 const ROUND = 40; // ticks in a round
13 const EMPTY_TICKS = 2; // ticks that emptying the barrel costs; rain keeps falling
14 const CATCH_SCORE = 10; // points for each drop caught
15 const FULL_BONUS = 25; // points for emptying a barrel that was full
16 const PUDDLE_LIMIT = 8; // the puddle reaching this floods the yard (loss)
17
18 const finite = v => (Number.isFinite(v) ? v : 0);
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
26 // schedule[t] is the spout that drips on tick t, or -1 for a dry tick. Rain comes in bursts: a spout drips for a
27 // few ticks running, then a pause, then another spout.
28 function rain(seed) {
29 const out = [];
30 let slot = 0;
31 while (out.length < ROUND) {
32 const spout = Math.floor(noise(seed, slot++) * SPOUTS);
33 const drips = 2 + Math.floor(noise(seed, slot++) * 3); // 2..4 drops in the burst
34 const pause = Math.floor(noise(seed, slot++) * 3); // 0..2 dry ticks after it
35 for (let i = 0; i < drips; i++) out.push(spout);
36 for (let i = 0; i < pause; i++) out.push(-1);
37 }
38 return out.slice(0, ROUND);
39 }
40
41 function refresh(s) {
42 if (s.status === 'over') {
43 s.line = s.won
44 ? `Yard dry: ${s.score} points, puddle ${s.puddle} of ${PUDDLE_LIMIT}`
45 : `Yard flooded: ${s.score} points, puddle reached ${PUDDLE_LIMIT}`;
46 } else {
47 s.line = `Tick ${s.time} of ${ROUND}: barrel ${s.barrel} of ${CAPACITY} at spout ${s.at}, puddle ${s.puddle} of ${PUDDLE_LIMIT}, ${s.score} points`;
48 }
49 return s;
50 }
51
52 const start = (seed = 1) => {
53 const sd = finite(seed) >>> 0;
54 return refresh({
55 seed: sd, spouts: SPOUTS, capacity: CAPACITY, length: ROUND, limit: PUDDLE_LIMIT, schedule: rain(sd),
56 time: 0, at: Math.floor(SPOUTS / 2), barrel: 0, puddle: 0, caught: 0, score: 0,
57 status: 'playing', won: false, line: '',
58 });
59 };
60
61 const copy = s => Object.assign({}, s, { schedule: s.schedule.slice() });
62 const refuse = (s, why) => ({ ok: false, why, event: '', state: s });
63
64 // advance one tick on a copy (n is already a copy); returns the event: '', 'caught', 'missed', 'won' or 'lost'
65 // pouring is true while the barrel is being tipped out: it catches nothing then
66 function step(n, pouring = false) {
67 const drop = n.schedule[n.time];
68 let event = '';
69 if (drop !== undefined && drop >= 0) {
70 if (!pouring && drop === n.at && n.barrel < n.capacity) {
71 n.barrel += 1; n.caught += 1; n.score += CATCH_SCORE; event = 'caught';
72 } else { n.puddle += 1; event = 'missed'; }
73 }
74 n.time += 1;
outdated

pouring never survives a call: empty() runs it to 0 before returning. Remove it or make it real (see the review body).

75 if (n.puddle >= PUDDLE_LIMIT) { n.status = 'over'; n.won = false; return 'lost'; }
76 if (n.time >= n.length) { n.status = 'over'; n.won = true; return 'won'; }
77 return event;
78 }
79
80 // move(state, spout) -> { ok, why, event, state }: the barrel goes under that spout
81 function move(s, spout) {
82 if (s.status !== 'playing') return refuse(s, 'over');
83 if (!Number.isInteger(spout) || spout < 0 || spout >= s.spouts) return refuse(s, 'bad-spout');
84 const n = copy(s); n.at = spout;
outdated

Unreachable through the API, since no returned state has pouring > 0, and untested. Delete it or test it.

85 return { ok: true, why: '', event: '', state: refresh(n) };
86 }
87
88 // tick(state) -> { ok, why, event, state }
89 function tick(s) {
90 if (s.status !== 'playing') return refuse(s, 'over');
91 const n = copy(s);
92 const event = step(n);
93 return { ok: true, why: '', event, state: refresh(n) };
94 }
95
96 // empty(state) -> { ok, why, event, state }: tips the barrel out, which takes EMPTY_TICKS ticks of rain with the barrel
97 // catching nothing. Emptying a full barrel scores the bonus. An empty barrel is refused.
98 function empty(s) {
99 if (s.status !== 'playing') return refuse(s, 'over');
100 if (s.barrel === 0) return refuse(s, 'already-empty');
101 const n = copy(s);
outdated

Same: the 'emptying' refusal can never fire. Untested.

102 const wasFull = n.barrel >= n.capacity;
103 if (wasFull) n.score += FULL_BONUS;
104 n.barrel = 0;
105 let event = wasFull ? 'bonus' : 'emptied';
106 for (let i = 0; i < EMPTY_TICKS && n.status === 'playing'; i++) {
107 const e = step(n, true);
108 if (e === 'won' || e === 'lost') event = e;
109 }
110 return { ok: true, why: '', event, state: refresh(n) };
111 }
112
113 const api = {
114 SPOUTS, CAPACITY, ROUND, EMPTY_TICKS, CATCH_SCORE, FULL_BONUS, PUDDLE_LIMIT, rain, start, move, tick, empty,
115 };
116 if (typeof module !== 'undefined') module.exports = api; else root.RainBarrel = api;
117 })(typeof window !== 'undefined' ? window : globalThis);
rain-barrel/gutter.test.mjs added +123
@@ -0,0 +1,123 @@
1 import { test, expect } from 'bun:test';
2 import {
3 SPOUTS, CAPACITY, ROUND, EMPTY_TICKS, CATCH_SCORE, FULL_BONUS, PUDDLE_LIMIT, rain, start, move, tick, empty,
4 } from './gutter.js';
5
6 // a state with a hand-written schedule, so each rule is checked against a count done by hand
7 const rigged = (schedule, over = {}) => ({ ...start(1), schedule, length: schedule.length, ...over });
8
9 test('the same seed gives the same schedule, other seeds differ, and the stated sizes hold', () => {
10 expect(start(7)).toEqual(start(7));
11 expect(rain(7)).toHaveLength(ROUND);
12 const seen = new Set();
13 for (let seed = 1; seed <= 20; seed++) seen.add(JSON.stringify(rain(seed)));
14 expect(seen.size).toBeGreaterThan(10);
15 const s = start(3);
16 expect([s.spouts, s.capacity, s.length, s.limit]).toEqual([SPOUTS, CAPACITY, ROUND, PUDDLE_LIMIT]);
17 for (const d of s.schedule) { expect(d).toBeGreaterThanOrEqual(-1); expect(d).toBeLessThan(SPOUTS); }
18 expect(s.schedule.some(d => d >= 0)).toBe(true);
19 });
20
21 test('a spout off the row is refused and changes nothing', () => {
22 const s = start(1);
23 for (const bad of [-1, SPOUTS, 1.5, NaN, '2', undefined]) {
24 const r = move(s, bad);
25 expect([r.ok, r.why]).toEqual([false, 'bad-spout']);
26 expect(r.state).toBe(s);
27 }
28 const r = move(s, 0);
29 expect([r.ok, r.state.at]).toEqual([true, 0]);
30 });
31
32 test('a drop over the barrel is caught and scores; a drop elsewhere lands in the puddle', () => {
33 let s = rigged([2, 3, -1], { at: 2 });
34 let r = tick(s);
35 expect([r.event, r.state.barrel, r.state.puddle, r.state.score]).toEqual(['caught', 1, 0, CATCH_SCORE]);
36 r = tick(r.state);
37 expect([r.event, r.state.barrel, r.state.puddle, r.state.score]).toEqual(['missed', 1, 1, CATCH_SCORE]);
38 });
39
40 test('a dry tick changes only the clock', () => {
41 const r = tick(rigged([-1, 0]));
42 expect([r.ok, r.event, r.state.time, r.state.barrel, r.state.puddle]).toEqual([true, '', 1, 0, 0]);
43 });
44
45 test('a full barrel catches nothing until it is emptied', () => {
46 let s = rigged(Array(CAPACITY + 2).fill(2), { at: 2 });
47 for (let i = 0; i < CAPACITY; i++) s = tick(s).state;
48 expect([s.barrel, s.puddle]).toEqual([CAPACITY, 0]);
49 s = tick(s).state;
50 expect([s.barrel, s.puddle, s.score]).toEqual([CAPACITY, 1, CAPACITY * CATCH_SCORE]);
51 });
52
53 test('emptying costs ticks, rain keeps falling meanwhile, and a full barrel earns the bonus', () => {
54 let s = rigged([2, 2, 2, 2, 2, 2, 2, 2, 2, 2], { at: 2 });
55 for (let i = 0; i < CAPACITY; i++) s = tick(s).state;
56 const before = s;
57 const r = empty(s);
58 expect([r.ok, r.event]).toEqual([true, 'bonus']);
59 expect(r.state.time).toBe(before.time + EMPTY_TICKS);
60 expect(r.state.puddle).toBe(before.puddle + EMPTY_TICKS); // the barrel catches nothing while it pours
61 expect(r.state.barrel).toBe(0);
62 expect(r.state.score).toBe(before.score + FULL_BONUS);
63 expect(tick(r.state).state.barrel).toBe(1); // and catches again afterwards
64 });
65
66 test('emptying a part-filled barrel costs ticks but earns no bonus; an empty barrel is refused', () => {
67 const s0 = rigged(Array(10).fill(-1), { at: 2 });
68 const e = empty(s0);
69 expect([e.ok, e.why]).toEqual([false, 'already-empty']);
70 expect(e.state).toBe(s0);
71 const s = { ...s0, barrel: 1 };
72 const r = empty(s);
73 expect([r.ok, r.event, r.state.time, r.state.score, r.state.barrel]).toEqual([true, 'emptied', EMPTY_TICKS, 0, 0]);
74 });
75
76 test('the round ends with the win line when time passes under the limit', () => {
77 let s = rigged([-1, -1, 4]);
78 let r;
79 for (let i = 0; i < 3; i++) { r = tick(s); s = r.state; }
80 expect([r.event, s.status, s.won, s.puddle]).toEqual(['won', 'over', true, 1]);
81 expect(s.line).toContain('Yard dry');
82 const again = tick(s);
83 expect([again.ok, again.why]).toEqual([false, 'over']);
84 expect(again.state).toBe(s);
85 expect(move(s, 1).why).toBe('over');
86 expect(empty(s).why).toBe('over');
87 });
88
89 test('the puddle reaching the limit floods the yard at once, with the loss line', () => {
90 let s = rigged(Array(PUDDLE_LIMIT + 5).fill(4), { at: 0 });
91 let r;
92 for (let i = 0; i < PUDDLE_LIMIT; i++) { r = tick(s); s = r.state; }
93 expect([r.event, s.status, s.won, s.puddle, s.time]).toEqual(['lost', 'over', false, PUDDLE_LIMIT, PUDDLE_LIMIT]);
94 expect(s.line).toContain('Yard flooded');
95 });
96
97 test('a puddle one short of the limit when the round ends still wins', () => {
98 let s = rigged(Array(PUDDLE_LIMIT - 1).fill(4), { at: 0 });
99 let r;
100 for (let i = 0; i < PUDDLE_LIMIT - 1; i++) { r = tick(s); s = r.state; }
101 expect([r.event, s.won, s.puddle]).toEqual(['won', true, PUDDLE_LIMIT - 1]);
102 });
103
104 test('a whole seeded round plays out to an end and ends within the stated length', () => {
105 let s = start(11);
106 let guard = 0;
107 while (s.status === 'playing' && guard++ < 100) s = tick(s).state;
108 expect(s.status).toBe('over');
109 expect(s.time).toBeLessThanOrEqual(ROUND);
110 });
111
112 test('the yard flooding during empty() ends the round there, with the loss event and no further ticks', () => {
113 const s = rigged(Array(10).fill(4), { at: 0, barrel: 1, puddle: PUDDLE_LIMIT - 1 });
114 const r = empty(s);
115 expect([r.ok, r.event, r.state.status, r.state.won, r.state.time, r.state.puddle]).toEqual([true, 'lost', 'over', false, 1, PUDDLE_LIMIT]);
116 expect(r.state.line).toContain('Yard flooded');
117 });
118
119 test('the round ending during empty() wins, and the bonus is still scored', () => {
120 const s = rigged([-1, -1, -1], { at: 0, time: 2, barrel: CAPACITY });
121 const r = empty(s);
122 expect([r.event, r.state.status, r.state.won, r.state.time, r.state.score]).toEqual(['won', 'over', true, 3, FULL_BONUS]);
123 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs