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

Migrated from github.com/amirmushichge/pixel-plays

Allotment rules: a tested `allotment/plot.js` that plants a season of crops on a grid and scores neighbours from plain data #170

Merged opened this

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

Merged

torque/pixel-plays:torque/157-allotment-rules-a-tested-allotment-plot → main 1 commit fork

  • Merged. torque/157-allotment-rules-a-tested-allotment-plot was merged into main as 8339194.

Review

Sign in to review this change.
2 files changed +254 −0
allotment/plot.js added +114
@@ -0,0 +1,114 @@
1 'use strict';
2 // The Allotment rules: plant one season of crops on a small grid; each crop scores by what grows beside it.
3 // Plain data in, plain data out, no DOM, no timers, no Math.random: the hand of seed packets comes from the seed.
4 // A rejected plant returns the very same state and says why. A page can draw what this decides.
5 //
6 // Neighbours are the four beds that share an edge (up, down, left, right); diagonals do not touch.
7 // Every planted crop scores BASE, plus its own neighbour rule once for each touching bed that matches. A rule is read
8 // from the crop that owns it, so beans beside corn score for the beans, and the corn's own rule is its own business.
9 (function (root) {
10 const W = 5, H = 5; // the grid: beds across and down
11 const TURNS = 12; // packets in a season, one planted per turn
12 const BASE = 1; // points a crop earns just for growing
13 const TARGET = 28; // the score at or above which the season is a win
14 const CROPS = { // one stated rule each: +/- points per touching `with` bed
15 beans: { with: 'sweetcorn', per: 3, text: 'Beans: +3 for each touching sweetcorn (they climb it)' },
16 sweetcorn: { with: 'sweetcorn', per: -1, text: 'Sweetcorn: -1 for each touching sweetcorn (they crowd)' },
17 carrots: { with: 'onion', per: -2, text: 'Carrots: -2 for each touching onion (they compete for the same soil)' },
18 onion: { with: 'lettuce', per: 2, text: 'Onion: +2 for each touching lettuce (it keeps the pests off)' },
19 lettuce: { with: 'carrots', per: 2, text: 'Lettuce: +2 for each touching carrots (they share the shade)' },
20 };
21 const NAMES = Object.keys(CROPS);
22
23 const finite = v => (Number.isFinite(v) ? v : 0);
24 // a repeatable number in [0, 1) for this seed and slot
25 function noise(seed, n) {
26 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
27 h = Math.imul(h ^ (h >>> 13), 1274126177);
28 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
29 }
30 const hand = seed => Array.from({ length: TURNS }, (_, i) => NAMES[Math.floor(noise(seed, i) * NAMES.length)]);
31 const idx = (x, y) => y * W + x;
32 const onGrid = (x, y) => Number.isInteger(x) && Number.isInteger(y) && x >= 0 && x < W && y >= 0 && y < H;
33 const copy = s => Object.assign({}, s, { grid: s.grid.slice(), hand: s.hand.slice() });
34
35 // Total of a grid (an array of W*H crop names or null, row by row) from the CROPS rules alone.
36 function total(grid) {
37 let sum = 0;
38 for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
39 const c = grid[idx(x, y)];
40 if (!c) continue;
41 const rule = CROPS[c];
42 sum += BASE;
43 for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]])
44 if (onGrid(x + dx, y + dy) && grid[idx(x + dx, y + dy)] === rule.with) sum += rule.per;
45 }
46 return sum;
47 }
48 const score = s => total(s.grid);
49
50 // The best total the season's hand can reach: a deterministic hill-climb (move one packet to a free bed, or swap two
51 // beds) from seeded starts. It is the best found, a floor on the true best, and the same for the same seed.
52 function bestOf(seed) {
53 const h = hand(seed), cells = W * H;
54 let best = -Infinity;
55 for (let r = 0; r < 8; r++) {
56 const order = Array.from({ length: cells }, (_, i) => i);
57 for (let i = cells - 1; i > 0; i--) {
58 const j = Math.floor(noise(seed, 100 + r * 40 + i) * (i + 1));
59 [order[i], order[j]] = [order[j], order[i]];
60 }
61 const grid = Array(cells).fill(null);
62 h.forEach((c, i) => { grid[order[i]] = c; });
63 let cur = total(grid), improved = true;
64 while (improved) {
65 improved = false;
66 for (let a = 0; a < cells; a++) for (let b = a + 1; b < cells; b++) {
67 if (grid[a] === grid[b]) continue; // swapping a bed with a free bed moves a packet
68 [grid[a], grid[b]] = [grid[b], grid[a]];
69 const t = total(grid);
70 if (t > cur) { cur = t; improved = true; } else [grid[a], grid[b]] = [grid[b], grid[a]];
71 }
72 }
73 best = Math.max(best, cur);
74 }
75 return best;
76 }
77
78 function refresh(s) {
79 const left = s.hand.length - s.planted;
80 if (s.planted >= s.hand.length || s.grid.every(Boolean)) {
81 const sc = score(s), win = sc >= TARGET;
82 s.status = win ? 'won' : 'lost';
83 s.line = win ? `Harvest in: ${sc} points, the target of ${TARGET} reached (best ${s.best})`
84 : `A thin season: ${sc} points, short of the target of ${TARGET} (best ${s.best})`;
85 } else {
86 s.status = 'playing';
87 s.line = `${left} packet${left === 1 ? '' : 's'} left, ${score(s)} points, next ${s.hand[s.planted]}`;
88 }
89 return s;
90 }
91
92 function start(seed = 1) {
93 seed = finite(seed) >>> 0;
94 return refresh({ seed, w: W, h: H, turns: TURNS, target: TARGET, planted: 0, status: 'playing', line: '',
95 best: bestOf(seed), grid: Array(W * H).fill(null), hand: hand(seed) });
96 }
97
98 // Plant the next packet at (x, y). Returns { ok, why, state }; on refusal state is the very same object.
99 function plant(s, x, y) {
100 if (s.status !== 'playing') return { ok: false, why: 'season-over', state: s };
101 if (!onGrid(x, y)) return { ok: false, why: 'off-grid', state: s };
102 if (s.grid[idx(x, y)]) return { ok: false, why: 'filled', state: s };
103 const n = copy(s);
104 n.grid[idx(x, y)] = s.hand[s.planted];
105 n.planted++;
106 return { ok: true, why: '', state: refresh(n) };
107 }
108
109 // The end of the season, or null while it is still on: { score, best, won, line }.
110 const result = s => (s.status === 'playing' ? null : { score: score(s), best: s.best, won: s.status === 'won', line: s.line });
111
112 const api = { W, H, TURNS, BASE, TARGET, CROPS, NAMES, hand, start, plant, score, total, result, bestOf };
113 if (typeof module !== 'undefined') module.exports = api; else root.Allotment = api;
114 })(typeof window !== 'undefined' ? window : globalThis);
allotment/plot.test.mjs added +140
@@ -0,0 +1,140 @@
1 import { test, expect } from 'bun:test';
2 import { W, H, TURNS, BASE, TARGET, CROPS, NAMES, hand, start, plant, score, total, result, bestOf } from './plot.js';
3
4 // a grid built by hand from [x, y, crop] triples
5 const grid = cells => { const g = Array(W * H).fill(null); for (const [x, y, c] of cells) g[y * W + x] = c; return g; };
6 const withGrid = cells => Object.assign(start(1), { grid: grid(cells) });
7
8 test('a season starts with an empty grid of a stated size, stated turns and a hand to match', () => {
9 const s = start(1);
10 expect([s.w, s.h, s.turns]).toEqual([W, H, TURNS]);
11 expect(s.grid).toHaveLength(W * H);
12 expect(s.grid.every(c => c === null)).toBe(true);
13 expect(s.hand).toHaveLength(TURNS);
14 expect(s.hand.every(c => NAMES.includes(c))).toBe(true);
15 expect(s.status).toBe('playing');
16 expect(score(s)).toBe(0);
17 });
18
19 test('the same seed always gives the same hand, and other seeds give other hands', () => {
20 expect(start(7).hand).toEqual(start(7).hand);
21 expect(start(7).hand).toEqual(hand(7));
22 expect(start(7).best).toBe(start(7).best);
23 expect(new Set([1, 2, 3, 4, 5, 6].map(n => start(n).hand.join()))).toHaveLength(6);
24 expect(start(NaN).hand).toEqual(start(0).hand);
25 });
26
27 test('there are at least four crops, each with one stated neighbour rule', () => {
28 expect(NAMES.length).toBeGreaterThanOrEqual(4);
29 for (const c of NAMES) {
30 expect(NAMES).toContain(CROPS[c].with);
31 expect(Number.isInteger(CROPS[c].per) && CROPS[c].per !== 0).toBe(true);
32 expect(CROPS[c].text.length).toBeGreaterThan(10);
33 }
34 });
35
36 test('planting puts the next packet in an empty bed and moves on to the one after', () => {
37 const s = start(1), r = plant(s, 2, 3);
38 expect(r.ok).toBe(true);
39 expect(r.state.grid[3 * W + 2]).toBe(s.hand[0]);
40 expect(r.state.planted).toBe(1);
41 expect(s.grid[3 * W + 2]).toBe(null); // the old state is untouched
42 const r2 = plant(r.state, 0, 0);
43 expect(r2.state.grid[0]).toBe(s.hand[1]);
44 });
45
46 test('a filled bed and a cell off the grid are refused and the state is left unchanged', () => {
47 const s = plant(start(1), 1, 1).state;
48 const filled = plant(s, 1, 1);
49 expect([filled.ok, filled.why, filled.state]).toEqual([false, 'filled', s]);
50 for (const [x, y] of [[-1, 0], [0, -1], [W, 0], [0, H], [1.5, 1], [NaN, 0], ['1', 1], [undefined, 1]]) {
51 const r = plant(s, x, y);
52 expect([r.ok, r.why, r.state]).toEqual([false, 'off-grid', s]);
53 }
54 });
55
56 test('each crop scores its base, plus its own rule for each touching bed', () => {
57 expect(BASE).toBe(1);
58 // beans +3 per touching sweetcorn (the sweetcorn pair also crowd: -1 each)
59 expect(total(grid([[1, 1, 'beans']]))).toBe(1);
60 expect(total(grid([[1, 1, 'beans'], [2, 1, 'sweetcorn']]))).toBe(1 + 3 + 1);
61 expect(total(grid([[1, 1, 'beans'], [2, 1, 'sweetcorn'], [1, 2, 'sweetcorn']]))).toBe(1 + 6 + 1 + 1);
62 // sweetcorn -1 per touching sweetcorn
63 expect(total(grid([[0, 0, 'sweetcorn'], [1, 0, 'sweetcorn']]))).toBe(2 * (1 - 1));
64 expect(total(grid([[1, 1, 'sweetcorn'], [0, 1, 'sweetcorn'], [2, 1, 'sweetcorn']]))).toBe((1 - 2) + 2 * (1 - 1));
65 // carrots -2 per touching onion (the onion has no rule about carrots)
66 expect(total(grid([[2, 2, 'carrots'], [2, 3, 'onion']]))).toBe(1 - 2 + 1);
67 expect(total(grid([[2, 2, 'carrots'], [2, 3, 'onion'], [3, 2, 'onion']]))).toBe(1 - 4 + 2);
68 // onion +2 per touching lettuce
69 expect(total(grid([[4, 4, 'onion'], [3, 4, 'lettuce']]))).toBe(1 + 2 + 1);
70 // lettuce +2 per touching carrots
71 expect(total(grid([[0, 4, 'lettuce'], [0, 3, 'carrots'], [1, 4, 'carrots']]))).toBe(1 + 4 + 2);
72 });
73
74 test('only beds that share an edge touch: diagonals and distant beds do not', () => {
75 expect(total(grid([[1, 1, 'beans'], [2, 2, 'sweetcorn']]))).toBe(2);
76 expect(total(grid([[0, 0, 'beans'], [2, 0, 'sweetcorn']]))).toBe(2);
77 expect(total(grid([[0, 0, 'beans'], [W - 1, 0, 'sweetcorn']]))).toBe(2); // no wrap-around
78 });
79
80 test('score(state) totals the planted grid from the rules alone', () => {
81 const s = withGrid([[0, 0, 'beans'], [1, 0, 'sweetcorn'], [3, 3, 'carrots']]);
82 expect(score(s)).toBe(1 + 3 + 1 + 1);
83 });
84
85 test('the season ends when the turns run out, reporting score and best', () => {
86 let s = start(1);
87 for (let i = 0; i < TURNS; i++) {
88 expect(s.status).toBe('playing');
89 expect(result(s)).toBe(null);
90 s = plant(s, i % W, Math.floor(i / W)).state;
91 }
92 expect(s.status).not.toBe('playing');
93 const end = result(s);
94 expect(end.score).toBe(score(s));
95 expect(end.best).toBe(bestOf(1));
96 expect(end.best).toBeGreaterThanOrEqual(end.score);
97 const r = plant(s, 4, 4);
98 expect([r.ok, r.why, r.state]).toEqual([false, 'season-over', s]);
99 });
100
101 test('the season ends early when the grid is full', () => {
102 const s = withGrid(Array.from({ length: W * H - 1 }, (_, i) => [i % W, Math.floor(i / W), 'lettuce']));
103 const r = plant(s, W - 1, H - 1);
104 expect(r.ok).toBe(true);
105 expect(r.state.planted).toBeLessThan(TURNS);
106 expect(result(r.state)).not.toBe(null);
107 });
108
109 test('the win line is at or above the target and the loss line below it', () => {
110 // plant a last packet of `crop` at (2, 1) on a hand-built grid, one turn from the end
111 const finish = (cells, crop) => {
112 const s = Object.assign(start(1), { grid: grid(cells), planted: TURNS - 1 });
113 s.hand[TURNS - 1] = crop;
114 return plant(s, 2, 1).state;
115 };
116 // a pair of beans and sweetcorn side by side scores 1 + 3 + 1 = 5; pairs in rows 0, 2 and 4 never touch
117 const pairs = [0, 2, 4].flatMap(y => [[0, y], [3, y]].flatMap(([x]) => [[x, y, 'beans'], [x + 1, y, 'sweetcorn']]));
118 expect(total(grid(pairs))).toBe(30);
119 expect(TARGET).toBe(28);
120
121 const win = finish(pairs, 'lettuce'); // a lettuce touching nothing adds 1: 31
122 expect(score(win)).toBe(31);
123 expect(win.status).toBe('won');
124 expect(result(win)).toEqual({ score: 31, best: bestOf(1), won: true, line: win.line });
125 expect(win.line).toContain('target of 28 reached');
126
127 const exact = finish(pairs.slice(0, 10).concat([[4, 1, 'lettuce'], [4, 3, 'lettuce']]), 'lettuce'); // 25 + 2 + 1
128 expect(score(exact)).toBe(TARGET);
129 expect(exact.status).toBe('won');
130
131 const under = finish(pairs.slice(0, 10).concat([[4, 1, 'lettuce']]), 'lettuce'); // 25 + 1 + 1
132 expect(score(under)).toBe(TARGET - 1);
133 expect(under.status).toBe('lost');
134 expect(result(under).won).toBe(false);
135 expect(under.line).toContain('short of the target of 28');
136 });
137
138 test('the target is reachable: the best of every shipped seed meets it', () => {
139 for (const n of [1, 2, 3, 4, 5, 6, 7, 8]) expect(bestOf(n)).toBeGreaterThanOrEqual(TARGET);
140 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs