fertig-classic-games/tools/verifyRummikub.js

391 lines
22 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Headless verification for Rummikub ("Aunt Rivka's Kitchen").
// node tools/verifyRummikub.js [--games=N] [--ladder=N]
// Exits non-zero on any failure.
//
// 1. Set validation, joker placement by position, why-invalid reasons,
// canonical order, partitioning.
// 2. The rack-set search, table attachment, run splitting, local re-solve.
// 3. Engine: deal, positional moves, auto-split, undo/reset, the opening meld
// (30 and the 50 house rule), draw/penalty, rounds & match scoring, save
// round-trip (plain JSON).
// 4. Self-play soak: 2–4 players × skills 1–5, tile conservation every turn,
// every AI plan commits legally, games end.
// 5. Skill ladder: skill 5 beats skill 1 head-to-head on paired deals.
// 6. Solver time budget on crowded tables.
// 7. Table layout: nothing overlaps the HUD or leaves the screen at worst case.
import {
isValidSet, setProblem, canonicalOrder, partitionable, solvePartition, bestRackSets,
attachToTable, localResolve, planPlay, bestMeldDecomposition,
} from '../src/games/rummikub/RummikubSolver.js';
import * as G from '../src/games/rummikub/RummikubLogic.js';
import { planTurn, coachPlan, describePlan } from '../src/games/rummikub/RummikubAI.js';
import { INITIAL_MELD_MIN, TILE_COUNT, sortByGroup, sortByRun } from '../src/games/rummikub/RummikubData.js';
let failures = 0;
function check(name, cond, detail = '') {
if (cond) { console.log(` ok ${name}`); return; }
failures++;
console.error(` FAIL ${name}${detail ? ` — ${detail}` : ''}`);
}
const arg = (k, d) => Number((process.argv.find((a) => a.startsWith(`--${k}=`)) || '').split('=')[1]) || d;
// Fixture tiles use ids well above the engine's 0..105 so they never collide.
let _id = 100000;
const T = (color, number) => ({ id: _id++, color, number, isJoker: false });
const J = () => ({ id: _id++, color: null, number: null, isJoker: true });
const show = (s) => s.map((t) => (t.isJoker ? 'J' : `${t.color[0]}${t.number}`)).join(' ');
function rng(seed) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// ── 1. Sets ─────────────────────────────────────────────────────────────────────
console.log('Set validation:');
check('run 4-5-6 red', isValidSet([T('red', 4), T('red', 5), T('red', 6)]).valid);
check('group 7 r/b/k', isValidSet([T('red', 7), T('blue', 7), T('black', 7)]).valid);
check('group of four', isValidSet([T('red', 7), T('blue', 7), T('black', 7), T('orange', 7)]).valid);
check('five not a group', !isValidSet([T('red', 7), T('blue', 7), T('black', 7), T('orange', 7), T('red', 7)]).valid);
check('group needs distinct colours', !isValidSet([T('red', 7), T('red', 7), T('blue', 7)]).valid);
check('run rejects duplicate', !isValidSet([T('red', 5), T('red', 5), T('red', 6)]).valid);
check('run does not wrap 13→1', !isValidSet([T('red', 12), T('red', 13), T('red', 1)]).valid);
check('two tiles too short', !isValidSet([T('red', 4), T('red', 5)]).valid);
{
const r = isValidSet([T('red', 5), J(), T('red', 7)]);
check('joker fills run gap (=red6)', r.valid && r.points === 18, `points ${r.points}`);
}
{
const g = isValidSet([T('red', 7), T('blue', 7), J()]);
check('joker fills group, scored at 7', g.valid && g.points === 21, `points ${g.points}`);
}
{
const j = J();
const front = isValidSet([j, T('blue', 5), T('blue', 6), T('blue', 7)]);
const back = isValidSet([T('blue', 5), T('blue', 6), T('blue', 7), j]);
check('joker in front of a run stands for the 4', front.assignment?.[j.id]?.number === 4);
check('joker behind a run stands for the 8', back.assignment?.[j.id]?.number === 8);
const j2 = J();
const edge = isValidSet([T('blue', 12), T('blue', 13), j2]);
check('joker after 13 falls back to the 11', edge.valid && edge.assignment[j2.id].number === 11);
}
check('non-adjacent reals + joker invalid', !isValidSet([T('red', 2), T('red', 9), J()]).valid);
check('13 reals + joker too long', !isValidSet(Array.from({ length: 13 }, (_, i) => T('blue', i + 1)).concat(J())).valid);
check('all-joker set invalid', !isValidSet([J(), J(), J()]).valid);
console.log('Why-invalid reasons:');
check('short run → needs 1 more', setProblem([T('red', 5), T('red', 6)]) === 'needs 1 more');
check('gap named', setProblem([T('red', 5), T('red', 7), T('red', 8)]) === 'gap at 6', setProblem([T('red', 5), T('red', 7), T('red', 8)]));
check('duplicate colour named', setProblem([T('red', 5), T('red', 5), T('blue', 5)]) === 'two reds');
check('duplicate number in a run', setProblem([T('red', 5), T('red', 5), T('red', 6)]) === 'two 5s');
check('mixed colours', setProblem([T('red', 5), T('blue', 6), T('black', 9)]) === 'mixed colours');
check('valid set has no problem', setProblem([T('red', 5), T('red', 6), T('red', 7)]) === null);
check('lone tile → needs 2 more', setProblem([T('red', 5)]) === 'needs 2 more');
console.log('Canonical order:');
check('run sorts ascending', show(canonicalOrder([T('red', 7), T('red', 5), T('red', 6)])) === 'r5 r6 r7');
check('group sorts by colour', show(canonicalOrder([T('orange', 7), T('red', 7), T('blue', 7)])) === 'r7 b7 o7');
check('invalid set left alone', show(canonicalOrder([T('red', 9), T('red', 2)])) === 'r9 r2');
console.log('Partitioning:');
check('two clean sets partition', partitionable([T('red', 1), T('red', 2), T('red', 3), T('blue', 7), T('black', 7), T('orange', 7)]));
check('missing tile fails', !partitionable([T('red', 1), T('red', 2), T('blue', 7), T('black', 7)]));
check('empty table partitions', partitionable([]));
check('overlapping runs partition', partitionable([T('red', 1), T('red', 2), T('red', 3), T('red', 3), T('red', 4), T('red', 5)]));
{
const sol = solvePartition([T('red', 3), T('red', 4), T('red', 5), T('blue', 9), T('black', 9), J()]);
check('joker-in-table partition reconstructs', !!sol && sol.length === 2);
}
check('joker before 12-13 partitions', partitionable([T('red', 12), T('red', 13), J()]));
check('stranded tile fails', !partitionable([T('red', 1), T('red', 2), T('red', 3), T('blue', 7), T('black', 7), T('orange', 7), T('orange', 1)]));
{
const tiles = [T('red', 3), T('red', 4), J(), T('red', 6)];
const sol = solvePartition(tiles);
check('solver output is in display order', !!sol && show(sol[0]) === 'r3 r4 J r6', sol && show(sol[0]));
}
// ── 2. Search ───────────────────────────────────────────────────────────────────
console.log('Rack sets & table play:');
{
const rack = [T('red', 1), T('red', 2), T('red', 3), T('blue', 10), T('black', 10), T('orange', 10), T('red', 10),
T('blue', 11), T('blue', 12), J(), T('black', 4)];
const b = bestRackSets(rack, { minPoints: 30 });
check('best rack sets lays 10 of 11', b && b.tiles === 10, b && `${b.tiles}`);
const noJ = bestRackSets(rack, { maxJokers: 0 });
check('maxJokers 0 keeps the joker', noJ && !noJ.sets.flat().some((t) => t.isJoker));
}
{
// tile-count beats greed: r5-r8 run vs. the 5s group
const rack = [T('red', 5), T('red', 6), T('red', 7), T('red', 8), T('blue', 5), T('black', 5), T('blue', 6), T('black', 6)];
const b = bestRackSets(rack);
check('search finds 6-tile layout (two groups)', b && b.tiles >= 6, b && `${b.tiles}: ${b.sets.map(show).join(' | ')}`);
}
{
const table = [[T('blue', 3), T('blue', 4), T('blue', 5), T('blue', 6), T('blue', 7)], [T('red', 9), T('blue', 9), T('black', 9)]];
const a = attachToTable(table, [T('blue', 8), T('orange', 9)]);
check('attach to run end and group', a.played.length === 2);
const sp = attachToTable(table, [T('blue', 5)], { split: true });
check('split a long run with a duplicate', sp.played.length === 1 && sp.table.length === 3, sp.table.map(show).join(' | '));
const nosp = attachToTable(table, [T('blue', 5)], { split: false });
check('no split without the split option', nosp.played.length === 0);
}
{
// red 7 only fits by breaking the 7s group and the run: r5 r6 [r7] + 7s group of four → needs re-solve
const table = [[T('red', 5), T('red', 6), T('red', 7), T('red', 8)], [T('blue', 7), T('black', 7), T('orange', 7)]];
const lr = localResolve(table, [T('red', 9)]);
check('local re-solve places a tile', lr.played.length === 1 && lr.table.every((s) => isValidSet(s).valid), lr.table.map(show).join(' | '));
const table2 = [[T('red', 4), T('red', 5), T('red', 6)], [T('red', 7), T('blue', 7), T('black', 7), T('orange', 7)]];
const lr2 = localResolve(table2, [T('red', 8)]);
check('rearrange: borrow r7 from a group of four for r4–r8', lr2.played.length === 1 && lr2.table.every((s) => isValidSet(s).valid), lr2.table.map(show).join(' | '));
}
{
const r29 = [T('red', 4), T('red', 5), T('red', 6), T('black', 9)];
check('sub-30 opening rejected', bestMeldDecomposition(r29, [], { mustReach: INITIAL_MELD_MIN }) === null);
const r30 = [T('blue', 9), T('blue', 10), T('blue', 11)];
const d = bestMeldDecomposition(r30, [], { mustReach: INITIAL_MELD_MIN });
check('30 opening accepted', !!d && d.tilesPlayed.length === 3);
check('joker counts toward opening meld', !!bestMeldDecomposition([T('orange', 10), T('orange', 11), J()], [], { mustReach: 30 }));
const p50 = planPlay([T('blue', 9), T('blue', 10), T('blue', 11)], [], { melded: false, openMin: 50 });
check('50 house rule rejects a 30 opening', p50 === null);
}
// ── 3. Engine ───────────────────────────────────────────────────────────────────
console.log('Engine:');
for (const pc of [2, 3, 4]) {
const s = G.createGame({ seed: 123, playerCount: pc });
const dealt = s.players.reduce((a, p) => a + p.rack.length, 0);
check(`${pc}p deal: 14 each + pool = 106`, dealt === 14 * pc && s.pool.length === 106 - 14 * pc);
}
check('tile factory builds 106', G.buildTiles().length === TILE_COUNT);
check('rack penalty: joker=30', G.rackPenalty([J()]) === 30);
{
let s = G.createGame({ seed: 5, playerCount: 4 });
const poolBefore = s.pool.length;
s = G.drawTile(s);
check('draw advances turn', s.currentPlayer === 1);
check('draw removes one pool tile', s.pool.length === poolBefore - 1);
check('draw is logged', s.log.at(-1)?.kind === 'draw' && s.log.at(-1).n === 1);
}
// Build a controlled position for move tests.
function fixture({ rack, table = [], melded = true, openMin = 30 }) {
let s = G.createGame({ seed: 9, playerCount: 2, rules: { openMin } });
s.players = s.players.map((p, i) => (i === 0 ? { ...p, rack, hasMelded: melded } : p));
s.table = table;
s.currentPlayer = 0;
return G.beginTurn(s);
}
{
const r5 = T('red', 5), r6 = T('red', 6), r7 = T('red', 7), r8 = T('red', 8), r4 = T('red', 4), r3 = T('red', 3), r9 = T('red', 9);
let s = fixture({ rack: [r4, r8, r3, r9], table: [[r5, r6, r7]] });
s = G.moveTiles(s, [r4.id], { type: 'set', index: 0, at: 0 });
check('positional insert at the front', show(s.workingTable[0]) === 'r4 r5 r6 r7');
s = G.moveTiles(s, [r8.id], { type: 'set', index: 0, at: 0 });
check('valid set reorders itself (r8 dropped at front)', show(s.workingTable[0]) === 'r4 r5 r6 r7 r8');
const gap = G.moveTiles(s, [r6.id], { type: 'newSet' });
check('a gap that leaves short pieces stays together', gap.workingTable.length === 2 && show(gap.workingTable[0]) === 'r4 r5 r7 r8',
gap.workingTable.map(show).join(' | '));
s = G.moveTiles(s, [r3.id, r9.id], { type: 'set', index: 0 });
check('two tiles at once', show(s.workingTable[0]) === 'r3 r4 r5 r6 r7 r8 r9');
s = G.moveTiles(s, [r6.id], { type: 'newSet' });
check('pulling from the middle splits into two valid runs', s.workingTable.length === 3 && show(s.workingTable[0]) === 'r3 r4 r5' && show(s.workingTable[1]) === 'r7 r8 r9',
s.workingTable.map(show).join(' | '));
const lifted = G.liftTiles(s, [r6.id]);
check('lift without placing', lifted.table.length === 2 && lifted.moving[0] === r6);
s = G.undoMove(s);
check('undo restores the previous move', s.workingTable.length === 1 && show(s.workingTable[0]) === 'r3 r4 r5 r6 r7 r8 r9');
s = G.undoMove(G.undoMove(G.undoMove(s)));
check('undo back to the start', show(s.workingTable[0]) === 'r5 r6 r7' && s.workingRack.length === 4);
check('nothing left to undo', !G.canUndo(s));
const bad = G.moveTiles(s, [r5.id], { type: 'rack' });
check('table tiles cannot go to the rack', !!bad.commitError && bad.workingTable[0].length === 3);
}
{
const j = J();
const b5 = T('blue', 5), b6 = T('blue', 6), b7 = T('blue', 7);
let s = fixture({ rack: [j, b5, b6, b7] });
s = G.moveTiles(s, [b5.id], { type: 'newSet' });
s = G.moveTiles(s, [b6.id], { type: 'set', index: 0 });
s = G.moveTiles(s, [b7.id], { type: 'set', index: 0 });
s = G.moveTiles(s, [j.id], { type: 'set', index: 0, at: 0 });
const v = isValidSet(s.workingTable[0]);
check('joker dropped at the front plays as the 4', v.valid && v.assignment[j.id].number === 4, show(s.workingTable[0]));
}
{
// opening meld bookkeeping and the 30/50 rule
const tiles = [T('blue', 9), T('blue', 10), T('blue', 11)];
let s = fixture({ rack: tiles.slice(), melded: false });
s = G.moveTiles(s, tiles.map((t) => t.id), { type: 'newSet' });
check('opening of 30 commits', G.validateCommit(s).ok);
let h = fixture({ rack: tiles.slice(), melded: false, openMin: 50 });
h = G.moveTiles(h, tiles.map((t) => t.id), { type: 'newSet' });
const v = G.validateCommit(h);
check('opening of 30 fails the 50 rule', !v.ok && /50/.test(v.reason));
const tbl = [[T('red', 1), T('red', 2), T('red', 3)]];
let m = fixture({ rack: [T('red', 4), ...tiles], table: tbl, melded: false });
m = G.moveTiles(m, [m.workingRack[0].id], { type: 'set', index: 0 });
m = G.moveTiles(m, tiles.map((t) => t.id), { type: 'newSet' });
check('no touching the table before opening', !G.validateCommit(m).ok);
}
{
// reset & draw with tiles staged
const tiles = [T('blue', 9), T('blue', 10), T('orange', 2)];
let s = fixture({ rack: tiles.slice() });
s = G.moveTiles(s, [tiles[0].id, tiles[1].id], { type: 'newSet' });
check('staged changes seen', G.hasStagedChanges(s));
const d = G.drawTile(s);
check('draw with staged tiles resets them first', d.players[0].rack.length === 4 && d.table.length === 0);
const r = G.resetTurn(s);
check('reset returns staged tiles', r.workingRack.length === 3 && r.workingTable.length === 0);
check('reset is undoable', G.canUndo(r) && G.undoMove(r).workingTable.length === 1);
}
{
// timeout penalty
const tiles = [T('blue', 9), T('blue', 10), T('orange', 2)];
let s = fixture({ rack: tiles.slice() });
s = G.moveTiles(s, [tiles[0].id], { type: 'newSet' });
const f = G.forfeitTurn(s);
check('timeout draws the 3-tile penalty', f.players[0].rack.length === 6 && f.log.at(-1).penalty);
}
{
// round & match scoring: zero-sum, history, match end
let s = G.createGame({ seed: 77, playerCount: 3, rules: { match: 'r3' } });
let rounds = 0;
for (let guard = 0; guard < 20000 && s.phase !== 'gameOver'; guard++) {
if (s.phase === 'roundOver') { rounds++; s = G.nextRound(s); continue; }
const plan = planTurn(s, s.currentPlayer, 4, rng(guard));
if (plan.type === 'commit') s = G.commitTurn(G.stageAiPlan(s, plan)); else s = G.drawTile(s);
}
check('3-round match ends after 3 rounds', s.phase === 'gameOver' && s.match.history.length === 3, `${s.match.history.length} rounds`);
check('every round is zero-sum', s.match.history.every((h) => h.deltas.reduce((a, b) => a + b, 0) === 0));
check('match totals add up', s.match.scores.every((v, i) => v === s.match.history.reduce((a, h) => a + h.deltas[i], 0)));
check('match winner has the top score', s.match.scores[s.match.winner] === Math.max(...s.match.scores));
check('rounds rotate the first player', rounds === 2);
const json = JSON.parse(JSON.stringify(s));
check('state survives a JSON round-trip', G.tileCount(json) === TILE_COUNT && json.match.history.length === 3);
}
{
let s = G.createGame({ seed: 4, playerCount: 2, rules: { match: 't100' } });
check('points-target match parsed', s.match.spec.target === 100 && s.match.spec.rounds === null);
}
{
const r = [T('red', 9), T('blue', 3), T('red', 1), J(), T('black', 9)];
check('777 sort', show(sortByGroup(r)) === 'r1 b3 r9 b9 J');
check('789 sort', show(sortByRun(r)) === 'r1 r9 b3 b9 J');
}
{
// the Coach
const tiles = [T('blue', 9), T('blue', 10), T('blue', 11), T('red', 2)];
const s = fixture({ rack: tiles, melded: false });
const cp = coachPlan(s);
check('coach finds the opening', cp && cp.firstMeld && cp.points === 30);
check('coach describes it', /open with 30/.test(describePlan(cp, 4) ?? ''), describePlan(cp, 4));
}
// ── 4. Self-play soak ───────────────────────────────────────────────────────────
const games = arg('games', 240);
console.log(`Self-play (${games} games, skills 1–5):`);
let exceptions = 0, conserveBad = 0, illegal = 0, firstMeldBad = 0, noEnd = 0;
let slowest = 0;
const winsBySeat = {};
for (let g = 1; g <= games; g++) {
try {
const playerCount = 2 + (g % 3);
let s = G.createGame({ seed: (g * 2654435761) >>> 0, playerCount, rules: { openMin: g % 4 === 0 ? 50 : 30 } });
const rand = rng(g);
let turns = 0;
while (s.phase === 'play') {
if (++turns > 5000) { noEnd++; break; }
if (G.tileCount(s) !== TILE_COUNT) { conserveBad++; throw new Error(`tile total ${G.tileCount(s)}`); }
const seat = s.currentPlayer;
const melded = s.players[seat].hasMelded;
const skill = 1 + ((g + seat) % 5);
const t0 = Date.now();
const plan = planTurn(s, seat, skill, rand);
slowest = Math.max(slowest, Date.now() - t0);
if (plan.type === 'commit') {
const st = G.stageAiPlan(s, plan);
const v = G.validateCommit(st);
if (!v.ok) { illegal++; throw new Error(`skill ${skill} illegal commit: ${v.reason}`); }
if (!melded && (v.firstMeldPoints ?? 0) < s.rules.openMin) firstMeldBad++;
s = G.commitTurn(st);
} else s = G.drawTile(s);
for (const set of s.table) if (!isValidSet(set).valid) illegal++;
}
if (s.winner != null) winsBySeat[s.winner] = (winsBySeat[s.winner] || 0) + 1;
} catch (e) {
exceptions++;
if (exceptions <= 5) console.error(` game ${g}: ${e.message}`);
}
}
check('no exceptions during self-play', exceptions === 0, `${exceptions} games threw`);
check('tile conservation holds (106 every turn)', conserveBad === 0, `${conserveBad} violations`);
check('every AI plan commits legally', illegal === 0, `${illegal} illegal`);
check('opening-meld rule never broken', firstMeldBad === 0, `${firstMeldBad} bad`);
check('games end', noEnd === 0, `${noEnd} ran away`);
check('AI turn under 1.5s worst case', slowest < 1500, `${slowest}ms`);
console.log(` wins by seat ${JSON.stringify(winsBySeat)} · slowest AI turn ${slowest}ms`);
// ── 5. Skill ladder ─────────────────────────────────────────────────────────────
const ladder = arg('ladder', 120);
console.log(`Skill ladder (${ladder} paired 2-player deals):`);
function duel(seed, skills) {
let s = G.createGame({ seed, playerCount: 2 });
const rand = rng(seed);
for (let i = 0; i < 4000 && s.phase === 'play'; i++) {
const plan = planTurn(s, s.currentPlayer, skills[s.currentPlayer], rand);
s = plan.type === 'commit' ? G.commitTurn(G.stageAiPlan(s, plan)) : G.drawTile(s);
}
return s.winner;
}
for (const [hi, lo] of [[5, 1], [3, 1], [4, 2], [5, 3]]) {
let w = 0;
for (let i = 0; i < ladder; i++) {
const seed = (i * 97 + 13) >>> 0;
if (duel(seed, [hi, lo]) === 0) w++;
if (duel(seed, [lo, hi]) === 1) w++;
}
const rate = w / (ladder * 2);
check(`skill ${hi} beats skill ${lo} (${Math.round(rate * 100)}%)`, rate > 0.55, `${Math.round(rate * 100)}%`);
}
// ── 6. Solver time on a crowded table ──────────────────────────────────────────
console.log('Solver budget:');
{
let worst = 0;
for (let k = 0; k < 20; k++) {
// grow a crowded table by self-play, then time a full plan from a big rack
let s = G.createGame({ seed: 5000 + k, playerCount: 4 });
const rand = rng(k);
for (let i = 0; i < 40 && s.phase === 'play'; i++) {
const plan = planTurn(s, s.currentPlayer, 2, rand);
s = plan.type === 'commit' ? G.commitTurn(G.stageAiPlan(s, plan)) : G.drawTile(s);
}
if (s.phase !== 'play') continue;
const bigRack = [...s.players[0].rack, ...s.pool.slice(0, 16)];
const t0 = Date.now();
planPlay(bigRack, s.table, { melded: true, level: 5 });
worst = Math.max(worst, Date.now() - t0);
}
check('level-5 plan on a crowded table under 1.5s', worst < 1500, `${worst}ms`);
console.log(` worst ${worst}ms`);
}
// ── 7. Layout ───────────────────────────────────────────────────────────────────
console.log('Layout:');
{
const Tb = await import('../src/games/rummikub/RummikubTable.js').catch(() => null);
if (Tb?.verifyLayout) {
const problems = Tb.verifyLayout();
check('table layout fits (worst cases)', problems.length === 0, problems.slice(0, 6).join('; '));
} else console.log(' (no layout module yet)');
}
console.log(failures ? `\n${failures} check(s) FAILED` : '\nAll checks passed.');
process.exit(failures ? 1 : 0);