fertig-classic-games/tools/verifyFarkel.js

315 lines
17 KiB
JavaScript
Raw Permalink 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.

#!/usr/bin/env node
// verifyFarkel.js — headless checks for Farkle:
// • scoring table (standard + every house rule), parts/labels
// • per-roll scoring: dice from different throws never combine (regressions)
// • farkle odds by enumeration, hot dice, entry minimum, bank gating
// • final round, three-Farkle penalty, piggyback, rankings, autosave JSON
// • solver: odds, textbook keeps, monotone values, reach solver
// • AI: never banks below entry or short of the final-round leader;
// seeded self-play terminates; skill ladder 1 < 2 < 3 < 4 < 5
// • screen layout: furniture on screen, no overlaps (when present)
// Usage: node tools/verifyFarkel.js [--quick]
import * as L from '../src/games/farkel/FarkelLogic.js';
import { DEFAULT_RULES, FARKLE_ODDS, normalizeRules, scoringReference } from '../src/games/farkel/FarkelData.js';
import { pointsSolver, reachSolver, bestKeep, rankKeeps, farkleChance } from '../src/games/farkel/FarkelSolver.js';
import { planDecision, wantsPiggyback, coachAdvice } from '../src/games/farkel/FarkelAI.js';
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
const QUICK = process.argv.includes('--quick');
let pass = 0, fail = 0;
function ok(label, cond, detail = '') {
if (cond) pass++;
else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; }
}
const section = (n) => console.log(`\n${n}`);
const R = (o = {}) => normalizeRules(o);
// ── scoring ──────────────────────────────────────────────────────────────────
section('Scoring');
{
const T = [
[[1], 100], [[5], 50], [[1, 1], 200], [[5, 5], 100], [[1, 5], 150],
[[1, 1, 1], 1000], [[2, 2, 2], 200], [[3, 3, 3], 300], [[4, 4, 4], 400], [[5, 5, 5], 500], [[6, 6, 6], 600],
[[2, 2, 2, 2], 1000], [[3, 3, 3, 3, 3], 2000], [[4, 4, 4, 4, 4, 4], 3000],
[[1, 1, 1, 1], 1100], [[5, 5, 5, 5], 1000], [[1, 1, 1, 1, 1, 1], 3000],
[[1, 2, 3, 4, 5, 6], 1500], [[2, 2, 3, 3, 4, 4], 1500], [[2, 2, 2, 2, 3, 3], 1500],
[[2, 2, 2, 3, 3, 3], 500], [[1, 1, 1, 5, 5, 5], 1500], [[2, 2, 2, 1], 300], [[3, 3, 3, 5, 5], 400],
];
for (const [d, pts] of T) {
const r = L.scoreSelection(d);
ok(`score ${d.join('')} = ${pts}`, r.valid && r.points === pts, JSON.stringify(r));
}
for (const d of [[2], [1, 2], [2, 2], [3, 4], [1, 1, 6], [2, 3, 4, 5, 6]]) {
ok(`invalid ${d.join('')}`, !L.scoreSelection(d).valid);
}
// house rules
ok('two triplets 2500', L.scoreSelection([2, 2, 2, 3, 3, 3], R({ twoTriplets: true })).points === 2500);
ok('two triplets beats 1s+5s triples', L.scoreSelection([1, 1, 1, 5, 5, 5], R({ twoTriplets: true })).points === 2500);
const dbl = R({ doubling: true });
ok('doubling four 2s = 400', L.scoreSelection([2, 2, 2, 2], dbl).points === 400);
ok('doubling five 3s = 1200', L.scoreSelection([3, 3, 3, 3, 3], dbl).points === 1200);
ok('doubling six 1s = 8000', L.scoreSelection([1, 1, 1, 1, 1, 1], dbl).points === 8000);
ok('doubling four 2s + pair = three pairs 1500', L.scoreSelection([2, 2, 2, 2, 3, 3], dbl).points === 1500);
// parts + reference keys line up
const keys = new Set(scoringReference(R({ twoTriplets: true })).map((r) => r.key));
for (const d of [[1], [5, 5], [1, 1, 1], [6, 6, 6], [2, 2, 2, 2], [4, 4, 4, 4, 4], [3, 3, 3, 3, 3, 3], [1, 2, 3, 4, 5, 6], [2, 2, 4, 4, 6, 6], [2, 2, 2, 3, 3, 3]]) {
const p = L.scoreParts(d, R({ twoTriplets: true }));
ok(`parts of ${d.join('')} are reference rows`, p.parts.every((x) => keys.has(x.key)), p.parts.map((x) => x.key).join());
ok(`parts of ${d.join('')} sum`, p.parts.reduce((s, x) => s + x.points, 0) === p.points);
}
ok('best keep 1,5,2,3,4,6 → straight', L.bestScoring([1, 5, 2, 3, 4, 6]).points === 1500);
ok('best keep prefers hot dice on ties', L.bestScoring([5, 5, 5, 1, 1, 1]).indices.length === 6);
ok('smart group triple', L.smartGroup([2, 4, 2, 6, 2, 3], 2).join() === '0,2,4');
ok('smart group straight', L.smartGroup([1, 2, 3, 4, 5, 6], 3).length === 6);
ok('smart group single 1', L.smartGroup([1, 2, 3, 4, 4, 6], 0).join() === '0');
ok('scoring mask', L.scoringMask([1, 2, 3, 5, 6, 6]).join() === 'true,false,false,true,false,false');
}
// ── per-roll scoring regressions (the old engine combined throws) ────────────
section('Per-roll scoring');
{
const s = L.createInitialState({ playerCount: 2 });
// set aside 1 and 5, then throw 2,3,4,6 — a Farkle, not a straight
s.phase = 'awaitPick'; s.turn.rolled = [1, 5, 2, 2, 3, 6];
L.applySetAside(s, [0, 1]);
ok('kept 150', s.turn.kept === 150 && s.turn.available === 4);
ok('2,3,4,6 after 1,5 is a Farkle', !L.hasScoring([2, 3, 4, 6]));
// set aside 2,2,2 then throw a single 2 — no four of a kind
const s2 = L.createInitialState({ playerCount: 2 });
s2.phase = 'awaitPick'; s2.turn.rolled = [2, 2, 2, 3, 4, 6];
L.applySetAside(s2, [0, 1, 2]);
ok('three 2s = 200', s2.turn.kept === 200);
ok('a lone 2 later does not score', !L.hasScoring([2, 3, 4]));
s2.phase = 'awaitPick'; s2.turn.rolled = [2, 1, 3];
ok('cannot add a 2 to an old triple', L.applySetAside(s2, [0]) === null);
ok('the 1 still scores', L.applySetAside(s2, [1])?.points === 100 && s2.turn.kept === 300);
// set aside 1,1 then 3,3,4,4 — not three pairs
ok('3,3,4,4 alone does not score', !L.hasScoring([3, 3, 4, 4]));
}
// ── odds ─────────────────────────────────────────────────────────────────────
section('Farkle odds');
{
for (let n = 1; n <= 6; n++) {
let farkles = 0, total = 6 ** n;
for (let k = 0; k < total; k++) {
const d = []; let x = k;
for (let i = 0; i < n; i++) { d.push(1 + (x % 6)); x = Math.floor(x / 6); }
if (!L.hasScoring(d)) farkles++;
}
ok(`${n}-die farkle odds`, Math.abs(farkles / total - FARKLE_ODDS[n]) < 1e-12, `${farkles}/${total}`);
ok(`${n}-die solver odds`, Math.abs(farkleChance(DEFAULT_RULES, n) - FARKLE_ODDS[n]) < 1e-12);
}
}
// ── turn flow ────────────────────────────────────────────────────────────────
section('Turn flow');
{
const s = L.createInitialState({ playerCount: 3, names: ['A', 'B', 'C'] });
ok('starts awaitRoll', s.phase === 'awaitRoll' && s.turn.available === 6);
ok('cannot bank before rolling', L.bank(s) === null);
s.phase = 'awaitPick'; s.turn.rolled = [1, 1, 1, 5, 5, 5];
const hot = L.applySetAside(s, [0, 1, 2, 3, 4, 5]);
ok('hot dice', hot.hot && s.turn.available === 6 && s.turn.kept === 1500 && s.players[0].stats.hotDice === 1);
ok('hot dice groups keep cycle', s.turn.groups[0].cycle === 0 && s.turn.cycle === 1);
ok('bank allowed ≥ entry', L.canBank(s));
const b = L.bank(s);
ok('banked 1500', b.banked === 1500 && s.players[0].score === 1500 && s.players[0].onBoard);
ok('next player', s.current === 1 && s.phase === 'awaitRoll' && s.turn.kept === 0);
// entry gating
s.phase = 'awaitPick'; s.turn.rolled = [1, 5, 2, 3, 4, 4];
L.applySetAside(s, [0, 1]);
ok('150 < entry: bank blocked', !L.canBank(s) && L.bank(s) === null);
ok('rolling on is allowed', L.canRoll(s));
// farkle
s.phase = 'farkled';
L.farkleTurn(s);
ok('farkle passes', s.current === 2 && s.players[1].stats.farkles === 1 && s.players[1].farkleStreak === 1);
// entry 0
const z = L.createInitialState({ playerCount: 2, rules: { entry: 0 } });
z.phase = 'awaitPick'; z.turn.rolled = [5, 2, 3, 4, 6, 6];
L.applySetAside(z, [0]);
ok('entry 0 allows a 50 bank', L.canBank(z));
// seeded rolls
const a = L.createInitialState({ playerCount: 2 });
const c = L.createInitialState({ playerCount: 2 });
L.rollDice(a, mulberry32(7)); L.rollDice(c, mulberry32(7));
ok('seeded roll repeatable', a.turn.rolled.join() === c.turn.rolled.join());
ok('state is JSON-safe', JSON.stringify(L.cloneState(a)) === JSON.stringify(a));
}
section('Final round');
{
const s = L.createInitialState({ playerCount: 3, names: ['A', 'B', 'C'] });
s.players.forEach((p) => { p.onBoard = true; });
s.players[0].score = 9800;
s.phase = 'awaitPick'; s.turn.rolled = [1, 1, 1, 2, 3, 4];
L.applySetAside(s, [0, 1, 2]);
L.bank(s);
ok('final round triggered', s.finalRound && s.finalFrom === 0 && s.players[0].score === 10800);
ok('B needs 10,850 − score', L.finalRoundNeed(s) === 10800 - s.players[1].score + 50);
s.phase = 'farkled'; L.farkleTurn(s);
ok('C still to play', s.phase === 'awaitRoll' && s.current === 2);
s.players[2].score = 11000;
ok('C leads: needs nothing', L.finalRoundNeed(s) === 0);
s.phase = 'farkled'; L.farkleTurn(s);
ok('game over after the lap', L.isGameOver(s) && s.winners.join() === '2');
ok('rankings', L.rankings(s).join() === '2,3,1');
}
section('House rules');
{
const s = L.createInitialState({ playerCount: 2, rules: { threeFarkle: true } });
s.players[0].score = 700; s.players[0].onBoard = true;
for (let k = 0; k < 3; k++) {
s.current = 0; s.phase = 'farkled';
const r = L.farkleTurn(s);
if (k < 2) ok(`farkle ${k + 1}: no penalty`, r.penalty === 0);
else ok('third farkle costs up to 1,000', r.penalty === 700 && s.players[0].score === 0 && s.players[0].farkleStreak === 0);
}
// piggyback
const p = L.createInitialState({ playerCount: 2, rules: { piggyback: true } });
p.phase = 'awaitPick'; p.turn.rolled = [1, 1, 1, 2, 3, 4];
L.applySetAside(p, [0, 1, 2]);
L.bank(p);
ok('piggyback offered', p.piggyOffer && p.piggyOffer.kept === 1000 && p.piggyOffer.available === 3);
ok('take piggyback', L.takePiggyback(p) && p.turn.kept === 1000 && p.turn.available === 3 && !L.canBank(p));
const q = L.createInitialState({ playerCount: 2, rules: { piggyback: true } });
q.phase = 'awaitPick'; q.turn.rolled = [1, 1, 1, 2, 3, 4];
L.applySetAside(q, [0, 1, 2]); L.bank(q);
L.rollDice(q, mulberry32(3));
ok('rolling fresh declines the offer', q.piggyOffer === null && q.turn.kept === 0 && q.turn.rolls === 1);
ok('piggy AI decision is boolean', typeof wantsPiggyback(p, 5) === 'boolean');
ok('rules normalise', normalizeRules({ target: 123, entry: 7 }).target === 10000 && normalizeRules({ entry: 7 }).entry === 500);
}
// ── solver ───────────────────────────────────────────────────────────────────
section('Solver');
{
const s0 = pointsSolver(DEFAULT_RULES, 0);
const e = s0.rollValue(0, 6);
ok('expected turn ≈ 590', e > 560 && e < 620, e.toFixed(1));
const s5 = pointsSolver(DEFAULT_RULES, 500);
ok('entry rule lowers the value', s5.rollValue(0, 6) < e);
ok('never bank with 6 dice at 1000', !s0.shouldBank(1000, 6));
ok('bank 2 dice at 600', s0.shouldBank(600, 2));
ok('roll 3 dice at 200', !s0.shouldBank(200, 3));
ok('roll 4 dice at 500', !s0.shouldBank(500, 4));
ok('bank below entry impossible', !s5.shouldBank(300, 1));
let mono = true;
for (let n = 1; n <= 6; n++) for (let t = 50; t <= 5000; t += 50) if (s0.value(t, n) + 1e-9 < s0.value(t - 50, n)) mono = false;
ok('value monotone in total', mono);
const k1 = bestKeep([1, 5, 2, 3, 4, 4], 0, DEFAULT_RULES, s0);
ok('textbook: keep a lone 1 from 1,5,…', k1.indices.length === 1 && k1.points === 100);
const k2 = bestKeep([1, 2, 3, 4, 5, 6], 0, DEFAULT_RULES, s0);
ok('keep a straight', k2.points === 1500);
const r = reachSolver(DEFAULT_RULES, 1000);
const p = r.rollValue(0, 6);
ok('reach 1000 probability sane', p > 0.25 && p < 0.6, p.toFixed(3));
ok('reach is monotone in need', reachSolver(DEFAULT_RULES, 2000).rollValue(0, 6) < p);
ok('ranked keeps sorted', rankKeeps([1, 1, 5, 2, 3, 6], 0, DEFAULT_RULES, s0).every((k, i, a) => !i || a[i - 1].value >= k.value));
const st = L.createInitialState({ playerCount: 2 });
st.phase = 'awaitPick'; st.turn.rolled = [1, 5, 2, 3, 4, 4];
const adv = coachAdvice(st, [0, 1]);
ok('coach flags a 1+5 keep as worse than the lone 1', adv && adv.regret > 0 && adv.best.points === 100);
}
// ── AI play ──────────────────────────────────────────────────────────────────
function playTurn(s, skill, rng, checks) {
for (let guard = 0; guard < 200; guard++) {
if (s.piggyOffer && s.turn.rolls === 0 && wantsPiggyback(s, skill)) L.takePiggyback(s);
L.rollDice(s, rng);
if (s.phase === 'farkled') { L.farkleTurn(s); return 0; }
const me = s.players[s.current];
const need = L.finalRoundNeed(s);
const d = planDecision(s, skill, rng);
const res = L.applySetAside(s, d.keep);
if (!res) { checks.badKeep++; return 0; }
if (d.bank) {
const leadBefore = Math.max(...s.players.filter((p) => p !== me).map((p) => p.score));
const wasFinal = s.finalRound;
const b = L.bank(s);
if (!b) { checks.badBank++; return 0; }
if (wasFinal && need > 0 && me.score <= leadBefore) checks.finalShort++;
return b.banked;
}
}
checks.stuck++;
return 0;
}
section('AI self-play');
{
const rng = mulberry32(12345);
const checks = { badKeep: 0, badBank: 0, finalShort: 0, stuck: 0 };
const GAMES = QUICK ? 120 : 600;
let turns = 0, maxTurns = 0, belowTarget = 0;
const ruleSets = [{}, { entry: 0 }, { entry: 1000, target: 5000 }, { threeFarkle: true, piggyback: true }, { doubling: true, twoTriplets: true, target: 15000 }];
for (let g = 0; g < GAMES; g++) {
const n = 2 + (g % 3);
const skills = {};
for (let i = 0; i < n; i++) skills[i] = 1 + Math.floor(rng() * 5);
const s = L.createInitialState({ playerCount: n, skills, rules: ruleSets[g % ruleSets.length] });
let k = 0;
while (!L.isGameOver(s) && k < 3000) { playTurn(s, s.players[s.current].skill, rng, checks); k++; }
turns += k; maxTurns = Math.max(maxTurns, k);
ok(`game ${g} finished`, L.isGameOver(s), `${k} turns`);
if (Math.max(...s.players.map((p) => p.score)) < s.rules.target) belowTarget++;
ok(`game ${g} winners hold the max`, s.winners.every((w) => s.players[w].score === Math.max(...s.players.map((p) => p.score))));
}
ok('every keep was legal', checks.badKeep === 0, String(checks.badKeep));
ok('never banked illegally (entry)', checks.badBank === 0, String(checks.badBank));
ok('never banked short of the final-round leader', checks.finalShort === 0, String(checks.finalShort));
ok('no stuck turns', checks.stuck === 0);
ok('winner always reached the target', belowTarget === 0, String(belowTarget));
console.log(` ${GAMES} games · avg ${(turns / GAMES).toFixed(1)} turns · max ${maxTurns}`);
}
section('Skill ladder');
{
const N = QUICK ? 30000 : 120000;
const avg = [];
for (let sk = 1; sk <= 5; sk++) {
const rng = mulberry32(900 + sk);
const checks = { badKeep: 0, badBank: 0, finalShort: 0, stuck: 0 };
let sum = 0;
for (let i = 0; i < N; i++) {
const s = L.createInitialState({ playerCount: 2, skills: { 0: sk } });
s.players[0].onBoard = true;
sum += playTurn(s, sk, rng, checks);
}
avg[sk] = sum / N;
}
console.log(` points/turn: ${avg.slice(1).map((a, i) => `${i + 1}:${a.toFixed(0)}`).join(' ')}`);
for (let sk = 2; sk <= 5; sk++) ok(`skill ${sk} > skill ${sk - 1}`, avg[sk] > avg[sk - 1] + 5, `${avg[sk].toFixed(1)} vs ${avg[sk - 1].toFixed(1)}`);
const opt = pointsSolver(DEFAULT_RULES, 0).rollValue(0, 6);
ok('skill 5 matches the solver', Math.abs(avg[5] - opt) < opt * 0.03, `${avg[5].toFixed(1)} vs ${opt.toFixed(1)}`);
}
// ── layout (optional until the scene modules exist) ─────────────────────────
section('Layout');
try {
const Y = await import('../src/games/farkel/FarkelLayout.js');
for (let nOpp = 1; nOpp <= 3; nOpp++) {
const f = Y.hudFurniture(nOpp);
for (const r of f) ok(`${r.name} on screen (${nOpp} opp)`, Y.onScreen(r), JSON.stringify(r));
for (let i = 0; i < f.length; i++) for (let j = i + 1; j < f.length; j++) {
if (Y.ALLOWED_OVERLAPS?.has(`${f[i].name}|${f[j].name}`)) continue;
ok(`${f[i].name} ∩ ${f[j].name} (${nOpp} opp)`, !Y.rectsOverlap(f[i], f[j]));
}
}
// six dice fit across the tray and the rail
for (let n = 1; n <= 6; n++) {
const xs = Array.from({ length: n }, (_, i) => Y.columnU(i, n));
ok(`${n} columns inside the felt`, xs.every((u) => u > Y.DIE_SIZE && u < Y.TRAY_FELT.w - Y.DIE_SIZE));
}
for (let k = 0; k < 6; k++) ok(`rail slot ${k} on the rail`, Y.railU(k, 6, 3) > 0 && Y.TRAY_FELT.x + Y.railU(k, 6, 3) < Y.RAIL.x + Y.RAIL.w);
} catch (e) {
if (e.code === 'ERR_MODULE_NOT_FOUND') console.log(' (layout module not present — skipped)');
else { ok('layout module loads', false, e.message); }
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);