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

Migrated from github.com/amirmushichge/pixel-plays

Fence Posts rules: a tested `fence-posts/field.js` where you and a farmer take turns fencing between posts and claim each pen you close, from plain data, in a two-file pull with a test file that runs in under a second #317

Merged opened this

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

Merged

torque/pixel-plays:torque/303-fence-posts-rules-a-tested-fence-posts-f → main 1 commit fork

  • Merged. torque/303-fence-posts-rules-a-tested-fence-posts-f was merged into main as 999a1f4.

Review

Sign in to review this change.
2 files changed +392 −0
fence-posts/field.js added +155
@@ -0,0 +1,155 @@
1 'use strict';
2 // The Fence Posts rules: a meadow staked with a grid of posts. You and a rival farmer take turns running one length of
3 // fence between two neighbouring posts; whoever closes the fourth side of a pen claims it and its sheep, and fences
4 // again. Plain data in, plain data out, no DOM, no timers, no Math.random: every sheep count and every tie-break comes
5 // from the seed. A rejected call returns the very same state and says why.
6 //
7 // Units: posts and pens are counted; lengths of fence are one grid step. ROWS × COLS pens sit between
8 // (ROWS+1) × (COLS+1) posts. Pen (r, c) has four sides: h:r:c (top), h:r+1:c (bottom), v:r:c (left), v:r:c+1 (right).
9 // horizontal lengths h:r:c join post (r,c)–(r,c+1), 0 ≤ r ≤ ROWS, 0 ≤ c < COLS
10 // vertical lengths v:r:c join post (r,c)–(r+1,c), 0 ≤ r < ROWS, 0 ≤ c ≤ COLS
11 // total lengths = ROWS·(COLS+1) + COLS·(ROWS+1) (counting argument; 40 for 4 × 4)
12 // Winner: more sheep; a tie in sheep goes to more pens; a tie in both is a draw.
13 (function (root) {
14 const ROWS = 4, COLS = 4; // pens; posts are 5 × 5
15 const SHEEP_MIN = 1, SHEEP_MAX = 5; // sheep in each pen, inclusive
16 const YOU = 'you', FARMER = 'farmer';
17 const LENGTHS = ROWS * (COLS + 1) + COLS * (ROWS + 1);
18
19 // mulberry32 as a pure step: next(seed) -> [value in [0,1), nextSeed]
20 function next(r) {
21 r = (r + 0x6D2B79F5) >>> 0;
22 let t = r;
23 t = Math.imul(t ^ (t >>> 15), t | 1);
24 t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
25 return [((t ^ (t >>> 14)) >>> 0) / 4294967296, r];
26 }
27
28 // parse(edge) -> {k, r, c} for a well-formed edge on the grid, else null
29 function parse(edge) {
30 if (typeof edge !== 'string') return null;
31 const m = /^([hv]):(0|[1-9]\d?):(0|[1-9]\d?)$/.exec(edge);
32 if (!m) return null;
33 const k = m[1], r = +m[2], c = +m[3];
34 if (k === 'h' ? !(r <= ROWS && c < COLS) : !(r < ROWS && c <= COLS)) return null;
35 return { k, r, c };
36 }
37
38 const sidesOf = (r, c) => [`h:${r}:${c}`, `h:${r + 1}:${c}`, `v:${r}:${c}`, `v:${r}:${c + 1}`];
39
40 // pensOf(edge) -> indexes (r*COLS+c) of the one or two pens the length borders
41 function pensOf(edge) {
42 const { k, r, c } = parse(edge), out = [];
43 if (k === 'h') { if (r > 0) out.push((r - 1) * COLS + c); if (r < ROWS) out.push(r * COLS + c); }
44 else { if (c > 0) out.push(r * COLS + c - 1); if (c < COLS) out.push(r * COLS + c); }
45 return out;
46 }
47
48 const builtSides = (built, i) => sidesOf(Math.floor(i / COLS), i % COLS).filter(e => built[e]).length;
49
50 function tally(s) {
51 const t = { [YOU]: { sheep: 0, pens: 0 }, [FARMER]: { sheep: 0, pens: 0 } };
52 for (const p of s.pens) if (p.owner) { t[p.owner].sheep += p.sheep; t[p.owner].pens++; }
53 return t;
54 }
55
56 // describe(state) -> the one-line account of the game
57 function describe(s) {
58 const t = tally(s), y = t[YOU], f = t[FARMER];
59 const score = `${y.sheep} sheep to ${f.sheep}, ${y.pens} pens to ${f.pens}`;
60 if (s.status === 'won') return `You win: ${score}`;
61 if (s.status === 'lost') return `You lose: ${score}`;
62 if (s.status === 'tied') return `A draw: ${score}`;
63 return `${s.turn === YOU ? 'Your' : "The farmer's"} turn, ${LENGTHS - Object.keys(s.built).length} lengths to build: ${score}`;
64 }
65
66 // start(seed) -> an empty field, you to move first, SHEEP_MIN..SHEEP_MAX sheep in every pen drawn from the seed
67 function start(seed) {
68 const sd = Number.isFinite(seed) ? Math.trunc(seed) >>> 0 : 0;
69 let rng = sd;
70 const pens = [];
71 for (let i = 0; i < ROWS * COLS; i++) {
72 let v; [v, rng] = next(rng);
73 pens.push({ r: Math.floor(i / COLS), c: i % COLS, sheep: SHEEP_MIN + Math.min(SHEEP_MAX - SHEEP_MIN, Math.floor(v * (SHEEP_MAX - SHEEP_MIN + 1))), owner: null });
74 }
75 const s = { seed: sd, rng, rows: ROWS, cols: COLS, posts: (ROWS + 1) * (COLS + 1), turn: YOU, built: {}, pens, status: 'playing', line: '' };
76 s.line = describe(s);
77 return s;
78 }
79
80 // fences(state) -> every unbuilt length, horizontals then verticals, in row order
81 function fences(state) {
82 const out = [];
83 for (let r = 0; r <= ROWS; r++) for (let c = 0; c < COLS; c++) if (!state.built[`h:${r}:${c}`]) out.push(`h:${r}:${c}`);
84 for (let r = 0; r < ROWS; r++) for (let c = 0; c <= COLS; c++) if (!state.built[`v:${r}:${c}`]) out.push(`v:${r}:${c}`);
85 return out;
86 }
87
88 const refuse = (state, why) => ({ ok: false, state, why, closed: 0 });
89
90 // build(state, edge, player = 'you') -> {ok, state, why, closed}
91 // Closing one or two pens claims each for the builder, who moves again; otherwise the turn passes.
92 function build(state, edge, player = YOU) {
93 if (state.status !== 'playing') return refuse(state, 'the game is over');
94 if (player !== YOU && player !== FARMER) return refuse(state, 'unknown player');
95 if (player !== state.turn) return refuse(state, 'not your turn');
96 if (!parse(edge)) return refuse(state, 'not a length of fence on the grid');
97 if (state.built[edge]) return refuse(state, 'that length is already built');
98 const built = { ...state.built, [edge]: player };
99 const pens = state.pens.slice();
100 let closed = 0;
101 for (const i of pensOf(edge)) if (!pens[i].owner && builtSides(built, i) === 4) { pens[i] = { ...pens[i], owner: player }; closed++; }
102 const s = { ...state, built, pens, turn: closed ? player : (player === YOU ? FARMER : YOU) };
103 if (Object.keys(built).length === LENGTHS) {
104 const t = tally(s);
105 const d = t[YOU].sheep - t[FARMER].sheep || t[YOU].pens - t[FARMER].pens;
106 s.status = d > 0 ? 'won' : d < 0 ? 'lost' : 'tied';
107 }
108 s.line = describe(s);
109 return { ok: true, state: s, why: '', closed };
110 }
111
112 // choose(state, rule) -> the length the farmer builds, with the rule that picked it
113 // Rule 1: close any pen it can. Rule 2: otherwise a length that gives no pen a third side, if one exists.
114 // Rule 3: otherwise the length giving away the fewest pens (pens that already have two sides and would get a third).
115 // Ties among equal candidates are broken by the seeded stream: candidates[floor(u·n)], one draw per tie.
116 function choose(state) {
117 const open = fences(state);
118 const sides = e => pensOf(e).map(i => builtSides(state.built, i));
119 let pool = open.filter(e => sides(e).some(n => n === 3));
120 let rule = 'close';
121 if (!pool.length) {
122 pool = open.filter(e => sides(e).every(n => n < 2));
123 rule = 'safe';
124 if (!pool.length) {
125 const cost = e => sides(e).filter(n => n === 2).length;
126 const best = Math.min(...open.map(cost));
127 pool = open.filter(e => cost(e) === best);
128 rule = 'fewest';
129 }
130 }
131 let edge = pool[0], rng = state.rng;
132 if (pool.length > 1) { let u; [u, rng] = next(rng); edge = pool[Math.min(pool.length - 1, Math.floor(u * pool.length))]; }
133 return { edge, rule, rng };
134 }
135
136 // reply(state) -> {ok, state, why, moves: [{edge, rule}]}: the farmer plays until the turn passes back or the game ends
137 function reply(state) {
138 if (state.status !== 'playing') return { ...refuse(state, 'the game is over'), moves: [] };
139 if (state.turn !== FARMER) return { ...refuse(state, "not the farmer's turn"), moves: [] };
140 let s = state;
141 const moves = [];
142 while (s.status === 'playing' && s.turn === FARMER) {
143 const { edge, rule, rng } = choose(s);
144 s = build({ ...s, rng }, edge, FARMER).state;
145 moves.push({ edge, rule });
146 }
147 return { ok: true, state: s, why: '', moves };
148 }
149
150 const api = {
151 ROWS, COLS, SHEEP_MIN, SHEEP_MAX, YOU, FARMER, LENGTHS,
152 start, fences, build, reply, choose, parse, pensOf, tally, describe,
153 };
154 if (typeof module !== 'undefined') module.exports = api; else root.FencePosts = api;
155 })(typeof window !== 'undefined' ? window : globalThis);
fence-posts/field.test.mjs added +237
@@ -0,0 +1,237 @@
1 import { test, expect } from 'bun:test';
2 import {
3 ROWS, COLS, SHEEP_MIN, SHEEP_MAX, LENGTHS, start, fences, build, reply, choose, pensOf, tally,
4 } from './field.js';
5
6 // a field with the given lengths already standing (owned by nobody's claim), with `turn` to move
7 const field = (edges, turn = 'farmer', seed = 1) => {
8 const s = start(seed);
9 const built = {};
10 for (const e of edges) built[e] = 'you';
11 return { ...s, built, turn };
12 };
13 // the four sides of pen (r, c)
14 const sides = (r, c) => [`h:${r}:${c}`, `h:${r + 1}:${c}`, `v:${r}:${c}`, `v:${r}:${c + 1}`];
15 const same = (state, edge, player) => {
16 const r = build(state, edge, player);
17 expect(r.ok).toBe(false);
18 expect(r.state).toBe(state);
19 return r.why;
20 };
21
22 test('start: stated grid, you first, seeded sheep in a stated range; same seed, same field and replies', () => {
23 const a = start(7), b = start(7), c = start(8);
24 expect([ROWS, COLS, a.posts, a.turn, a.status, LENGTHS]).toEqual([4, 4, 25, 'you', 'playing', 40]);
25 expect(a.pens.length).toBe(16);
26 expect(a.pens).toEqual(b.pens);
27 expect(a.pens).not.toEqual(c.pens);
28 for (const p of a.pens) { expect(p.sheep).toBeGreaterThanOrEqual(SHEEP_MIN); expect(p.sheep).toBeLessThanOrEqual(SHEEP_MAX); expect(p.owner).toBe(null); }
29 expect(new Set(a.pens.map(p => p.sheep)).size).toBe(SHEEP_MAX - SHEEP_MIN + 1);
30 expect(start(NaN).seed).toBe(0);
31 const x = reply(build(a, 'h:0:0').state), y = reply(build(b, 'h:0:0').state);
32 expect(x.moves).toEqual(y.moves);
33 expect(x.state).toEqual(y.state);
34 });
35
36 test('fences lists every unbuilt length and shrinks as they are built', () => {
37 const s = start(1);
38 expect(fences(s).length).toBe(40);
39 expect(new Set(fences(s)).size).toBe(40);
40 const t = build(s, 'v:2:3').state;
41 expect(fences(t).length).toBe(39);
42 expect(fences(t)).not.toContain('v:2:3');
43 });
44
45 test('build refuses: built, off the grid, malformed, out of turn, game over — with a reason and the same state', () => {
46 const s = start(1);
47 const t = build(s, 'h:0:0').state;
48 expect(same(field(['h:0:0'], 'you'), 'h:0:0')).toBe('that length is already built');
49 for (const bad of ['h:5:0', 'h:0:4', 'v:4:0', 'v:0:5', 'h:-1:0', 'h:00:0', 'x:0:0', 'h:0', '', null, 7, {}, 'h:0:0 ']) {
50 expect(same(s, bad)).toBe('not a length of fence on the grid');
51 }
52 expect(same(s, 'h:1:1', 'farmer')).toBe('not your turn');
53 expect(same(t, 'h:1:1')).toBe('not your turn');
54 expect(same(s, 'h:1:1', 'nobody')).toBe('unknown player');
55 const over = { ...s, status: 'won' };
56 expect(same(over, 'h:1:1')).toBe('the game is over');
57 expect(build(s, 'h:0:0').ok).toBe(true);
58 });
59
60 test('a length that closes nothing passes the turn; the input state is not changed', () => {
61 const s = start(1);
62 const r = build(s, 'h:0:0');
63 expect([r.ok, r.closed, r.state.turn, r.state.built['h:0:0']]).toEqual([true, 0, 'farmer', 'you']);
64 expect(s.built).toEqual({});
65 expect(build(r.state, 'h:2:2', 'farmer').state.turn).toBe('you');
66 });
67
68 test('a single close claims the pen and its sheep, and the builder moves again', () => {
69 const s = field(sides(1, 1).slice(1), 'you');
70 const r = build(s, 'h:1:1');
71 expect([r.ok, r.closed, r.state.turn]).toEqual([true, 1, 'you']);
72 expect(r.state.pens[1 * COLS + 1].owner).toBe('you');
73 expect(tally(r.state).you).toEqual({ sheep: s.pens[5].sheep, pens: 1 });
74 expect(r.state.line).toContain('Your turn');
75 });
76
77 test('a double close claims both pens with one length', () => {
78 // pens (1,1) and (1,2) share v:1:2
79 const rest = [...sides(1, 1), ...sides(1, 2)].filter((e, i, a) => e !== 'v:1:2' && a.indexOf(e) === i);
80 const s = field(rest, 'you');
81 expect(pensOf('v:1:2')).toEqual([5, 6]);
82 const r = build(s, 'v:1:2');
83 expect([r.closed, r.state.turn, r.state.pens[5].owner, r.state.pens[6].owner]).toEqual([2, 'you', 'you', 'you']);
84 expect(tally(r.state).you).toEqual({ sheep: s.pens[5].sheep + s.pens[6].sheep, pens: 2 });
85 });
86
87 test('reply refuses on your turn and when the game is over', () => {
88 const s = start(1);
89 const r = reply(s);
90 expect([r.ok, r.state, r.moves]).toEqual([false, s, []]);
91 expect(r.why).toBe("not the farmer's turn");
92 expect(reply({ ...s, status: 'lost', turn: 'farmer' }).why).toBe('the game is over');
93 });
94
95 test('farmer rule 1: closes a pen when it can, in preference to a safe length', () => {
96 const s = field(sides(2, 2).slice(1)); // pen (2,2) has three sides
97 const c = choose(s);
98 expect([c.edge, c.rule]).toEqual(['h:2:2', 'close']);
99 const r = reply(s);
100 expect(r.moves[0]).toEqual({ edge: 'h:2:2', rule: 'close' });
101 expect(r.state.pens[2 * COLS + 2].owner).toBe('farmer');
102 // it moved again after the close, then passed the turn back
103 expect(r.moves.length).toBeGreaterThan(1);
104 expect(r.state.turn).toBe('you');
105 expect(r.moves.at(-1).rule).not.toBe('close');
106 });
107
108 test('farmer rule 2: with nothing to close it never gives a third side while a safe length exists', () => {
109 // every pen has at most one side; make a field with one pen at two sides
110 const s = field(['h:0:0', 'v:0:0']);
111 expect(choose(s).rule).toBe('safe');
112 for (let seed = 1; seed < 30; seed++) {
113 const c = choose({ ...s, rng: seed });
114 for (const i of pensOf(c.edge)) {
115 const have = sides(Math.floor(i / COLS), i % COLS).filter(e => s.built[e]).length;
116 expect(have).toBeLessThan(2);
117 }
118 }
119 });
120
121 test('farmer rule 3: with no safe length it gives away the fewest pens', () => {
122 // everything built except v:0:1 (borders pens (0,0) and (0,1)), h:0:0 (pen (0,0)) and h:0:1 (pen (0,1)):
123 // both pens stand at two sides, so v:0:1 would give away two pens and the other two give away one each
124 const open = new Set(['v:0:1', 'h:0:0', 'h:0:1']);
125 const s = field(fences(start(1)).filter(e => !open.has(e)));
126 expect(fences(s).sort()).toEqual([...open].sort());
127 const picks = new Set();
128 for (let seed = 0; seed < 40; seed++) {
129 const c = choose({ ...s, rng: seed });
130 expect(c.rule).toBe('fewest');
131 picks.add(c.edge);
132 }
133 expect([...picks].sort()).toEqual(['h:0:0', 'h:0:1']);
134 });
135
136 test('farmer ties are broken by the seed: same seed same pick, different seeds reach different picks', () => {
137 const s = field(['h:0:0', 'v:0:0']);
138 const a = choose({ ...s, rng: 5 }), b = choose({ ...s, rng: 5 });
139 expect(a).toEqual(b);
140 const picks = new Set();
141 for (let seed = 0; seed < 40; seed++) picks.add(choose({ ...s, rng: seed }).edge);
142 expect(picks.size).toBeGreaterThan(3);
143 // a single candidate draws nothing from the seed
144 const one = field(fences(start(1)).filter(e => e !== 'h:4:3'));
145 expect(choose(one).rng).toBe(one.rng);
146 expect(choose(s).rng).not.toBe(s.rng);
147 });
148
149 function play(seed) {
150 let s = start(seed), turns = 0;
151 while (s.status === 'playing') {
152 if (s.turn === 'you') s = build(s, fences(s)[(turns * 7) % fences(s).length]).state;
153 else s = reply(s).state;
154 turns++;
155 if (turns > 200) throw new Error('did not end');
156 }
157 return s;
158 }
159
160 test('a whole game ends with every length built and every pen claimed by someone', () => {
161 for (const seed of [1, 2, 3, 4, 5]) {
162 const s = play(seed);
163 expect(Object.keys(s.built).length).toBe(LENGTHS);
164 expect(fences(s)).toEqual([]);
165 expect(s.pens.every(p => p.owner)).toBe(true);
166 const t = tally(s);
167 expect(t.you.pens + t.farmer.pens).toBe(16);
168 expect(t.you.sheep + t.farmer.sheep).toBe(s.pens.reduce((n, p) => n + p.sheep, 0));
169 expect(s.line).toContain(`${t.you.sheep} sheep to ${t.farmer.sheep}, ${t.you.pens} pens to ${t.farmer.pens}`);
170 expect(build(s, 'h:0:0').why).toBe('the game is over');
171 }
172 });
173
174 // the last length of a nearly done field, with chosen owners/sheep so the result is known by hand
175 function finish(owners, sheep) {
176 const s = start(1);
177 const pens = s.pens.map((p, i) => ({ ...p, sheep: sheep[i], owner: owners[i] }));
178 const last = 'h:4:3';
179 const built = {};
180 for (const e of fences(s)) if (e !== last) built[e] = 'you';
181 // pen 15 is closed by the last length: leave it unowned for now
182 pens[15] = { ...pens[15], owner: null };
183 return build({ ...s, built, pens, turn: 'you' }, last);
184 }
185 const owners = (n) => Array.from({ length: 16 }, (_, i) => (i < n ? 'you' : 'farmer'));
186
187 test('win line: more sheep wins and reports both sides', () => {
188 const sheep = Array(16).fill(2); sheep[0] = 5;
189 const r = finish(owners(8), sheep); // you hold 0..7 plus pen 15 (closed by you) = 9 pens
190 expect(r.state.status).toBe('won');
191 expect(r.state.line).toBe('You win: 21 sheep to 14, 9 pens to 7');
192 });
193
194 test('loss line: fewer sheep loses', () => {
195 const sheep = Array(16).fill(2); sheep[10] = 5;
196 const r = finish(owners(4), sheep);
197 expect(r.state.status).toBe('lost');
198 expect(r.state.line).toBe('You lose: 10 sheep to 25, 5 pens to 11');
199 });
200
201 test('a tie in sheep goes to more pens', () => {
202 // you: pens 0..7 + pen 15 = 9 pens; farmer 7 pens; make sheep equal 18 each? you 9 pens·2 = 18, farmer 7 pens: 6×2 + 6 = 18
203 const sheep = Array(16).fill(2); sheep[8] = 6;
204 const r = finish(owners(8), sheep);
205 expect(tally(r.state).you.sheep).toBe(tally(r.state).farmer.sheep);
206 expect(r.state.status).toBe('won');
207 expect(r.state.line).toBe('You win: 18 sheep to 18, 9 pens to 7');
208 // and the other way: farmer has more pens
209 const o = owners(5), sh = Array(16).fill(1); sh[0] = 6; // you: pens 0..4 (6+4=10) + pen 15 → 11; farmer 10 pens, 10 sheep
210 const l = finish(o, sh);
211 const t = tally(l.state);
212 expect(t.you.sheep).toBe(11); expect(t.farmer.sheep).toBe(10);
213 const sh2 = Array(16).fill(1); sh2[0] = 5; // you 5+4+1 = 10, farmer 10: tie in sheep, farmer 10 pens vs 6
214 const l2 = finish(o, sh2);
215 expect(tally(l2.state).you.sheep).toBe(tally(l2.state).farmer.sheep);
216 expect(l2.state.status).toBe('lost');
217 expect(l2.state.line).toBe('You lose: 10 sheep to 10, 6 pens to 10');
218 });
219
220 test('a tie in sheep and pens is a draw', () => {
221 const s = start(1);
222 const pens = s.pens.map((p, i) => ({ ...p, sheep: 2, owner: i < 8 ? 'you' : 'farmer' }));
223 pens[15] = { ...pens[15], owner: null };
224 const built = {};
225 for (const e of fences(s)) if (e !== 'h:4:3') built[e] = 'you';
226 // the farmer closes the last pen instead
227 const r = build({ ...s, built, pens, turn: 'farmer' }, 'h:4:3', 'farmer');
228 // you 8 pens/16 sheep, farmer 8 pens/16 sheep
229 expect(r.state.status).toBe('tied');
230 expect(r.state.line).toBe('A draw: 16 sheep to 16, 8 pens to 8');
231 });
232
233 test('the rules module runs fast: a full game in well under a second', () => {
234 const t = performance.now();
235 play(9);
236 expect(performance.now() - t).toBeLessThan(500);
237 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs