fertig-classic-games/tools/verifyYatzi.js

312 lines
18 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.

#!/usr/bin/env node
// verifyYatzi.js — headless checks for Zahtzee:
// • scoring table, forced Joker rules, +100 bonus, commit bookkeeping/stats
// • seeded rolls, held dice untouched, sortUnheld keeps the multiset
// • upper par / bonus meter, rounds, rankings
// • solver: transition probabilities sum to 1, the known 4.6% Zahtzee odds,
// expert keeps on textbook positions
// • AI soak: every game finishes legally; 2–4 player tables; skill ladder
// strictly ordered by average score (1 < 2 < 3 < 4 < 5)
// • N-die tray throws land on the rolled faces, inside the felt, apart
// • screen layout: furniture on screen, no overlaps, pad rows on the paper
// Usage: node tools/verifyYatzi.js [--quick]
import * as L from '../src/games/yatzi/YatziLogic.js';
import { planTurn, expertAdvice, bestCategory, bonusChance } from '../src/games/yatzi/YatziAI.js';
import { ROLLS, KEEPS, solveTurn, rankKeeps, chaseOdds, maskForKeep } from '../src/games/yatzi/YatziSolver.js';
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
import { planTrayThrow, topFace } from '../src/ui/dice/Dice3D.js';
import * as Y from '../src/games/yatzi/YatziLayout.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 near = (a, b, eps) => Math.abs(a - b) <= eps;
function card(fill = {}) {
const sc = Object.fromEntries(L.CATEGORIES.map((c) => [c, null]));
return Object.assign(sc, fill);
}
function stateWith(dice, fill = {}, extra = {}) {
const s = L.createInitialState({ playerNames: [{ name: 'A' }, { name: 'B', isAI: true }] });
s.dice = dice; s.phase = 'rolling'; s.rollsRemaining = 1;
Object.assign(s.players[0].scorecard, fill);
Object.assign(s.players[0], extra);
return s;
}
// ── scoring ─────────────────────────────────────────────────────────────────────
section('Scoring');
{
const T = [
[[1, 1, 1, 2, 3], 'ones', 3], [[6, 6, 2, 6, 1], 'sixes', 18], [[2, 3, 4, 5, 6], 'fives', 5],
[[3, 3, 3, 4, 5], 'threeOfKind', 18], [[3, 3, 4, 4, 5], 'threeOfKind', 0],
[[2, 2, 2, 2, 6], 'fourOfKind', 14], [[2, 2, 2, 6, 6], 'fourOfKind', 0],
[[2, 2, 3, 3, 3], 'fullHouse', 25], [[2, 2, 2, 2, 2], 'fullHouse', 0], [[2, 2, 3, 3, 4], 'fullHouse', 0],
[[1, 2, 3, 4, 6], 'smallStraight', 30], [[3, 4, 5, 6, 6], 'smallStraight', 30], [[1, 2, 3, 5, 6], 'smallStraight', 0],
[[2, 3, 4, 5, 6], 'largeStraight', 40], [[1, 2, 3, 4, 6], 'largeStraight', 0],
[[4, 4, 4, 4, 4], 'yahtzee', 50], [[4, 4, 4, 4, 3], 'yahtzee', 0], [[6, 5, 4, 3, 1], 'chance', 19],
];
for (const [d, c, v] of T) ok(`${c} ${d.join('')} = ${v}`, L.baseScore(d, c) === v, `got ${L.baseScore(d, c)}`);
ok('all 13 boxes open on a fresh card', L.legalCategories([1, 2, 3, 4, 6], card()).length === 13);
ok('a filled box is not legal', !L.legalCategories([1, 2, 3, 4, 6], card({ chance: 16 })).includes('chance'));
ok('scoreForCommit returns null for a filled box', L.scoreForCommit([1, 1, 1, 1, 1], 'ones', card({ ones: 3 })) === null);
}
// ── Joker ────────────────────────────────────────────────────────────────────────
section('Joker rules (forced)');
{
const five4 = [4, 4, 4, 4, 4];
ok('first Zahtzee: no Joker, any box', L.jokerMode(five4, card()) === null && L.legalCategories(five4, card()).length === 13);
const z50 = card({ yahtzee: 50 });
ok('matching upper open → forced there', JSON.stringify(L.legalCategories(five4, z50)) === '["fours"]');
ok('forced upper scores 20', L.scoreForCommit(five4, 'fours', z50) === 20);
ok('other boxes illegal while upper is open', L.scoreForCommit(five4, 'chance', z50) === null);
const z50f = card({ yahtzee: 50, fours: 12 });
const legal = L.legalCategories(five4, z50f);
ok('upper filled → only open lower boxes', legal.length === 6 && legal.every((c) => L.LOWER.includes(c)), legal.join(','));
ok('upper zero NOT allowed while lower is open (the old bug)', !legal.includes('ones'));
ok('Joker Full House = 25', L.scoreForCommit(five4, 'fullHouse', z50f) === 25);
ok('Joker Sm. Straight = 30', L.scoreForCommit(five4, 'smallStraight', z50f) === 30);
ok('Joker Lg. Straight = 40', L.scoreForCommit(five4, 'largeStraight', z50f) === 40);
ok('Joker 4 of a Kind = sum', L.scoreForCommit(five4, 'fourOfKind', z50f) === 20);
const lowerFull = card({ yahtzee: 50, fours: 12, threeOfKind: 20, fourOfKind: 20, fullHouse: 25, smallStraight: 30, largeStraight: 40, chance: 22 });
const l2 = L.legalCategories(five4, lowerFull);
ok('lower full → scratch an open upper box', L.jokerMode(five4, lowerFull) === 'scratch' && l2.length === 5 && l2.every((c) => L.UPPER.includes(c)));
ok('the scratch scores 0', L.scoreForCommit(five4, 'sixes', lowerFull) === 0);
let s = stateWith(five4, { yahtzee: 50, fours: 12 });
s = L.commitScore(s, 'largeStraight');
ok('+100 bonus awarded with 50 in the box', s.players[0].yahtzeeBonusCount === 1 && s.lastBonusGained && s.lastCommit.bonus);
ok('bonus counted in the totals', L.computeTotals(s.players[0]).yahtzeeBonus === 100);
let s0 = stateWith(five4, { yahtzee: 0, fours: 12 });
ok('scratched Zahtzee box: Joker still forced to lower', L.jokerMode(five4, s0.players[0].scorecard) === 'lower');
s0 = L.commitScore(s0, 'fullHouse');
ok('…but no +100', s0.players[0].yahtzeeBonusCount === 0 && s0.players[0].scorecard.fullHouse === 25);
}
// ── commit / turn flow ──────────────────────────────────────────────────────────
section('Commit and turn flow');
{
let s = stateWith([6, 6, 6, 2, 2]);
const t = L.commitScore(s, 'fullHouse');
ok('commit writes the box', t.players[0].scorecard.fullHouse === 25);
ok('turn passes to the next player', t.current === 1 && t.rollsRemaining === 3 && t.phase === 'preroll');
ok('holds reset', t.held.every((h) => !h));
ok('lastCommit recorded', t.lastCommit.category === 'fullHouse' && t.lastCommit.value === 25 && t.lastCommit.player === 0);
ok('best turn stat', t.players[0].stats.bestTurn.value === 25);
ok('illegal commit is a no-op', L.commitScore(t, 'chance') === t);
ok('log line written', t.log.length === 1 && t.log[0].includes('Full House'));
const sc = L.commitScore(stateWith([1, 2, 3, 5, 6]), 'yahtzee');
ok('scratch counted', sc.players[0].stats.scratches === 1 && sc.players[0].scorecard.yahtzee === 0);
const ub = L.commitScore(stateWith([6, 6, 6, 6, 1], { ones: 3, twos: 6, threes: 9, fours: 12, fives: 15 }), 'sixes');
ok('upper bonus flagged on the commit that earns it', ub.lastCommit.upperBonusEarned && L.computeTotals(ub.players[0]).upperBonus === 35);
ok('toggleHold only while rolling', L.toggleHold(L.createInitialState({ playerNames: [{ name: 'A' }] }), 0).held[0] === false);
}
// ── rolling ─────────────────────────────────────────────────────────────────────
section('Rolling');
{
const base = L.createInitialState({ playerNames: [{ name: 'A' }] });
const a = L.rollDice(base, mulberry32(7)), b = L.rollDice(base, mulberry32(7));
ok('seeded rolls repeat', JSON.stringify(a.dice) === JSON.stringify(b.dice));
ok('roll uses one throw', a.rollsRemaining === 2 && a.phase === 'rolling');
let h = L.setHeld(a, [true, false, true, false, false]);
const r2 = L.rollDice(h, mulberry32(99));
ok('held dice untouched', r2.dice[0] === a.dice[0] && r2.dice[2] === a.dice[2]);
let all = true, sortedOk = true;
const rng = mulberry32(3);
for (let i = 0; i < 2000; i++) {
let s = L.rollDice(base, rng);
s.dice.forEach((d) => { if (d < 1 || d > 6 || !Number.isInteger(d)) all = false; });
s = L.setHeld(s, [rng() < 0.5, rng() < 0.5, rng() < 0.5, rng() < 0.5, rng() < 0.5]);
const r = L.rollDice(s, rng);
const srt = L.sortUnheld(r);
const idx = [0, 1, 2, 3, 4].filter((k) => !r.held[k]);
const before = idx.map((k) => r.dice[k]).sort().join();
const after = idx.map((k) => srt.dice[k]);
if (after.join() !== before) sortedOk = false;
if (r.held.some((hh, k) => hh && srt.dice[k] !== r.dice[k])) sortedOk = false;
}
ok('dice are always 1–6', all);
ok('sortUnheld sorts only the rolled dice and keeps the multiset', sortedOk);
const done = { ...a, rollsRemaining: 0, phase: 'scoring' };
ok('no fourth roll', L.rollDice(done) === done);
}
// ── par / rounds / ranks ────────────────────────────────────────────────────────
section('Par, rounds and rankings');
{
const p = { scorecard: card({ ones: 3, sixes: 24 }), yahtzeeBonusCount: 0 };
const par = L.upperPar(p);
ok('par counts against three-of-each', par.par === 6 && par.sub === 27 && par.need === 36 && par.alive);
const dead = L.upperPar({ scorecard: card({ ones: 0, twos: 0, threes: 0, fours: 0, fives: 5 }) });
ok('bonus out of reach detected', !dead.alive && dead.need === 58);
ok('bonusChance is 1 once earned, 0 when impossible', bonusChance(63, [1]) === 1 && bonusChance(0, [1]) === 0);
const s = L.createInitialState({ playerNames: [{ name: 'A' }, { name: 'B' }, { name: 'C' }] });
ok('round 1 at the start', L.roundOf(s) === 1);
s.players.forEach((pl, i) => { pl.scorecard.chance = [20, 25, 20][i]; });
ok('round 2 after everyone scores once', L.roundOf(s) === 2);
ok('ties share a rank', JSON.stringify(L.rankings(s)) === '[2,1,2]');
}
// ── solver ──────────────────────────────────────────────────────────────────────
section('Solver');
{
ok('252 rolls, 462 keeps', ROLLS.length === 252 && KEEPS.length === 462);
ok('roll probabilities sum to 1', near(ROLLS.reduce((a, r) => a + r.p, 0), 1, 1e-9));
const sol = solveTurn((d) => (L.isYahtzee(d) ? 1 : 0));
const p3 = ROLLS.reduce((a, r, i) => a + r.p * sol.V[2][i], 0);
ok('Zahtzee in three throws ≈ 4.60% (known value 4.6029%)', near(p3, 0.046029, 0.00005), (p3 * 100).toFixed(4) + '%');
const ls = chaseOdds('ls', L.isLargeStraight, [2, 3, 4, 5, 5], 2);
ok('open-ended four-run with two throws ≈ 55.6% for a Large Straight', near(ls, 1 - (2 / 3) ** 2, 1e-9), ls.toFixed(4));
const adv = expertAdvice([5, 5, 5, 5, 5], [false, false, false, false, false], card(), 2);
ok('expert stands on a Zahtzee', adv.stop);
const adv2 = expertAdvice([6, 6, 6, 2, 1], [false, false, false, false, false], card(), 2);
ok('expert keeps three sixes from 6-6-6-2-1', adv2.keep.join() === '6,6,6', adv2.keep.join());
const adv3 = expertAdvice([2, 3, 4, 5, 5], [false, false, false, false, false], card(), 1);
ok('expert keeps the 2-3-4-5 run with one throw left', adv3.keep.join() === '2,3,4,5', adv3.keep.join());
ok('best box for 2-2-3-3-3 is Full House on a fresh card', bestCategory([2, 2, 3, 3, 3], card()) === 'fullHouse');
ok('expert scratches Aces, not Zahtzee, with junk', bestCategory([2, 3, 4, 6, 6], card({
twos: 6, threes: 9, fours: 12, fives: 15, sixes: 18, threeOfKind: 20, fourOfKind: 20, fullHouse: 25,
smallStraight: 30, largeStraight: 40, chance: 22,
})) === 'ones');
const m = maskForKeep([3, 5, 3, 1, 3], [3, 3], [false, false, true, false, true]);
ok('maskForKeep prefers dice already held', m[2] && m[4] && !m[0]);
const ranked = rankKeeps(solveTurn((d) => L.sumDice(d)), [1, 1, 6, 6, 2], 1);
ok('rankKeeps best-first', ranked.every((r, i) => i === 0 || r.value <= ranked[i - 1].value));
ok('keep the sixes when maximising the sum', ranked[0].dice.join() === '6,6', ranked[0].dice.join());
}
// ── AI soak ─────────────────────────────────────────────────────────────────────
function playGame(skills, seed) {
const rng = mulberry32(seed);
let s = L.createInitialState({ playerNames: skills.map((k, i) => ({ name: `P${i}`, isAI: true })) });
let turns = 0, illegal = 0;
while (s.phase !== 'gameover') {
if (++turns > 13 * skills.length + 1) return { stuck: true };
const p = s.players[s.current];
const plan = planTurn(p.scorecard, p.yahtzeeBonusCount, skills[s.current], rng);
s = L.rollDice(s, rng);
while (s.rollsRemaining > 0) {
const m = plan.chooseHold(s.dice, s.held, s.rollsRemaining);
if (plan.shouldStop(m)) break;
s = L.setHeld(s, m);
s = L.rollDice(s, rng);
}
const cat = plan.chooseCategory(s.dice);
if (!L.legalCategories(s.dice, s.players[s.current].scorecard).includes(cat)) illegal++;
const next = L.commitScore(s, cat);
if (next === s) return { stuck: true };
s = next;
}
return { s, illegal, turns };
}
section('AI soak');
{
let stuck = 0, illegal = 0, filled = true, sums = true;
const games = QUICK ? 40 : 160;
for (let g = 0; g < games; g++) {
const n = 2 + (g % 3);
const skills = Array.from({ length: n }, (_, i) => 1 + ((g + i * 2) % 5));
const r = playGame(skills, 500 + g);
if (r.stuck) { stuck++; continue; }
illegal += r.illegal;
for (const pl of r.s.players) {
if (!L.CATEGORIES.every((c) => pl.scorecard[c] !== null)) filled = false;
const t = L.computeTotals(pl);
if (t.grand !== t.upperSubtotal + t.upperBonus + t.lowerSubtotal + t.yahtzeeBonus) sums = false;
}
if (L.roundOf(r.s) !== 13) filled = false;
}
ok(`${games} mixed 2–4 player games finish`, stuck === 0, `${stuck} stuck`);
ok('every AI box choice was legal', illegal === 0, `${illegal} illegal`);
ok('every column ends with all 13 boxes filled', filled);
ok('grand totals add up', sums);
}
section('Skill ladder');
{
const N = QUICK ? 120 : 500;
const avg = {};
const skills = QUICK ? [1, 3, 5] : [1, 2, 3, 4, 5];
for (const k of skills) {
let sum = 0;
for (let g = 0; g < N; g++) sum += L.computeTotals(playGame([k], 9000 + g).s.players[0]).grand;
avg[k] = sum / N;
}
console.log(' averages: ' + skills.map((k) => `${k}=${avg[k].toFixed(1)}`).join(' '));
for (let i = 1; i < skills.length; i++) {
ok(`skill ${skills[i]} out-scores skill ${skills[i - 1]}`, avg[skills[i]] > avg[skills[i - 1]], `${avg[skills[i]].toFixed(1)} vs ${avg[skills[i - 1]].toFixed(1)}`);
}
if (avg[5]) ok('expert averages 235+', avg[5] >= 235, avg[5].toFixed(1));
}
// ── throws ──────────────────────────────────────────────────────────────────────
section('Dice throws (N-die tray)');
{
const rng = mulberry32(42);
let faces = true, inside = true, apart = 0, total = 0;
const S = Y.DIE_SIZE;
const throws = QUICK ? 120 : 400;
for (let t = 0; t < throws; t++) {
const n = 1 + (t % 5);
const want = Array.from({ length: n }, () => 1 + Math.floor(rng() * 6));
const origin = t % 2 ? Y.humanOrigin() : Y.seatOrigin(200 + (t % 3) * 375);
const plan = planTrayThrow(Y.TRAY_WORLD, origin, want, rng, S, { spread: 1.6, sep: 1.45, aim: { u0: 0.25, u1: 0.75, v0: 0.3, v1: 0.72 } });
plan.dice.forEach((d, i) => {
const last = d.frames[d.frames.length - 1];
if (topFace(last.q) !== want[i]) faces = false;
if (last.u < S / 2 - 1 || last.u > Y.TRAY_WORLD.w - S / 2 + 1 || last.v < S / 2 - 1 || last.v > Y.TRAY_WORLD.h - S / 2 + 1) inside = false;
});
for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) {
total++;
if (Math.hypot(plan.dice[i].u - plan.dice[j].u, plan.dice[i].v - plan.dice[j].v) >= S * 1.05) apart++;
}
}
ok('every die lands on the rolled face', faces);
ok('every die rests inside the felt', inside);
ok('≥ 97% of die pairs rest apart', total === 0 || apart / total >= 0.97, `${((100 * apart) / total).toFixed(1)}%`);
const two = planTrayThrow({ w: 300, h: 300 }, { u: 150, v: 360, h: 60 }, [3, 4], mulberry32(1), 30);
ok('two-die planner still returns two dice (Catan)', two.dice.length === 2 && two.dice.every((d, i) => d.top === [3, 4][i]));
}
// ── layout ──────────────────────────────────────────────────────────────────────
section('Screen layout');
{
for (let nOpp = 1; nOpp <= 3; nOpp++) {
const f = Y.hudFurniture(nOpp);
f.forEach((r) => 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++) {
ok(`${f[i].name} / ${f[j].name} don't overlap (${nOpp} opp)`, !Y.rectsOverlap(f[i], f[j]));
}
for (let k = 0; k < nOpp; k++) {
const s = Y.seatParts(k, nOpp);
ok(`seat ${k} bubble inside its seat`, Y.inside(s.bubble, s.rect));
ok(`seat ${k} portrait inside its seat`, s.portrait.x - s.portrait.r >= s.rect.x && s.portrait.y + s.portrait.r <= s.rect.y + s.rect.h);
}
}
ok('pad rows end on the paper', Y.PAD_BOTTOM <= Y.PAPER.y + Y.PAPER.h - 10, String(Y.PAD_BOTTOM));
ok('paper inside the board', Y.inside(Y.PAPER, Y.BOARD));
for (let n = 2; n <= 4; n++) {
ok(`pad columns fit (${n} players)`, Y.colX(n - 1, n) + Y.colW(n) <= Y.GRID.x + Y.GRID.w + 0.01 && Y.colW(n) >= 90);
}
Y.COLUMN_X.forEach((x, i) => {
ok(`die column ${i + 1} inside the felt`, x - Y.DIE_SIZE / 2 >= Y.TRAY_FELT.x && x + Y.DIE_SIZE / 2 <= Y.TRAY_FELT.x + Y.TRAY_FELT.w);
ok(`ledge slot ${i + 1} on the ledge`, x - 60 >= Y.LEDGE.x && x + 60 <= Y.LEDGE.x + Y.LEDGE.w);
});
const rest = Y.ground(Y.COLUMN_U[0], Y.REST_V);
ok('tray rest row inside the felt', rest.y > Y.TRAY_FELT.y + 40 && rest.y < Y.TRAY_FELT.y + Y.TRAY_FELT.h - 10);
const ledge = Y.ground(0, Y.LEDGE_V);
ok('ledge ground on the ledge top', ledge.y > Y.LEDGE.y && ledge.y < Y.LEDGE.y + 70);
ok('cup mouth below the tray', Y.CUP_MOUTH.y > Y.TRAY.y + Y.TRAY.h);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);