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

Migrated from github.com/amirmushichge/pixel-plays

Pancake Griddle rules: a tested `pancake-griddle/griddle.js` where you pour, flip and serve pancakes on a busy griddle before they burn, from plain data, in a two-file pull with a test file that runs in under a second #314

Merged opened this

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

Merged

torque/pixel-plays:torque/300-pancake-griddle-rules-a-tested-pancake-g → main 1 commit fork

  • Merged. torque/300-pancake-griddle-rules-a-tested-pancake-g was merged into main as a7f9142.

Review

Sign in to review this change.
2 files changed +316 −0
pancake-griddle/griddle.js added +175
@@ -0,0 +1,175 @@
1 'use strict';
2 // The Pancake Griddle rules: pour batter onto a griddle of rings, flip each pancake when its underside is golden,
3 // and serve it to the oldest waiting order once both sides are done, before anything burns. Plain data in, plain
4 // data out, no DOM, no timers, no Math.random: the order queue comes from the seed. A rejected call returns the very
5 // same state and says why.
6 //
7 // Units: seconds and points. A side only cooks while it is face down; `t` is its total face-down time.
8 // doneness(t) = raw for t < GOLD_FROM
9 // golden for GOLD_FROM ≤ t ≤ GOLD_TO (the stated window)
10 // burnt for t > GOLD_TO
11 // t is closed-form: t = banked + (now − since), so doneness never depends on how time was sliced into ticks.
12 // Burn and patience events are placed at their exact times and applied in time order within a tick.
13 (function (root) {
14 const RINGS = 4; // rings on the griddle, numbered 0..RINGS-1
15 const LIVES = 3;
16 const ROUND = 60; // s, the round length
17 const GOLD_FROM = 4; // s face down before a side is golden
18 const GOLD_TO = 7; // s face down after which a side is burnt (the golden window is 3 s)
19 const ORDERS = 14; // orders in the queue
20 const FIRST_AT = 2; // s, earliest first arrival
21 const GAP_MIN = 2.5, GAP_MAX = 4.5; // s between arrivals
22 const PATIENCE_MIN = 14, PATIENCE_MAX = 22; // s an order waits before it walks away
23 const SERVE_SCORE = 100; // points for a pancake golden on both sides
24 const TIP = 50; // extra points when served within half the order's patience
25
26 // mulberry32 as a pure step: next(seed) -> [value in [0,1), nextSeed]
27 function next(r) {
28 r = (r + 0x6D2B79F5) >>> 0;
29 let t = r;
30 t = Math.imul(t ^ (t >>> 15), t | 1);
31 t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
32 return [((t ^ (t >>> 14)) >>> 0) / 4294967296, r];
33 }
34
35 // doneness(t) -> 'raw' | 'golden' | 'burnt' for t seconds face down
36 const doneness = t => t < GOLD_FROM ? 'raw' : t <= GOLD_TO ? 'golden' : 'burnt';
37
38 // faceDown(pancake, time) -> seconds the side now face down has cooked in total
39 const faceDown = (p, time) => p.sides[p.down] + Math.max(0, time - p.since);
40
41 // sideTimes(pancake, time) -> [t0, t1] total face-down seconds of both sides at an absolute time
42 function sideTimes(p, time) {
43 const t = p.sides.slice();
44 t[p.down] = faceDown(p, time);
45 return t;
46 }
47
48 const plural = (n, w) => `${n} ${n === 1 ? w : w === 'life' ? 'lives' : w + 's'}`;
49
50 function describe(s) {
51 const served = s.orders.filter(o => o.status === 'served').length;
52 if (s.status === 'won') return `You win: round over with ${plural(s.lives, 'life')} left, score ${s.score}, ${plural(served, 'order')} served`;
53 if (s.status === 'lost') return `You lose: no lives left, score ${s.score}, ${plural(served, 'order')} served`;
54 return `${plural(s.pancakes.filter(Boolean).length, 'pancake')} on ${RINGS} rings, ${plural(s.lives, 'life')}, score ${s.score}`;
55 }
56
57 // start(seed) -> an empty griddle and the whole seeded queue of orders
58 function start(seed) {
59 const sd = Number.isFinite(seed) ? Math.trunc(seed) >>> 0 : 0;
60 let rng = sd, at = 0;
61 const orders = [];
62 for (let i = 0; i < ORDERS; i++) {
63 let a, b;
64 [a, rng] = next(rng); [b, rng] = next(rng);
65 at += i === 0 ? FIRST_AT + a * GAP_MIN : GAP_MIN + a * (GAP_MAX - GAP_MIN);
66 orders.push({ id: i, at, patience: PATIENCE_MIN + b * (PATIENCE_MAX - PATIENCE_MIN), status: 'waiting' });
67 }
68 const s = {
69 seed: sd, status: 'playing', time: 0, lives: LIVES, score: 0,
70 pancakes: Array.from({ length: RINGS }, () => null), orders, line: '',
71 };
72 s.line = describe(s);
73 return s;
74 }
75
76 const reject = (state, why) => ({ ok: false, state, why });
77 const clone = s => ({
78 ...s,
79 pancakes: s.pancakes.map(p => p && { ...p, sides: p.sides.slice() }),
80 orders: s.orders.map(o => ({ ...o })),
81 });
82 const done = s => { s.line = describe(s); return { ok: true, state: s, why: '' }; };
83
84 // lose(s): costs a life; the game is lost when none are left
85 function lose(s) {
86 s.lives -= 1;
87 if (s.lives <= 0) s.status = 'lost';
88 }
89
90 // tick(state, dt) -> { ok, state, why }: advances dt seconds; pancakes burn and orders give up at their exact times
91 function tick(state, dt) {
92 if (typeof dt !== 'number' || !Number.isFinite(dt) || dt <= 0) return reject(state, 'bad-dt');
93 if (state.status !== 'playing') return reject(state, 'game-over');
94 const end = Math.min(state.time + dt, ROUND);
95 const s = clone(state);
96 const events = [];
97 s.pancakes.forEach((p, ring) => {
98 if (!p) return;
99 const at = p.since + (GOLD_TO - p.sides[p.down]); // the instant the face-down side passes the window
100 if (at < end) events.push({ at, kind: 0, ring });
101 });
102 for (const o of s.orders) {
103 if (o.status === 'waiting' && o.at + o.patience < end) events.push({ at: o.at + o.patience, kind: 1, id: o.id });
104 }
105 events.sort((a, b) => a.at - b.at || a.kind - b.kind || (a.ring ?? a.id) - (b.ring ?? b.id));
106 for (const e of events) {
107 if (e.kind === 0) s.pancakes[e.ring] = null; else s.orders[e.id].status = 'expired';
108 s.time = Math.max(s.time, e.at);
109 lose(s);
110 if (s.status === 'lost') return done(s);
111 }
112 s.time = end;
113 if (end >= ROUND) s.status = 'won';
114 return done(s);
115 }
116
117 // ringCheck(state, ring) -> a reason string, or '' when the game is on and the ring is a real ring
118 function ringCheck(state, ring) {
119 if (state.status !== 'playing') return 'game-over';
120 if (!Number.isInteger(ring) || ring < 0 || ring >= RINGS) return 'bad-ring';
121 return '';
122 }
123
124 // pour(state, ring): starts a raw pancake on an empty ring
125 function pour(state, ring) {
126 const why = ringCheck(state, ring);
127 if (why) return reject(state, why);
128 if (state.pancakes[ring]) return reject(state, 'busy');
129 const s = clone(state);
130 s.pancakes[ring] = { sides: [0, 0], down: 0, since: s.time };
131 return done(s);
132 }
133
134 // flip(state, ring): banks the cooking of the side face down and turns the pancake over
135 function flip(state, ring) {
136 const why = ringCheck(state, ring);
137 if (why) return reject(state, why);
138 const p = state.pancakes[ring];
139 if (!p) return reject(state, 'empty');
140 const s = clone(state);
141 const q = s.pancakes[ring];
142 q.sides[q.down] = faceDown(p, s.time);
143 q.down = 1 - q.down;
144 q.since = s.time;
145 return done(s);
146 }
147
148 // serve(state, ring): hands the pancake to the oldest waiting order that has arrived.
149 // Golden on both sides scores SERVE_SCORE (+ TIP within half the patience); a raw or burnt side costs a life.
150 function serve(state, ring) {
151 const why = ringCheck(state, ring);
152 if (why) return reject(state, why);
153 const p = state.pancakes[ring];
154 if (!p) return reject(state, 'empty');
155 if (!state.orders.some(o => o.status === 'waiting' && o.at <= state.time)) return reject(state, 'no-order');
156 const s = clone(state);
157 const o = s.orders.find(q => q.status === 'waiting' && q.at <= s.time);
158 const good = sideTimes(p, s.time).every(t => doneness(t) === 'golden');
159 s.pancakes[ring] = null;
160 if (good) {
161 o.status = 'served';
162 s.score += SERVE_SCORE + (s.time - o.at <= o.patience / 2 ? TIP : 0);
163 } else {
164 o.status = 'failed';
165 lose(s);
166 }
167 return done(s);
168 }
169
170 const api = {
171 RINGS, LIVES, ROUND, GOLD_FROM, GOLD_TO, ORDERS, FIRST_AT, GAP_MIN, GAP_MAX, PATIENCE_MIN, PATIENCE_MAX,
172 SERVE_SCORE, TIP, start, tick, pour, flip, serve, doneness, faceDown, sideTimes, describe,
173 };
174 if (typeof module !== 'undefined') module.exports = api; else root.PancakeGriddle = api;
175 })(typeof window !== 'undefined' ? window : globalThis);
pancake-griddle/griddle.test.mjs added +141
@@ -0,0 +1,141 @@
1 import { test, expect } from 'bun:test';
2 import {
3 RINGS, LIVES, ROUND, GOLD_FROM, GOLD_TO, ORDERS, GAP_MIN, GAP_MAX, PATIENCE_MIN, PATIENCE_MAX, SERVE_SCORE, TIP,
4 start, tick, pour, flip, serve, doneness, sideTimes,
5 } from './griddle.js';
6
7 const ok = r => { expect(r.ok).toBe(true); return r.state; };
8 const order = (id, at, patience = 20) => ({ id, at, patience, status: 'waiting' });
9 const game = (orders = [order(0, 0)]) => ({ ...start(1), orders });
10 // a pancake poured at 0, flipped at `f`, served at `t`
11 const cook = (s, f, t) => {
12 s = ok(pour(s, 0)); s = ok(tick(s, f)); s = ok(flip(s, 0)); return ok(tick(s, t - f));
13 };
14
15 test('start: stated rings, lives, round and a seeded queue; same seed, same orders', () => {
16 const a = start(5), b = start(5), c = start(6);
17 expect([RINGS, LIVES, ROUND, a.status, a.lives, a.score, a.pancakes.length]).toEqual([4, 3, 60, 'playing', 3, 0, 4]);
18 expect(a.pancakes.every(p => p === null)).toBe(true);
19 expect(a.orders.length).toBe(ORDERS);
20 expect(a.orders).toEqual(b.orders);
21 expect(a.orders).not.toEqual(c.orders);
22 a.orders.forEach((o, i) => {
23 expect(o.patience).toBeGreaterThanOrEqual(PATIENCE_MIN); expect(o.patience).toBeLessThanOrEqual(PATIENCE_MAX);
24 if (i) { const g = o.at - a.orders[i - 1].at; expect(g).toBeGreaterThanOrEqual(GAP_MIN); expect(g).toBeLessThanOrEqual(GAP_MAX); }
25 });
26 expect(a.orders.at(-1).at).toBeLessThan(ROUND);
27 expect(start(NaN).seed).toBe(0);
28 });
29
30 test('windows: raw below 4 s, golden 4 to 7 s inclusive, burnt above', () => {
31 expect([doneness(0), doneness(3.99), doneness(4), doneness(7), doneness(7.01)])
32 .toEqual(['raw', 'raw', 'golden', 'golden', 'burnt']);
33 expect([GOLD_FROM, GOLD_TO]).toEqual([4, 7]);
34 });
35
36 test('doneness is the same however time is sliced', () => {
37 let a = ok(pour(game(), 0)); a = ok(tick(a, 5)); a = ok(flip(a, 0)); a = ok(tick(a, 3.5));
38 let b = ok(pour(game(), 0));
39 for (let i = 0; i < 50; i++) b = ok(tick(b, 0.1));
40 b = ok(flip(b, 0));
41 for (let i = 0; i < 35; i++) b = ok(tick(b, 0.1));
42 const [x, y] = sideTimes(a.pancakes[0], a.time), [u, v] = sideTimes(b.pancakes[0], b.time);
43 expect(x).toBeCloseTo(u, 9); expect(y).toBeCloseTo(v, 9);
44 expect(x).toBeCloseTo(5, 9); expect(y).toBeCloseTo(3.5, 9);
45 const one = ok(tick(ok(pour(game(), 0)), 8)), many = ok(pour(game(), 0));
46 let m = many; for (let i = 0; i < 8; i++) m = ok(tick(m, 1));
47 expect([one.lives, one.pancakes[0]]).toEqual([m.lives, m.pancakes[0]]);
48 });
49
50 test('every refusal gives its reason and the same state', () => {
51 const s = ok(pour(game(), 1));
52 for (const dt of [0, -1, NaN, Infinity, '1', null, undefined]) {
53 const r = tick(s, dt); expect([r.ok, r.why, r.state]).toEqual([false, 'bad-dt', s]);
54 }
55 for (const f of [pour, flip, serve]) for (const ring of [-1, 4, 1.5, NaN, '0', undefined]) {
56 const r = f(s, ring); expect([r.ok, r.why, r.state]).toEqual([false, 'bad-ring', s]);
57 }
58 expect(pour(s, 1)).toEqual({ ok: false, state: s, why: 'busy' });
59 expect(flip(s, 0)).toEqual({ ok: false, state: s, why: 'empty' });
60 expect(serve(s, 0)).toEqual({ ok: false, state: s, why: 'empty' });
61 const none = ok(pour(game([order(0, 10)]), 0));
62 expect(serve(none, 0)).toEqual({ ok: false, state: none, why: 'no-order' });
63 const over = { ...s, status: 'lost' };
64 for (const r of [tick(over, 1), pour(over, 0), flip(over, 1), serve(over, 1)])
65 expect([r.ok, r.why, r.state]).toEqual([false, 'game-over', over]);
66 });
67
68 test('a good serve scores 100 and a tip within half the patience', () => {
69 // flip at 5 (golden 5), serve at 10 (other side 5): golden both; order waited 10 = half of 20 -> tip
70 const s = cook(game(), 5, 10);
71 const r = ok(serve(s, 0));
72 expect([r.score, r.lives, r.orders[0].status, r.pancakes[0]]).toEqual([SERVE_SCORE + TIP, LIVES, 'served', null]);
73 // order arrived at 0, served at 10.5 > half of 20: no tip
74 const late = ok(serve(cook(game(), 5, 10.5), 0));
75 expect(late.score).toBe(SERVE_SCORE);
76 });
77
78 test('serving goes to the oldest waiting order that has arrived', () => {
79 const g = game([order(0, 0, 20), order(1, 1, 20), order(2, 50)]);
80 const r = ok(serve(cook(g, 5, 10), 0));
81 expect(r.orders.map(o => o.status)).toEqual(['served', 'waiting', 'waiting']);
82 });
83
84 test('serving a raw or a burnt side costs a life and the order is lost', () => {
85 const raw = ok(serve(cook(game(), 2, 5), 0)); // first side 2 s, second 3 s
86 expect([raw.lives, raw.score, raw.orders[0].status, raw.pancakes[0]]).toEqual([2, 0, 'failed', null]);
87 const oneSide = ok(serve(ok(tick(ok(pour(game(), 0)), 5)), 0)); // underside never cooked
88 expect(oneSide.lives).toBe(2);
89 const burnt = ok(serve(cook(game(), 7, 7.5), 0)); // first side 7 golden, second 0.5 raw
90 expect(burnt.lives).toBe(2);
91 });
92
93 test('a pancake burns on the griddle once a side passes 7 s, costing a life', () => {
94 const g = ok(pour(game(), 0));
95 const at7 = ok(tick(g, 7));
96 expect([at7.lives, !!at7.pancakes[0]]).toEqual([3, true]); // exactly 7 s is still golden
97 const after = ok(tick(at7, 0.01));
98 expect([after.lives, after.pancakes[0]]).toEqual([2, null]);
99 // the side facing up does not cook, so a flipped pancake lasts another 7 s on the other side
100 const f = ok(tick(ok(flip(ok(tick(g, 6)), 0)), 6));
101 expect([f.lives, !!f.pancakes[0]]).toEqual([3, true]);
102 });
103
104 test('an order whose patience runs out costs a life', () => {
105 const g = game([order(0, 0, 15)]);
106 const edge = ok(tick(g, 15));
107 expect([edge.lives, edge.orders[0].status]).toEqual([3, 'waiting']);
108 const gone = ok(tick(edge, 0.5));
109 expect([gone.lives, gone.orders[0].status]).toEqual([2, 'expired']);
110 expect(serve(ok(pour(gone, 0)), 0).why).toBe('no-order');
111 });
112
113 test('the game is lost with a loss line when lives run out', () => {
114 let s = game([order(0, 0, 5), order(1, 0, 6), order(2, 0, 7), order(3, 0, 40)]);
115 s = ok(tick(s, 7.5));
116 expect([s.status, s.lives, s.time]).toEqual(['lost', 0, 7]);
117 expect(s.line).toBe('You lose: no lives left, score 0, 0 orders served');
118 expect(tick(s, 1).why).toBe('game-over');
119 });
120
121 test('the round ends with a win line reporting score and orders served', () => {
122 let s = cook(game([order(0, 0, 40), order(1, 100)]), 5, 10);
123 s = ok(serve(s, 0));
124 s = ok(tick(s, 100));
125 expect([s.status, s.time, s.lives, s.score]).toEqual(['won', ROUND, 3, SERVE_SCORE + TIP]);
126 expect(s.line).toBe(`You win: round over with 3 lives left, score ${SERVE_SCORE + TIP}, 1 order served`);
127 expect(pour(s, 0).why).toBe('game-over');
128 });
129
130 test('a full seeded game replays identically', () => {
131 const play = () => {
132 let s = start(9);
133 for (let i = 0; i < 600; i++) {
134 if (s.status !== 'playing') break;
135 const r = i % 40 === 0 ? pour(s, (i / 40) % RINGS) : i % 40 === 20 ? serve(s, ((i - 20) / 40) % RINGS) : tick(s, 0.1);
136 if (r.ok) s = r.state;
137 }
138 return s;
139 };
140 expect(play()).toEqual(play());
141 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs