fertig-classic-games/tools/verifyHearts.js

283 lines
16 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
// verifyHearts.js — headless checks for Hearts: rules (deal, passing in all
// four directions, 2♣ lead, follow suit, hearts breaking, first-trick rule,
// scoring, both moon rules, match end at the target), the memory helpers and
// AI (always legal, skill timing), the den layout (on screen, clear of the HUD
// and each other), and an all-AI soak (every match ends, 52 cards conserved,
// skill ordering by points per hand).
// Usage: node tools/verifyHearts.js [--quick]
import * as Hr from '../src/games/hearts/HeartsLogic.js';
import { Card } from '../src/games/cards/Deck.js';
import { choosePass, choosePlay, suggestPass, suggestPlay } from '../src/games/hearts/HeartsAI.js';
import { aiTiming, mulberry32 } from '../src/ui/cardtable/AITiming.js';
import {
CARD_W, CARD_H, cardBounds, fanHit, fanBounds, rectsOverlap, onScreen, hudFurniture, plateRect, inPose,
} from '../src/ui/cardtable/TableGeometry.js';
import { T, L, handPose, trickPose, tricksPose, pointRowRect, handBadge, handHome, CENTRE } from '../src/games/hearts/HeartsTable.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}`);
let nid = 500;
const C = (key) => Object.assign(new Card(key[0], key[1]), { id: nid++ });
const count = (gs) => gs.players.reduce((n, p) => n + p.hand.length + p.wonCards.length, 0) + gs.trick.length;
function playing(hands, { current = 0, broken = false, trickNumber = 1 } = {}) {
const gs = Hr.createInitialState({ seed: 4 });
gs.phase = 'playing';
gs.players.forEach((p, s) => { p.hand = hands[s].map(C); p.wonCards = []; p.roundPoints = 0; });
gs.currentPlayer = current;
gs.heartsBroken = broken;
gs.trickNumber = trickNumber;
gs.trick = [];
gs.leadSuit = null;
return gs;
}
// ── Rules ────────────────────────────────────────────────────────────────────
section('Rules');
{
const gs = Hr.createInitialState({ seed: 9 });
ok('13 cards each', gs.players.every(p => p.hand.length === 13));
ok('52 unique', new Set(gs.players.flatMap(p => p.hand.map(c => c.id))).size === 52);
ok('first hand passes left', gs.phase === 'passing' && gs.passDirection === 'left');
ok('deal is logged', gs.log.some(e => e.kind === 'deal'));
ok('pass targets', Hr.passTargetSeat(0, 'left') === 1 && Hr.passTargetSeat(0, 'right') === 3 && Hr.passTargetSeat(0, 'across') === 2);
let g = gs;
const picks = [];
for (let s = 0; s < 4; s++) { const ids = g.players[s].hand.slice(0, 3).map(c => c.id); picks.push(ids); g = Hr.selectPass(g, s, ids); }
ok('passes resolve when all four are in', g.phase === 'playing' && g.players.every(p => p.hand.length === 13));
ok('passed cards land with the left neighbour', picks[0].every(id => g.players[1].hand.some(c => c.id === id)));
ok('2♣ holder leads', g.players[g.currentPlayer].hand.some(c => c.key === '2c'));
ok('must lead the 2♣', Hr.legalPlays(g, g.currentPlayer).length === 1 && Hr.legalPlays(g, g.currentPlayer)[0].key === '2c');
// directions cycle left → right → across → hold
let h = Hr.createInitialState({ seed: 3 });
const dirs = [];
for (let k = 0; k < 4; k++) {
dirs.push(h.passDirection);
h.phase = 'handOver';
h = Hr.startNextHand(h);
}
ok('pass directions cycle', dirs.join() === 'left,right,across,hold');
let hold = Hr.createInitialState({ seed: 3 });
for (let k = 0; k < 3; k++) { hold.phase = 'handOver'; hold = Hr.startNextHand(hold); }
ok('hold hand skips passing', hold.passDirection === 'hold' && hold.phase === 'playing' && hold.players[hold.currentPlayer].hand.some(c => c.key === '2c'));
}
{
const gs = playing([['5c', 'Kh', 'Qs'], ['9c', '2h', '3d'], ['Ac', '4h', '5d'], ['2c', 'Jh', '6s']], { current: 3, trickNumber: 0 });
let g = Hr.playCard(gs, gs.players[3].hand[0].id);
ok('must follow suit', Hr.legalPlays(g, 0).every(c => c.suit === 'c'));
g = Hr.playCard(g, g.players[0].hand[0].id);
g = Hr.playCard(g, g.players[1].hand[0].id);
g = Hr.playCard(g, g.players[2].hand[0].id);
ok('highest of the led suit wins', g.lastTrick.winnerSeat === 2 && g.currentPlayer === 2);
ok('hearts not broken yet', !g.heartsBroken);
ok('cannot lead hearts before broken', Hr.legalPlays(g, 2).every(c => c.suit !== 'h'));
}
{
const first = playing([['Qs', 'Kh', '9d'], ['2c', '2h', '3d'], ['Ac', '4h', '5d'], ['3c', 'Jh', '6s']], { current: 1, trickNumber: 0 });
let g = Hr.playCard(first, first.players[1].hand[0].id);
g = Hr.playCard(g, g.players[2].hand[0].id);
g = Hr.playCard(g, g.players[3].hand[0].id);
const leg = Hr.legalPlays(g, 0);
ok('no points on the first trick when void', leg.length === 1 && leg[0].key === '9d');
const allPts = playing([['Qs', 'Kh'], ['2c', '2h'], ['Ac', '4h'], ['3c', 'Jh']], { current: 1, trickNumber: 0 });
let a = Hr.playCard(allPts, allPts.players[1].hand[0].id);
a = Hr.playCard(a, a.players[2].hand[0].id);
a = Hr.playCard(a, a.players[3].hand[0].id);
ok('…unless you hold only point cards', Hr.legalPlays(a, 0).length === 2);
const brk = playing([['5c', 'Kh'], ['9c', '2h'], ['2d', '4h'], ['3d', 'Jh']], { current: 0, trickNumber: 3 });
let b = Hr.playCard(brk, brk.players[0].hand[0].id);
b = Hr.playCard(b, b.players[1].hand[0].id);
b = Hr.playCard(b, b.players[2].hand[1].id);
ok('a heart breaks hearts (logged)', b.heartsBroken && b.log.some(e => e.kind === 'heartsBroken'));
const onlyH = playing([['Kh', '2h'], ['9c'], ['2d'], ['3d']], { current: 0, trickNumber: 3 });
ok('may lead hearts holding nothing else', Hr.legalPlays(onlyH, 0).length === 2);
const voids = playing([['5c'], ['9c'], ['2d'], ['3d']], { current: 0, trickNumber: 3 });
let v = Hr.playCard(voids, voids.players[0].hand[0].id);
v = Hr.playCard(v, v.players[1].hand[0].id);
v = Hr.playCard(v, v.players[2].hand[0].id);
ok('known voids from the log', Hr.knownVoids(v)[2].has('c'));
ok('played keys tracked', Hr.playedKeys(v).has('5c') && Hr.playedKeys(v).has('2d'));
}
{
// scoring: a full hand dealt by hand; seat 0 takes everything → moon
const mk = (target, moonMode) => {
const gs = Hr.createInitialState({ seed: 1, target, moonMode });
gs.phase = 'playing';
const suits = ['h', 's', 'd', 'c'];
const ranks = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'];
// seat 0 holds every heart; others hold the rest; Q♠ forced onto seat 0's trick
gs.players[0].hand = ranks.map(r => C(`${r}h`));
gs.players[1].hand = ranks.map(r => C(`${r}s`));
gs.players[2].hand = ranks.map(r => C(`${r}d`));
gs.players[3].hand = ranks.map(r => C(`${r}c`));
gs.players.forEach(p => { p.wonCards = []; p.roundPoints = 0; });
gs.heartsBroken = true;
gs.trickNumber = 1;
gs.currentPlayer = 0;
return gs;
};
const runOut = (g) => {
let guard = 0;
while (g.phase === 'playing' && guard++ < 100) {
const s = g.currentPlayer;
const legal = Hr.legalPlays(g, s);
// seat 1 dumps the Queen as soon as it can
const pick = s === 1 ? (legal.find(c => c.key === 'Qs') ?? legal[legal.length - 1]) : legal[legal.length - 1];
g = Hr.playCard(g, pick.id);
}
return g;
};
const m = runOut(mk(100, 'add'));
ok('moon: shooter 0, others +26', m.moonShooter === 0 && m.handScores.join() === '0,26,26,26');
const sub = runOut(mk(100, 'subtract'));
ok('moon (subtract): shooter −26, others 0', sub.handScores.join() === '-26,0,0,0');
const low = runOut(mk(20, 'add'));
ok('reaching the target ends the match, lowest wins', low.phase === 'gameOver' && low.winnerSeats.join() === '0');
ok('52 cards accounted for after a hand', m.players.reduce((n, p) => n + p.wonCards.length, 0) === 52);
}
// ── AI ───────────────────────────────────────────────────────────────────────
section('AI');
{
ok('slower hands at low skill', aiTiming(1).carry > aiTiming(3).carry && aiTiming(3).carry > aiTiming(5).carry);
const gs = Hr.createInitialState({ seed: 12 });
for (const sk of [1, 3, 5]) {
const ids = choosePass(gs, 1, { skill: sk, rng: mulberry32(sk) });
ok(`skill ${sk} passes 3 of its own cards`, ids.length === 3 && new Set(ids).size === 3 && ids.every(id => gs.players[1].hand.some(c => c.id === id)));
}
const withQ = playing([['Qs', '5c', '9d'], ['2c'], ['3c'], ['4c']], { current: 1, trickNumber: 3 });
withQ.players[0].hand = [C('Qs'), C('9d'), C('Kh')];
let g = Hr.playCard(withQ, withQ.players[1].hand[0].id);
g = Hr.playCard(g, g.players[2].hand[0].id);
g = Hr.playCard(g, g.players[3].hand[0].id);
ok('void → dumps the Queen', choosePlay(g, 0, { skill: 3, rng: () => 0.5 }) === g.players[0].hand.find(c => c.key === 'Qs').id);
const duck = playing([['Kd', '7d', '2d'], ['9d'], ['3c'], ['4c']], { current: 1, trickNumber: 3 });
const d1 = Hr.playCard(duck, duck.players[1].hand[0].id);
const d2 = Hr.playCard(Hr.playCard(d1, d1.players[2].hand[0].id), Hr.playCard(d1, d1.players[2].hand[0].id).players[3].hand[0].id);
ok('ducks under the winner with its highest safe card', choosePlay(d2, 0, { skill: 3, rng: () => 0.5 }) === d2.players[0].hand.find(c => c.key === '7d').id);
ok('hints are legal', (() => { const s = Hr.createInitialState({ seed: 2 }); return suggestPass(s, 0).length === 3; })());
const lead = playing([['5c', '9d', 'Kh'], ['2c'], ['3c'], ['4c']], { current: 0, trickNumber: 3, broken: true });
ok('hint play is legal', Hr.isLegalPlay(lead, 0, suggestPlay(lead, 0)));
}
// ── Layout ───────────────────────────────────────────────────────────────────
section('Layout');
{
const furn = hudFurniture();
for (let s = 1; s < 4; s++) furn.push({ name: `plate ${s}`, r: plateRect(L.seats[s].plate) });
for (let i = 0; i < furn.length; i++) for (let j = i + 1; j < furn.length; j++) ok(`${furn[i].name} clear of ${furn[j].name}`, !rectsOverlap(furn[i].r, furn[j].r));
const tricks = [0, 1, 2, 3].map(s => cardBounds(trickPose(s)));
for (let i = 0; i < 4; i++) for (let j = i + 1; j < 4; j++) ok(`trick spots ${i}/${j} apart`, !rectsOverlap(tricks[i], tricks[j]));
const won = [0, 1, 2, 3].map(s => {
const st = cardBounds(tricksPose(s, 20));
const pr = pointRowRect(s, 14);
return { st, pr };
});
const fans = [0, 1, 2, 3].map(s => fanBounds(L.seats[s].fan, 13, s === 0 ? 44 : 0));
for (let s = 0; s < 4; s++) {
ok(`seat ${s}: hand on screen`, onScreen(fans[s], s === 0 ? 50 : 10));
ok(`seat ${s}: trick spot on the table`, T.onFelt({ x: tricks[s].x0, y: tricks[s].y0 }) && T.onFelt({ x: tricks[s].x1, y: tricks[s].y1 }));
ok(`seat ${s}: won stack on the table`, T.onFelt({ x: won[s].st.x0, y: won[s].st.y0 }) && T.onFelt({ x: won[s].st.x1, y: won[s].st.y1 }));
ok(`seat ${s}: 14-card point row on the table`, T.onFelt({ x: won[s].pr.x0, y: won[s].pr.y0 }) && T.onFelt({ x: won[s].pr.x1, y: won[s].pr.y1 }));
ok(`seat ${s}: won stack clear of its point row`, !rectsOverlap(won[s].st, won[s].pr));
for (const f of furn) {
ok(`seat ${s}: hand clear of ${f.name}`, !rectsOverlap(fans[s], f.r), `${JSON.stringify(fans[s])} vs ${JSON.stringify(f.r)}`);
ok(`seat ${s}: point row clear of ${f.name}`, !rectsOverlap(won[s].pr, f.r));
ok(`seat ${s}: won stack clear of ${f.name}`, !rectsOverlap(won[s].st, f.r));
}
for (let t = 0; t < 4; t++) {
ok(`hand ${s} clear of trick spot ${t}`, !rectsOverlap(fans[s], tricks[t]));
ok(`hand ${s} clear of point row ${t}`, !rectsOverlap(fans[s], won[t].pr), `${JSON.stringify(fans[s])} vs ${JSON.stringify(won[t].pr)}`);
ok(`trick ${s} clear of point row ${t}`, !rectsOverlap(tricks[s], won[t].pr));
if (t !== s) ok(`point rows ${s}/${t} apart`, !rectsOverlap(won[s].pr, won[t].pr) && !rectsOverlap(won[s].pr, won[t].st));
}
if (s > 0) {
const b = handBadge(s), br = { x0: b.x - 17, x1: b.x + 17, y0: b.y - 17, y1: b.y + 17 };
ok(`seat ${s}: badge on screen`, onScreen(br));
for (const f of furn) ok(`seat ${s}: badge clear of ${f.name}`, !rectsOverlap(br, f.r));
const hh = handHome(s);
ok(`seat ${s}: ghost hand rests on screen`, hh.x > 0 && hh.x < 1920 && hh.y > 0 && hh.y < 1080);
}
}
let rt = true;
for (let i = 0; i < 13; i++) {
const p = handPose(0, i, 13);
const step = handPose(0, 1, 13).x - handPose(0, 0, 13).x;
if (fanHit(L.seats[0].fan, 13, { x: p.x - CARD_W / 2 + step * 0.45, y: p.y - CARD_H * 0.3 }) !== i) rt = false;
}
ok('hand hit-test round trip (13)', rt);
ok('drop onto your trick spot', inPose(trickPose(0), trickPose(0), 60));
ok('pass arrow centre on the table', T.onFelt(CENTRE));
}
// ── Soak ─────────────────────────────────────────────────────────────────────
section('Soak');
function match(skills, seed, opts = {}) {
const rand = mulberry32(seed);
let gs = Hr.createInitialState({ seed, ...opts });
let hands = 0, noop = 0, conserve = true;
const pts = [0, 0, 0, 0];
while (!Hr.isGameOver(gs) && hands < 80) {
let st = 0;
while (gs.phase !== 'handOver' && gs.phase !== 'gameOver' && st++ < 600) {
if (gs.phase === 'passing') { for (let s = 0; s < 4; s++) if (!gs.passReady[s]) gs = Hr.selectPass(gs, s, choosePass(gs, s, { skill: skills[s], rng: rand })); continue; }
const id = choosePlay(gs, gs.currentPlayer, { skill: skills[gs.currentPlayer], rng: rand });
const nx = Hr.playCard(gs, id);
if (nx === gs) { noop++; break; }
gs = nx;
if (count(gs) !== 52) conserve = false;
}
if (gs.phase !== 'handOver' && gs.phase !== 'gameOver') break;
hands++;
gs.handScores.forEach((p, s) => { pts[s] += p; });
if (gs.phase === 'handOver') gs = Hr.startNextHand(gs);
}
return { gs, hands, noop, conserve, pts };
}
{
const M = QUICK ? 20 : 80;
for (const opts of [{}, { target: 50 }, { moonMode: 'subtract' }]) {
let ended = 0, noops = 0, conserved = true, hands = 0;
for (let i = 0; i < M; i++) {
const r = match([1, 2, 3, 4].map((_, s) => 1 + ((i + s) % 5)), 400 + i * 7, opts);
if (Hr.isGameOver(r.gs)) ended++;
noops += r.noop;
if (!r.conserve) conserved = false;
hands += r.hands;
}
const tag = JSON.stringify(opts);
ok(`${tag}: every match ends`, ended === M, `${ended}/${M}`);
ok(`${tag}: AI never plays illegally`, noops === 0, `${noops}`);
ok(`${tag}: 52 cards conserved`, conserved);
console.log(` ${tag}: avg ${(hands / M).toFixed(1)} hands per match`);
}
// skill: one seat of skill a among three of skill b — points per hand
const vs = (a, b, games) => {
let pa = 0, pb = 0, hands = 0;
for (let i = 0; i < games; i++) {
const seat = i % 4;
const skills = [b, b, b, b]; skills[seat] = a;
const r = match(skills, 9000 + i);
hands += r.hands;
pa += r.pts[seat];
pb += r.pts.reduce((x, y) => x + y, 0) - r.pts[seat];
}
return { a: pa / hands, b: pb / hands / 3 };
};
const G = QUICK ? 80 : 300;
const s53 = vs(5, 3, G), s31 = vs(3, 1, G);
console.log(` points per hand: skill 5 ${s53.a.toFixed(2)} vs skill 3 ${s53.b.toFixed(2)} · skill 3 ${s31.a.toFixed(2)} vs skill 1 ${s31.b.toFixed(2)}`);
ok('skill 3 takes clearly fewer points than skill 1', s31.a < s31.b * 0.85);
ok('skill 5 takes fewer points than skill 3', s53.a < s53.b * (QUICK ? 1.0 : 0.97));
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);