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

Migrated from github.com/amirmushichge/pixel-plays

Bottle Bank rules: a tested `bottle-bank/bins.js` where you swing a conveyor chute to sort coloured bottles into the right bins before three cracks end the shift, from plain data, in a two-file pull with a test file that runs in under a second #318

Merged opened this

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

Merged

torque/pixel-plays:torque/315-bottle-bank-rules-a-tested-bottle-bank-b → main 1 commit fork

  • Merged. torque/315-bottle-bank-rules-a-tested-bottle-bank-b was merged into main as 1295cad.

Review

Sign in to review this change.
2 files changed +231 −0
bottle-bank/bins.js added +117
@@ -0,0 +1,117 @@
1 'use strict';
2 // The Bottle Bank rules: glass bottles ride a conveyor toward its end; you swing the chute between three bins and
3 // each bottle drops into whichever bin the chute faces when it reaches the end. Plain data in, plain data out, no
4 // DOM, no timers, no Math.random: the bottle order and gaps come from the seed. A refused call returns the very
5 // same state and says why: { ok:false, state, why }.
6 //
7 // Units: the belt is BELT cells long and a tick moves every bottle `speed` cells. A bottle's x is its cell
8 // position; x < 0 means it has not reached the belt yet, x ≥ BELT means it has reached the end and drops.
9 // speed(dropped) = the SPEEDS entry with the greatest `from` ≤ bottles already dropped (cells per tick)
10 // Bins and colours share an index: 0 clear, 1 green, 2 brown. A bottle is right when bin === colour.
11 (function (root) {
12 const COLOURS = ['clear', 'green', 'brown'];
13 const BINS = COLOURS.length;
14 const BOTTLES = 24; // bottles in a shift
15 const BELT = 10; // cells from the loading end to the chute
16 const FIRST_GAP = 4; // cells before the first bottle's loading point
17 const GAP_MIN = 3, GAP_MAX = 6; // cells between consecutive bottles (≥ top speed, so one drop per tick)
18 const SPEEDS = [{ from: 0, speed: 1 }, { from: 8, speed: 2 }, { from: 16, speed: 3 }]; // rises after 8 and 16 drops
19 const CRACKS = 3; // the third crack ends the shift
20 const POINT = 1; // per bottle in the right bin
21 const BONUS = { 3: 2, 5: 3, 8: 5 }; // streak length -> bonus points, paid when the streak reaches it
22
23 // mulberry32 as a pure step: next(seed) -> [value in [0,1), nextSeed]
24 function next(r) {
25 r = (r + 0x6D2B79F5) >>> 0;
26 let t = r;
27 t = Math.imul(t ^ (t >>> 15), t | 1);
28 t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
29 return [((t ^ (t >>> 14)) >>> 0) / 4294967296, r];
30 }
31
32 // speedAt(dropped) -> cells per tick once `dropped` bottles have fallen
33 function speedAt(dropped) {
34 let sp = SPEEDS[0].speed;
35 for (const k of SPEEDS) if (dropped >= k.from) sp = k.speed;
36 return sp;
37 }
38
39 const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
40
41 // describe(state) -> the one-line report; the end line names sorted, cracks and best streak
42 function describe(s) {
43 const tail = `${s.sorted} sorted, ${plural(s.cracks, 'crack')}, best streak ${s.best}, score ${s.score}`;
44 if (s.status === 'over') return `Shift over: ${tail}`;
45 return `Chute on ${COLOURS[s.chute]}: ${tail}, ${s.bottles.length - s.dropped} to go`;
46 }
47
48 // start(seed) -> a shift: the whole seeded line of bottles, laid out by cumulative gap
49 function start(seed) {
50 const sd = Number.isFinite(seed) ? Math.trunc(seed) >>> 0 : 0;
51 let rng = sd, x = -FIRST_GAP;
52 const bottles = [];
53 for (let i = 0; i < BOTTLES; i++) {
54 let a, b;
55 [a, rng] = next(rng); [b, rng] = next(rng);
56 if (i) x -= GAP_MIN + Math.floor(b * (GAP_MAX - GAP_MIN + 1));
57 bottles.push({ id: i, colour: Math.floor(a * BINS), x, fate: 'riding' });
58 }
59 // bottle 0 starts FIRST_GAP cells before the belt; later ones queue further back
60 const s = {
61 seed: sd, status: 'playing', tick: 0, chute: 0, dropped: 0, sorted: 0, cracks: 0, streak: 0, best: 0,
62 score: 0, bottles, line: '',
63 };
64 s.line = describe(s);
65 return s;
66 }
67
68 const reject = (state, why) => ({ ok: false, state, why });
69 const clone = s => ({ ...s, bottles: s.bottles.map(b => ({ ...b })) });
70 const done = s => { s.line = describe(s); return { ok: true, state: s, why: '' }; };
71
72 // aim(state, bin): points the chute at bin 0..2
73 function aim(state, bin) {
74 if (state.status !== 'playing') return reject(state, 'game-over');
75 if (!Number.isInteger(bin) || bin < 0 || bin >= BINS) return reject(state, 'bad-bin');
76 if (bin === state.chute) return done(clone(state));
77 const s = clone(state);
78 s.chute = bin;
79 return done(s);
80 }
81
82 // drop(s, bottle): the bottle falls into the bin the chute faces and is scored
83 function drop(s, b) {
84 s.dropped += 1;
85 if (b.colour === s.chute) {
86 b.fate = 'sorted';
87 s.sorted += 1; s.streak += 1; s.score += POINT + (BONUS[s.streak] || 0);
88 s.best = Math.max(s.best, s.streak);
89 } else {
90 b.fate = 'cracked';
91 s.cracks += 1; s.streak = 0;
92 }
93 }
94
95 // step(state): advances the belt one tick; bottles reaching the end drop, furthest first. The third crack or the
96 // last drop ends the shift.
97 function step(state) {
98 if (state.status !== 'playing') return reject(state, 'game-over');
99 const s = clone(state);
100 const sp = speedAt(s.dropped);
101 s.tick += 1;
102 for (const b of s.bottles) if (b.fate === 'riding') b.x += sp;
103 const arriving = s.bottles.filter(b => b.fate === 'riding' && b.x >= BELT).sort((p, q) => q.x - p.x || p.id - q.id);
104 for (const b of arriving) {
105 drop(s, b);
106 if (s.cracks >= CRACKS) break;
107 }
108 if (s.cracks >= CRACKS || s.dropped >= s.bottles.length) s.status = 'over';
109 return done(s);
110 }
111
112 const api = {
113 COLOURS, BINS, BOTTLES, BELT, FIRST_GAP, GAP_MIN, GAP_MAX, SPEEDS, CRACKS, POINT, BONUS,
114 start, step, aim, speedAt, describe,
115 };
116 if (typeof module !== 'undefined') module.exports = api; else root.BottleBank = api;
117 })(typeof window !== 'undefined' ? window : globalThis);
bottle-bank/bins.test.mjs added +114
@@ -0,0 +1,114 @@
1 import { test, expect } from 'bun:test';
2 import {
3 BINS, BOTTLES, BELT, GAP_MIN, GAP_MAX, SPEEDS, CRACKS, BONUS, start, step, aim, speedAt,
4 } from './bins.js';
5
6 const ok = r => { expect(r.ok).toBe(true); return r.state; };
7 // a hand-built shift: bottles of the given colours, each already `lead` cells from the end, one per tick at speed 1
8 const shift = (colours, gap = 3) => {
9 const s = start(1);
10 s.bottles = colours.map((colour, id) => ({ id, colour, x: BELT - 1 - id * gap, fate: 'riding' }));
11 return s;
12 };
13 // run until the next drop; returns the state
14 const untilDrop = s => { const n = s.dropped; while (s.status === 'playing' && s.dropped === n) s = ok(step(s)); return s; };
15
16 test('start: same seed, same bottle order and same shift; different seed differs', () => {
17 const a = start(7), b = start(7), c = start(8);
18 expect(a.bottles).toEqual(b.bottles);
19 expect(a.bottles).not.toEqual(c.bottles);
20 expect(a.bottles.length).toBe(BOTTLES);
21 expect(a.bottles.every(x => x.colour >= 0 && x.colour < BINS)).toBe(true);
22 expect(new Set(a.bottles.map(x => x.colour)).size).toBe(3);
23 a.bottles.forEach((x, i) => {
24 if (i) { const g = a.bottles[i - 1].x - x.x; expect(g).toBeGreaterThanOrEqual(GAP_MIN); expect(g).toBeLessThanOrEqual(GAP_MAX); }
25 });
26 let x = a, y = b;
27 while (x.status === 'playing') { x = ok(aim(x, x.tick % 3)); y = ok(aim(y, y.tick % 3)); x = ok(step(x)); y = ok(step(y)); }
28 expect(x).toEqual(y);
29 expect(start(NaN).seed).toBe(0);
30 });
31
32 test('belt speed rises at the stated points', () => {
33 expect(SPEEDS).toEqual([{ from: 0, speed: 1 }, { from: 8, speed: 2 }, { from: 16, speed: 3 }]);
34 expect([speedAt(0), speedAt(7), speedAt(8), speedAt(15), speedAt(16), speedAt(23)]).toEqual([1, 1, 2, 2, 3, 3]);
35 let s = start(3), moved = s.bottles[0].x;
36 s = ok(step(s));
37 expect(s.bottles[0].x - moved).toBe(1);
38 s = { ...s, dropped: 8 }; moved = s.bottles[0].x; s = ok(step(s));
39 expect(s.bottles[0].x - moved).toBe(2);
40 s = { ...s, dropped: 16 }; moved = s.bottles[0].x; s = ok(step(s));
41 expect(s.bottles[0].x - moved).toBe(3);
42 });
43
44 test('a bottle drops only when it reaches the end, into the bin the chute faces', () => {
45 let s = shift([2]);
46 s = ok(aim(s, 2));
47 expect(s.bottles[0].fate).toBe('riding');
48 s = ok(step(s)); // x = BELT
49 expect([s.dropped, s.sorted, s.score, s.bottles[0].fate]).toEqual([1, 1, 1, 'sorted']);
50 // swinging after the bottle is on the belt but before the end changes the outcome
51 s = shift([1]); s.bottles[0].x = BELT - 2;
52 s = ok(step(s)); expect(s.dropped).toBe(0);
53 s = ok(aim(s, 1)); s = ok(step(s));
54 expect(s.bottles[0].fate).toBe('sorted');
55 });
56
57 test('a wrong drop is a crack and resets the streak', () => {
58 let s = shift([0, 0, 1]);
59 s = untilDrop(s); s = untilDrop(s);
60 expect([s.streak, s.sorted]).toEqual([2, 2]);
61 s = untilDrop(s); // chute still on clear, bottle green
62 expect([s.cracks, s.streak, s.sorted, s.best, s.bottles[2].fate]).toEqual([1, 0, 2, 2, 'cracked']);
63 expect(s.status).toBe('over'); // last bottle ends it
64 });
65
66 test('streak lengths add their stated bonus', () => {
67 expect(BONUS).toEqual({ 3: 2, 5: 3, 8: 5 });
68 let s = shift(Array(9).fill(0));
69 const scores = [];
70 for (let i = 0; i < 9; i++) { s = untilDrop(s); scores.push(s.score); }
71 // 1 point each, plus 2 at the 3rd, 3 at the 5th, 5 at the 8th
72 expect(scores).toEqual([1, 2, 5, 6, 10, 11, 12, 18, 19]);
73 expect([s.sorted, s.best, s.cracks]).toEqual([9, 9, 0]);
74 });
75
76 test('refusals give their reason and the very same state', () => {
77 const s = start(2);
78 for (const bin of [-1, 3, 1.5, NaN, '0', null, undefined]) {
79 const r = aim(s, bin); expect([r.ok, r.why]).toEqual([false, 'bad-bin']); expect(r.state).toBe(s);
80 }
81 let o = shift([1]); o = untilDrop(o);
82 expect(o.status).toBe('over');
83 for (const r of [aim(o, 0), step(o)]) { expect([r.ok, r.why]).toEqual([false, 'game-over']); expect(r.state).toBe(o); }
84 expect(aim(s, 2).state).not.toBe(s); // accepted calls never mutate the input
85 expect(s.chute).toBe(0);
86 });
87
88 test('the third crack ends the shift, leaving the rest on the belt', () => {
89 expect(CRACKS).toBe(3);
90 let s = shift([1, 1, 1, 1, 1]); // chute on clear: every drop cracks
91 s = untilDrop(s); s = untilDrop(s);
92 expect([s.cracks, s.status]).toEqual([2, 'playing']);
93 s = untilDrop(s);
94 expect([s.cracks, s.status, s.dropped]).toEqual([3, 'over', 3]);
95 expect(s.bottles.filter(b => b.fate === 'riding').length).toBe(2);
96 });
97
98 test('the last bottle ends the shift and the end line reports sorted, cracks and best streak', () => {
99 let s = shift([0, 0, 1, 1]);
100 s = untilDrop(s); s = untilDrop(s);
101 expect(s.status).toBe('playing');
102 expect(s.line).toContain('2 sorted');
103 s = untilDrop(s); s = ok(aim(s, 1)); s = untilDrop(s);
104 expect(s.status).toBe('over');
105 expect(s.line).toBe('Shift over: 3 sorted, 1 crack, best streak 2, score 3');
106 });
107
108 test('a whole seeded shift always ends and drops every bottle or cracks out', () => {
109 let s = start(11), n = 0;
110 while (s.status === 'playing' && n++ < 1000) s = ok(step(s));
111 expect(s.status).toBe('over');
112 expect(s.cracks >= CRACKS || s.dropped === BOTTLES).toBe(true);
113 expect(s.sorted + s.cracks).toBe(s.dropped);
114 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs