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

Migrated from github.com/amirmushichge/pixel-plays

Village Draughts moves: `moves(state)` checked against an independent rule check across 200 seeded games in `village-draughts/board.test.mjs` #296

Merged opened this

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

Merged

torque/pixel-plays:torque/292-village-draughts-moves-moves-state-check → main 2 commits fork 4 threads · 4 unresolved

  • Merged. torque/292-village-draughts-moves-moves-state-check was merged into main as c447f73.

Review

Sign in to review this change.
2 files changed +192 −0
village-draughts/board.js +7
@@ -68,8 +68,15 @@
6868 }
6969
7070 // moves(state) -> every legal move for the side to move (none once the game is over)
71 // A state is never changed once made, so its list is worked out once and kept with it (the caller must not edit it).
72 const listed = new WeakMap();
7173 function moves(state) {

Non-blocking: freeze the cached list (Object.freeze on the result of movesOf) so a caller's mutation throws instead of corrupting later calls.

7274 if (state.status !== 'playing') return [];
75 if (!listed.has(state)) listed.set(state, movesOf(state));
76 return listed.get(state);
77 }
78
79 function movesOf(state) {
7380 const side = state.turn, S = SIDES[side];
7481 const g = grid(state.board);
7582 const caps = [], steps = [];
village-draughts/board.test.mjs +185
@@ -177,3 +177,188 @@ test('fromBoard refuses bad rows and bad turns', () => {
177177 }
178178 expect(setOut(ok).ok).toBe(true); // the turn defaults to the player
179179 });
180
181 // ---- 200 seeded games against an independent rule check (written here; nothing below is taken from board.js) ----
182 const owner = ch => (ch === 'p' || ch === 'P' ? 'player' : ch === 'o' || ch === 'O' ? 'opponent' : null);
183 const FWD = { player: -1, opponent: 1 };
184 const FAR = { player: 0, opponent: SIZE - 1 };
185 const onBoard = (r, c) => r >= 0 && r < SIZE && c >= 0 && c < SIZE;
186 const dirsFor = (ch, side) => (ch === ch.toUpperCase() ? [-1, 1] : [FWD[side]]);
187
188 // can the piece ch on (r, c) jump anything? at(r, c) says what stands on a square once the mover has left its own
189 function canJump(at, side, ch, r, c) {
190 for (const dr of dirsFor(ch, side)) for (const dc of [-1, 1]) {
191 const [mr, mc, lr, lc] = [r + dr, c + dc, r + 2 * dr, c + 2 * dc];
192 if (onBoard(lr, lc) && owner(at(mr, mc)) && owner(at(mr, mc)) !== side && at(lr, lc) === '.') return true;
193 }
194 return false;
195 }
196
197 const gridMemo = new WeakMap();
198 const gridOf = s => { if (!gridMemo.has(s)) gridMemo.set(s, s.board.map(row => row.split(''))); return gridMemo.get(s); };
199
200 // does any piece of the side to move have a jump on this board? (worked out once per state)
201 const capMemo = new WeakMap();
202 function captureAvailable(s) {
203 if (!capMemo.has(s)) {
204 const g = gridOf(s);
205 let any = false;
206 for (let r = 0; r < SIZE && !any; r++) for (let c = 0; c < SIZE && !any; c++) {
207 const p = g[r][c];
208 if (owner(p) === s.turn) any = canJump((y, x) => (y === r && x === c ? '.' : g[y][x]), s.turn, p, r, c);
209 }
210 capMemo.set(s, any);
211 }
212 return capMemo.get(s);
213 }
214
215 // checkMove(state, m) -> '' when m is a legal move of the side to move, otherwise the first rule it breaks
216 function checkMove(s, m) {
217 const side = s.turn, g = gridOf(s);
218 const [fr, fc] = m.from;
219 const ch = g[fr][fc];
220 if (owner(ch) !== side) return 'moves a piece that is not the mover\'s';
221 if (m.path.length < 1) return 'empty path';
222 const man = ch === ch.toLowerCase();
223 if (m.captures.length === 0) {
224 if (captureAvailable(s)) return 'a step while a capture is available';
225 if (m.path.length !== 1) return 'a step of more than one square';
226 const [tr, tc] = m.path[0];
227 if (!onBoard(tr, tc) || Math.abs(tc - fc) !== 1 || !dirsFor(ch, side).includes(tr - fr)) return 'step is not one diagonal square' + (man ? ' forward' : '');
228 if ((tr === fr && tc === fc) || g[tr][tc] !== '.') return 'step onto an occupied square';
229 return '';
230 }
231 if (m.captures.length !== m.path.length) return 'captures and landings differ in number';
232 const taken = [];
233 const at = (y, x) => (y === fr && x === fc) || taken.some(k => k[0] === y && k[1] === x) ? '.' : g[y][x];
234 let [r, c] = [fr, fc], now = ch, crowned = false;
235 for (let i = 0; i < m.path.length; i++) {
236 if (crowned) return 'a man went on past the far row';
237 const [lr, lc] = m.path[i], [kr, kc] = m.captures[i];
238 const dr = lr - r, dc = lc - c;
239 if (Math.abs(dr) !== 2 || Math.abs(dc) !== 2 || !dirsFor(now, side).includes(dr / 2)) return 'jump is not two diagonal squares' + (man ? ' forward' : '');
240 if (kr !== r + dr / 2 || kc !== c + dc / 2) return 'jumped square is not between';
241 const victim = owner(at(kr, kc));
242 if (!victim || victim === side) return 'jump does not hop an opposing piece';
243 if (!onBoard(lr, lc) || at(lr, lc) !== '.') return 'jump onto an occupied square';
244 taken.push([kr, kc]);
245 [r, c] = [lr, lc];
246 if (man && r === FAR[side]) { crowned = true; now = now.toUpperCase(); }
247 }
248 if (!crowned && canJump(at, side, now, r, c)) return 'a jump path that a further jump could extend';
249 return '';
250 }
251
252 // a small seeded generator for the player's picks (the test's own, not the game's)
253 const fkey = m => m.from[0] * 8 + m.from[1] + ':' + m.path.map(p => p[0] * 8 + p[1]).join(','); // cheaper than JSON, same identity
254 const firstOf = (s, side) => { const g = gridOf(s); for (let r = 0; r < SIZE; r++) for (let c = 0; c < SIZE; c++) if (owner(g[r][c]) === side) return [r, c]; };
255 const must = (ok, why) => { if (!ok) throw new Error(why); };
256 const picker = seed => { let a = seed >>> 0; return n => { a = (Math.imul(a, 1664525) + 1013904223) >>> 0; return (a >>> 8) % n; }; };
257
258 test('checkMove itself catches broken moves', () => {
259 const s = fromBoard(put({ '6,1': 'p', '5,2': 'o', '3,2': 'o', '0,7': 'o', '7,6': 'p' }), 'player', 1);
260 expect(checkMove(s, { from: [6, 1], path: [[4, 3], [2, 1]], captures: [[5, 2], [3, 2]] })).toBe('');
261 expect(checkMove(s, { from: [6, 1], path: [[4, 3]], captures: [[5, 2]] })).toContain('extend');
262 expect(checkMove(s, { from: [7, 6], path: [[6, 5]], captures: [] })).toContain('capture');
263 const q = fromBoard(put({ '4,3': 'p', '5,4': 'p', '7,0': 'o' }), 'player', 1);
264 expect(checkMove(q, { from: [4, 3], path: [[5, 2]], captures: [] })).toContain('forward');
265 expect(checkMove(q, { from: [4, 3], path: [[3, 2], [2, 1]], captures: [] })).toContain('more than one');
266 expect(checkMove(q, { from: [7, 0], path: [[6, 1]], captures: [] })).toContain('not the mover');
267 expect(checkMove(q, { from: [5, 4], path: [[4, 3]], captures: [] })).toContain('occupied'); // step onto an occupied square
268 const j = fromBoard(put({ '6,1': 'p', '5,2': 'o', '4,3': 'o', '3,4': 'p', '0,7': 'o' }), 'player', 1);
269 expect(checkMove(j, { from: [6, 1], path: [[4, 3]], captures: [[5, 2]] })).toContain('occupied'); // jump onto an occupied square
270 const own = fromBoard(put({ '6,1': 'p', '5,2': 'p', '0,7': 'o' }), 'player', 1);
271 expect(checkMove(own, { from: [6, 1], path: [[4, 3]], captures: [[5, 2]] })).toContain('opposing'); // jump over an own piece
272 const back = fromBoard(put({ '4,3': 'p', '5,4': 'o', '0,1': 'o' }), 'player', 1);
273 expect(checkMove(back, { from: [4, 3], path: [[6, 5]], captures: [[5, 4]] })).toContain('forward'); // a man jumping backward
274 const crown = fromBoard(put({ '2,1': 'p', '1,2': 'o', '1,4': 'o', '7,0': 'o' }), 'player', 1);
275 expect(checkMove(crown, { from: [2, 1], path: [[0, 3], [2, 5]], captures: [[1, 2], [1, 4]] })).toContain('past the far row'); // goes on after crowning
276 });
277
278 // candidates(state, all) -> moves built from the board alone, without moves(): every one-square step in all four
279 // directions (legal or not; those onto an occupied square only when all is set, which the games do every fourth ply), every two-square jump in all four, and every chain of legal hops with every prefix of
280 // it, carried on past the far row too, since a man that does that must be refused.
281 function candidates(s, all) {
282 const side = s.turn, out = [], g = gridOf(s); // g is shared: every change below is put back
283 const hops = (from, at, r, c, path, caps, all) => {
284 for (const dr of [-2, 2]) for (const dc of [-2, 2]) {
outdated

Only every 8th ply checks that each listed move is accepted; the box says every. Also add the converse: independently generated candidates that are accepted must be in keys.

285 const [lr, lc, kr, kc] = [r + dr, c + dc, r + dr / 2, c + dc / 2];
286 if (!onBoard(lr, lc) || g[lr][lc] !== '.' || !owner(g[kr][kc]) || owner(g[kr][kc]) === side) continue;
287 if (!all && !dirsFor(at, side).includes(dr / 2)) continue;
288 const taken = g[kr][kc];
289 const p = [...path, [lr, lc]], k = [...caps, [kr, kc]];
290 out.push({ from, path: p, captures: k });
291 g[kr][kc] = '.';
292 hops(from, at.toUpperCase(), lr, lc, p, k, false);
293 g[kr][kc] = taken;
outdated

Prefix refusal is fine, but the "accepted implies listed" direction is never probed with moves not drawn from the list.

294 }
295 };
296 for (let r = 0; r < SIZE; r++) for (let c = 0; c < SIZE; c++) {
297 const ch = g[r][c];
298 if (owner(ch) !== side) continue;
299 for (const dr of [-1, 1]) for (const dc of [-1, 1]) if (onBoard(r + dr, c + dc) && (all || g[r + dr][c + dc] === '.')) out.push({ from: [r, c], path: [[r + dr, c + dc]], captures: [] });
300 g[r][c] = '.';
301 hops([r, c], ch, r, c, [], [], true);
302 g[r][c] = ch;
303 }
304 return out;
outdated

Only the first step found is tried (tried stops both loops). Try every step of every player piece.

305 }
306
307 test('200 seeded games: the move list is exactly the legal one, and move accepts exactly the listed moves', () => {
308 let listed = 0, jumped = 0, multi = 0, crowned = 0, refused = 0, mustCapture = 0;
309 for (let seed = 1; seed <= 200; seed++) {
310 const pick = picker(seed);
311 let s = start(seed);
312 for (let ply = 0; ply < 300 && s.status === 'playing'; ply++) {
313 const where = `seed ${seed} ply ${ply}`;
314 const list = moves(s);
315 must(list.length > 0, `${where}: playing but no moves`);
316 const keys = new Set(list.map(fkey));
317 must(keys.size === list.length, `${where}: a move listed twice`);
318 for (const m of list) { const e = checkMove(s, m); must(!e, `${where}: ${e}`); }
319 listed += list.length;
320 const anyCap = list[0].captures.length > 0;
321 if (anyCap) jumped++;
322 if (s.turn === 'player') {
323 const cands = candidates(s, ply % 4 === 0), seen = new Set(cands.map(fkey));
324 for (const k of keys) must(seen.has(k), `${where}: listed move ${k} is not one the board allows`);
325 for (const m of list) cands.push(m);
326 const done = new Set(), after = new Map();
327 for (const m of cands) {
328 const k = fkey(m);
329 if (done.has(k)) continue;
330 done.add(k);
331 const r = move(s, m.from, m.path);
332 if (r.ok !== keys.has(k)) throw new Error(`${where}: move ${r.ok ? 'accepts' : 'refuses'} ${k}, ${keys.has(k) ? 'listed' : 'not listed'}`);
333 if (!r.ok) {
334 must(r.state === s, `${where}: refused move changed the state`);
335 refused++;
336 const [tr, tc] = m.path[0], plainStep = m.path.length === 1 && Math.abs(tr - m.from[0]) === 1;
337 if (anyCap && plainStep && s.board[tr][tc] === '.' && dirsFor(s.board[m.from[0]][m.from[1]], 'player').includes(tr - m.from[0])) {
338 must(r.why === 'must-capture', `${where}: step over a capture refused as ${r.why}`);
339 mustCapture++;
340 }
341 } else { after.set(k, r.state); if (m.path.length > 1) multi++; }
342 }
343 const foe = firstOf(s, 'opponent');
344 const res = move(s, foe, [[foe[0] + 1, foe[1] + 1]]); // the other side's piece
345 must(res.ok === false && res.state === s, `${where}: opposing piece moved`); refused++;
346 const m = list[pick(list.length)];
347 s = after.get(fkey(m));
348 if (s.crowned) crowned++;
349 } else {
350 const res = move(s, list[0].from, list[0].path); // the side not to move
351 must(res.ok === false && res.why === 'not-your-turn' && res.state === s, `${where}: out-of-turn move`); refused++;
352 const r = reply(s);
353 must(r.ok && keys.has(fkey(r.state.last)), `${where}: reply not in the list`);
354 s = r.state;
355 }
356 }
357 }
358 expect(listed).toBeGreaterThan(5000);
359 expect(jumped).toBeGreaterThan(200); // the games really did meet captures,
360 expect(multi).toBeGreaterThan(0); // multi-jumps
361 expect(crowned).toBeGreaterThan(0); // and crownings
362 expect(refused).toBeGreaterThan(1000);
363 expect(mustCapture).toBeGreaterThan(100); // and refused steps over a capture
364 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs