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

Migrated from github.com/amirmushichge/pixel-plays

Jam Jars rules: a tested `jam-jars/shelf.js` where you pour layers of fruit between jars until each holds one fruit, within par pours, from plain data, in a two-file pull with a test file that runs in under a second #274

Merged opened this

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

Merged

vesper/pixel-plays:vesper/257-jam-jars-rules-a-tested-jam-jars-shelf-j → main 1 commit fork

  • Merged. vesper/257-jam-jars-rules-a-tested-jam-jars-shelf-j was merged into main as 9b786b7.

Review

Sign in to review this change.
2 files changed +310 −0
jam-jars/shelf.js added +120
@@ -0,0 +1,120 @@
1 'use strict';
2 // The Jam Jars rules: a pantry shelf of jars stacked with layers of fruit. Pour the top run of one fruit from one jar
3 // into another until every jar is empty or full of a single fruit, within the level's par number of pours.
4 // Plain data in, plain data out, no DOM, no timers, no randomness: the levels are written by hand below.
5 // A rejected call returns the very same state and says why. The page (not yet written) draws what this decides.
6 //
7 // A jar is a list of fruit names from bottom to top. Every jar holds at most `capacity` layers. Each level's par is the
8 // fewest pours that solve it (the test searches every level to prove it can be solved and that par is reachable).
9 (function (root) {
10 const LEVEL_SCORE = 100; // points for solving a level
11 const PAR_BONUS = 50; // extra points for solving it in par pours or fewer
12
13 // hand-made levels: capacity, jars (bottom to top) and par
14 const LEVELS = [
15 { name: 'First Shelf', capacity: 3, par: 5, jars: [['plum', 'fig', 'plum'], ['fig', 'plum', 'fig'], []] },
16 { name: 'Berry Row', capacity: 4, par: 7, jars: [
17 ['plum', 'fig', 'plum', 'fig'], ['fig', 'plum', 'fig', 'plum'], []] },
18 { name: 'Three Fruits', capacity: 3, par: 7, jars: [
19 ['plum', 'fig', 'quince'], ['quince', 'plum', 'fig'], ['fig', 'quince', 'plum'], []] },
20 { name: 'Full Pantry', capacity: 4, par: 10, jars: [
21 ['plum', 'fig', 'quince', 'plum'], ['fig', 'quince', 'plum', 'fig'], ['quince', 'plum', 'fig', 'quince'], [], []] },
22 ];
23
24 // the top run of matching layers of a jar: { fruit, count }, or null when the jar is empty
25 function top(jar) {
26 if (!jar.length) return null;
27 const fruit = jar[jar.length - 1];
28 let count = 0;
29 while (count < jar.length && jar[jar.length - 1 - count] === fruit) count++;
30 return { fruit, count };
31 }
32
33 // every jar is empty or full of one fruit
34 const sorted = (jars, capacity) =>
35 jars.every(j => j.length === 0 || (j.length === capacity && j.every(f => f === j[0])));
36
37 const clone = jars => jars.map(j => j.slice());
38 const refuse = (s, why) => ({ ok: false, why, event: '', state: s });
39
40 // '' when the pour is allowed, otherwise why not
41 function check(jars, capacity, from, to) {
42 const n = jars.length;
43 if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to < 0 || from >= n || to >= n) return 'bad-jar';
44 if (from === to) return 'same-jar';
45 if (!jars[from].length) return 'empty';
46 if (jars[to].length >= capacity) return 'full';
47 const t = top(jars[to]);
48 if (t && t.fruit !== top(jars[from]).fruit) return 'mismatch';
49 return '';
50 }
51
52 // refresh the derived field: the line
53 function refresh(s) {
54 s.line = s.status === 'won'
55 ? `Shelf done, you win: ${s.totalPours} pours against a par of ${s.totalPar}, ${s.score} points`
56 : `Level ${s.level + 1} of ${s.levels}: ${s.moves} pours, par ${s.par}, ${s.score} points`;
57 return s;
58 }
59
60 // load(level, carry) -> a shelf on level `level` (0-based), carrying score and totals from the levels before it
61 function load(level, carry) {
62 const L = LEVELS[level];
63 return refresh({
64 level, levels: LEVELS.length, name: L.name, capacity: L.capacity, par: L.par,
65 jars: clone(L.jars), history: [], moves: 0, score: carry.score, totalPours: carry.totalPours,
66 totalPar: carry.totalPar, levelScore: LEVEL_SCORE, parBonus: PAR_BONUS, status: 'playing', line: '',
67 });
68 }
69
70 // start(level = 0) -> the shelf for that level; an unknown level starts the first
71 const start = (level = 0) =>
72 load(Number.isInteger(level) && level >= 0 && level < LEVELS.length ? level : 0,
73 { score: 0, totalPours: 0, totalPar: 0 });
74
75 const copy = s => Object.assign({}, s, { jars: clone(s.jars), history: s.history.slice() });
76
77 // pour(state, from, to) -> { ok, why, event, state }: moves the top run of matching layers of jar `from` onto jar
78 // `to`, as many as fit. event is 'poured', 'solved' (the level is solved: it scored and the next begins) or 'won'
79 // (the last level is solved). Refused: 'over', 'bad-jar', 'same-jar', 'empty', 'full', 'mismatch'.
80 function pour(s, from, to) {
81 if (s.status !== 'playing') return refuse(s, 'over');
82 const why = check(s.jars, s.capacity, from, to);
83 if (why) return refuse(s, why);
84 const n = copy(s);
85 n.history.push(clone(s.jars));
86 const t = top(n.jars[from]);
87 const moved = Math.min(t.count, n.capacity - n.jars[to].length);
88 for (let i = 0; i < moved; i++) n.jars[to].push(n.jars[from].pop());
89 n.moves += 1;
90 if (!sorted(n.jars, n.capacity)) return { ok: true, why: '', event: 'poured', state: refresh(n) };
91 const score = n.score + LEVEL_SCORE + (n.moves <= n.par ? PAR_BONUS : 0);
92 const carry = { score, totalPours: n.totalPours + n.moves, totalPar: n.totalPar + n.par };
93 if (n.level + 1 < LEVELS.length) return { ok: true, why: '', event: 'solved', state: load(n.level + 1, carry) };
94 return { ok: true, why: '', event: 'won', state: refresh(Object.assign(n, carry, { status: 'won' })) };
95 }
96
97 // undo(state) -> { ok, why, event, state }: reverses the last pour of this level. It costs a move.
98 // Refused with 'nothing' when there is no pour to reverse and 'over' once the game is won.
99 function undo(s) {
100 if (s.status !== 'playing') return refuse(s, 'over');
101 if (!s.history.length) return refuse(s, 'nothing');
102 const n = copy(s);
103 n.jars = n.history.pop();
104 n.moves += 1;
105 return { ok: true, why: '', event: 'undone', state: refresh(n) };
106 }
107
108 // restart(state) -> the current level again from its first jars; the score and totals from earlier levels stay and
109 // the pours spent here are forgotten. There is no loss, only this.
110 function restart(s) {
111 const earlier = { score: s.score, totalPours: s.totalPours, totalPar: s.totalPar };
112 if (s.status === 'won') return { ok: false, why: 'over', event: '', state: s };
113 return { ok: true, why: '', event: 'restarted', state: load(s.level, earlier) };
114 }
115
116 const api = {
117 LEVEL_SCORE, PAR_BONUS, LEVELS, top, sorted, start, pour, undo, restart,
118 };
119 if (typeof module !== 'undefined') module.exports = api; else root.JamJars = api;
120 })(typeof window !== 'undefined' ? window : globalThis);
jam-jars/shelf.test.mjs added +190
@@ -0,0 +1,190 @@
1 import { test, expect } from 'bun:test';
2 import { LEVELS, LEVEL_SCORE, PAR_BONUS, top, sorted, start, pour, undo, restart } from './shelf.js';
3
4 // a state with hand-written jars, so each rule is checked against a count done by hand
5 const withJars = (jars, over = {}) => ({ ...start(0), capacity: 4, jars, history: [], moves: 0, ...over });
6
7 // breadth-first search: the fewest pours that solve a level, or -1
8 function fewest(level) {
9 const s0 = start(level);
10 const seen = new Set([JSON.stringify(s0.jars)]);
11 let layer = [s0], depth = 0;
12 while (layer.length) {
13 depth++;
14 const next = [];
15 for (const s of layer) {
16 for (let a = 0; a < s.jars.length; a++) for (let b = 0; b < s.jars.length; b++) {
17 const r = pour(s, a, b);
18 if (!r.ok) continue;
19 if (r.event !== 'poured') return depth;
20 const k = JSON.stringify(r.state.jars);
21 if (!seen.has(k)) { seen.add(k); next.push(r.state); }
22 }
23 }
24 layer = next;
25 }
26 return -1;
27 }
28
29 test('every level is solvable, and its stated par is the fewest pours', () => {
30 expect(LEVELS.length).toBeGreaterThanOrEqual(3);
31 LEVELS.forEach((L, i) => {
32 const s = start(i);
33 expect([s.level, s.par, s.capacity, s.moves]).toEqual([i, L.par, L.capacity, 0]);
34 expect(s.jars.some(j => j.length === 0)).toBe(true);
35 expect(s.jars.every(j => j.length <= s.capacity)).toBe(true);
36 expect(sorted(s.jars, s.capacity)).toBe(false);
37 expect(fewest(i)).toBe(L.par);
38 });
39 });
40
41 test('a pour from an empty jar is refused and the state is unchanged', () => {
42 const s = withJars([['plum'], [], []]);
43 const r = pour(s, 1, 0);
44 expect([r.ok, r.why, r.state]).toEqual([false, 'empty', s]);
45 });
46
47 test('a pour into a full jar is refused', () => {
48 const s = withJars([['plum'], ['fig', 'fig', 'fig', 'fig']]);
49 const r = pour(s, 0, 1);
50 expect([r.ok, r.why, r.state]).toEqual([false, 'full', s]);
51 });
52
53 test('a pour from a jar into itself is refused', () => {
54 const s = withJars([['plum', 'fig'], []]);
55 const r = pour(s, 0, 0);
56 expect([r.ok, r.why, r.state]).toEqual([false, 'same-jar', s]);
57 });
58
59 test('a pour onto a different fruit is refused, onto the same fruit or an empty jar is allowed', () => {
60 const s = withJars([['plum', 'fig'], ['plum'], []]);
61 const r = pour(s, 0, 1);
62 expect([r.ok, r.why, r.state]).toEqual([false, 'mismatch', s]);
63 expect(pour(s, 0, 2).state.jars).toEqual([['plum'], ['plum'], ['fig']]);
64 expect(pour(s, 1, 0).why).toBe('mismatch');
65 const t = withJars([['fig', 'plum'], ['plum'], ['quince']]);
66 expect(pour(t, 1, 0).state.jars).toEqual([['fig', 'plum', 'plum'], [], ['quince']]);
67 });
68
69 test('a bad jar number is refused', () => {
70 const s = withJars([['plum'], []]);
71 for (const [a, b] of [[-1, 0], [0, 2], [0.5, 1], ['0', 1], [NaN, 1]]) expect(pour(s, a, b).why).toBe('bad-jar');
72 });
73
74 test('a run of matching layers moves together', () => {
75 const s = withJars([['quince', 'fig', 'fig', 'fig'], [], ['plum']]);
76 const r = pour(s, 0, 1);
77 expect(r.state.jars).toEqual([['quince'], ['fig', 'fig', 'fig'], ['plum']]);
78 expect(top(r.state.jars[1])).toEqual({ fruit: 'fig', count: 3 });
79 });
80
81 test('only as many layers move as fit', () => {
82 const s = withJars([['quince', 'fig', 'fig', 'fig'], ['plum', 'fig', 'fig']]);
83 const r = pour(s, 0, 1);
84 expect(r.state.jars).toEqual([['quince', 'fig', 'fig'], ['plum', 'fig', 'fig', 'fig']]);
85 expect(r.state.moves).toBe(1);
86 });
87
88 test('every accepted pour counts as one move and a refused one counts none', () => {
89 let s = withJars([['plum', 'fig'], [], []]);
90 expect(pour(s, 1, 0).state.moves).toBe(0);
91 s = pour(s, 0, 1).state;
92 s = pour(s, 0, 2).state;
93 expect(s.moves).toBe(2);
94 });
95
96 test('undo reverses the last pour and costs a move', () => {
97 const s0 = start(0);
98 const a = pour(s0, 0, 2).state;
99 const b = pour(a, 1, 0);
100 expect(b.ok).toBe(true);
101 const r = undo(b.state);
102 expect([r.ok, r.event]).toEqual([true, 'undone']);
103 expect(r.state.jars).toEqual(a.jars);
104 expect(r.state.moves).toBe(3);
105 expect(undo(r.state).state.jars).toEqual(s0.jars);
106 expect(undo(undo(r.state).state).why).toBe('nothing');
107 expect(undo(s0)).toEqual({ ok: false, why: 'nothing', event: '', state: s0 });
108 });
109
110 test('a level is solved when every jar is empty or full of one fruit', () => {
111 expect(sorted([['fig', 'fig', 'fig', 'fig'], [], ['plum', 'plum', 'plum', 'plum']], 4)).toBe(true);
112 expect(sorted([['fig', 'fig', 'fig'], ['fig']], 4)).toBe(false);
113 expect(sorted([['fig', 'fig', 'fig', 'plum'], []], 4)).toBe(false);
114 });
115
116 // the last pour of level 1 (index 0): jars one pour from sorted
117 const nearly = (moves) => ({ ...start(0), capacity: 3, jars: [['plum', 'plum'], ['fig', 'fig', 'fig'], ['plum']], moves });
118
119 test('solving at par or under scores the level and the par bonus, and the next level begins', () => {
120 const s = nearly(LEVELS[0].par - 1);
121 const r = pour(s, 2, 0);
122 expect(r.event).toBe('solved');
123 expect(r.state.score).toBe(LEVEL_SCORE + PAR_BONUS);
124 expect([r.state.level, r.state.moves, r.state.jars]).toEqual([1, 0, LEVELS[1].jars]);
125 expect([r.state.totalPours, r.state.totalPar]).toEqual([LEVELS[0].par, LEVELS[0].par]);
126 });
127
128 test('solving over par scores the level without the bonus', () => {
129 const r = pour(nearly(LEVELS[0].par), 2, 0);
130 expect(r.event).toBe('solved');
131 expect(r.state.score).toBe(LEVEL_SCORE);
132 expect(r.state.totalPours).toBe(LEVELS[0].par + 1);
133 });
134
135 test('restart begins the current level again and keeps what earlier levels scored', () => {
136 let s = pour(nearly(0), 2, 0).state; // now on level 2 with a score
137 s = pour(s, 0, 2).state;
138 const r = restart(s);
139 expect(r.ok).toBe(true);
140 expect(r.state.jars).toEqual(LEVELS[1].jars);
141 expect([r.state.moves, r.state.history, r.state.level, r.state.score]).toEqual([0, [], 1, s.score]);
142 });
143
144 test('the last level ends the game with a win line of total pours against total par', () => {
145 const last = LEVELS.length - 1;
146 const base = start(last);
147 const s = {
148 ...base, jars: [['fig', 'fig', 'fig', 'fig'], ['plum', 'plum', 'plum', 'plum'], ['quince', 'quince', 'quince'], ['quince'], []],
149 moves: 4, score: 300, totalPours: 20, totalPar: 18,
150 };
151 const r = pour(s, 3, 2);
152 expect(r.event).toBe('won');
153 expect(r.state.status).toBe('won');
154 expect(r.state.totalPours).toBe(25);
155 expect(r.state.totalPar).toBe(18 + LEVELS[last].par);
156 expect(r.state.score).toBe(300 + LEVEL_SCORE + PAR_BONUS);
157 expect(r.state.line).toContain(`25 pours against a par of ${18 + LEVELS[last].par}`);
158 expect(pour(r.state, 0, 1).why).toBe('over');
159 expect(undo(r.state).why).toBe('over');
160 expect(restart(r.state).ok).toBe(false);
161 });
162
163 test('playing every level through by its shortest solution reaches the win line', () => {
164 let s = start(0);
165 const path = (st) => { // depth-limited search for the pours that solve the shown level
166 const go = (x, left, acc) => {
167 for (let a = 0; a < x.jars.length; a++) for (let b = 0; b < x.jars.length; b++) {
168 const r = pour(x, a, b);
169 if (!r.ok) continue;
170 if (r.event !== 'poured') return [...acc, [a, b]];
171 if (left > 1) { const p = go(r.state, left - 1, [...acc, [a, b]]); if (p) return p; }
172 }
173 return null;
174 };
175 return go(st, st.par, []);
176 };
177 let last;
178 for (let i = 0; i < LEVELS.length; i++) {
179 for (const [a, b] of path(s)) { last = pour(s, a, b); s = last.state; }
180 }
181 expect(last.event).toBe('won');
182 expect(s.totalPours).toBe(s.totalPar);
183 expect(s.score).toBe(LEVELS.length * (LEVEL_SCORE + PAR_BONUS));
184 });
185
186 test('start is deterministic and an unknown level starts the first', () => {
187 expect(start(2)).toEqual(start(2));
188 expect(start(99)).toEqual(start(0));
189 expect(start(-1).level).toBe(0);
190 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs