fertig-classic-games/tools/verifyTicketToRide.js

381 lines
20 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
// verifyTicketToRide.js — headless checks for Ticket to Ride (USA):
// • rules: payments, double-route lockout by player count, the 3-locomotive
// market sweep, end trigger + exactly one final turn each, longest trail vs a
// reference DFS, ticket scoring, forced passes + the all-stuck stall guard
// • all-AI soak across 2–5 players and mixed skills: every game finishes,
// 110 train cards conserved, trains never negative, no stalls
// • skill ladder: skill 5 vs skill 3 (mirrored seats/seeds)
// • screen layout: furniture on screen, no overlaps, map clear of the HUD
// Usage: node tools/verifyTicketToRide.js [--quick]
import * as L from '../src/games/tickettoride/TicketToRideLogic.js';
import * as AI from '../src/games/tickettoride/TicketToRideAI.js';
import { ROUTES, CITIES, TICKETS, TRAIN_COLORS, ROUTE_SCORE } from '../src/games/tickettoride/TicketToRideBoard.js';
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
import {
W, H, SHEET, TRACK, PAD, RAIL, STATUS, hudFurniture, furnitureChildren, onScreen, rectsOverlap, inside,
trackPos, TRACK_SQUARES,
} from '../src/games/tickettoride/TicketToRideLayout.js';
import { routeSegments, LAND_OUTLINE } from '../src/games/tickettoride/TicketToRideBoard.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}`);
function seedRandom(seed) { const r = mulberry32(seed); Math.random = r; return r; }
const cardsInPlay = (s) => s.trainDeck.length + s.discard.length + s.faceUp.length
+ s.players.reduce((t, p) => t + L.handCount(p), 0);
const route = (a, b, color) => ROUTES.find((r) => ((r.a === a && r.b === b) || (r.a === b && r.b === a)) && (!color || r.color === color));
const cid = (name) => CITIES.find((c) => c.name === name).id;
function blankHand(over = {}) { return { ...L.emptyHand(), ...over }; }
// A started game (setup tickets resolved) for rule tests.
function started(n = 4) {
let s = L.createInitialState(n);
while (s.pendingTickets) s = L.resolveTicketKeep(s, s.pendingTickets.seat, s.pendingTickets.drawn.slice(0, 2));
return s;
}
// ── All-AI game driver (mirrors TicketToRideGame.advance / aiTurn) ─────────────
function playGame({ players = 4, skills = null, maxSteps = 4000 } = {}) {
let s = L.createInitialState(players);
L.setPlayerNames(s, Array.from({ length: players }, (_, i) => `P${i}`));
const skillOf = (seat) => (skills ? skills[seat] : 3);
const problems = [];
let steps = 0, passes = 0;
const check = () => {
if (cardsInPlay(s) !== 110) problems.push(`cards ${cardsInPlay(s)} != 110`);
for (const p of s.players) {
if (p.trainsLeft < 0) problems.push(`seat ${p.seat} trains ${p.trainsLeft}`);
for (const k of [...TRAIN_COLORS, 'locomotive']) if (p.hand[k] < 0) problems.push(`seat ${p.seat} negative ${k}`);
const placed = p.routes.reduce((t, r) => t + ROUTES[r].length, 0);
if (placed + p.trainsLeft !== 45) problems.push(`seat ${p.seat} trains don't add up`);
}
if (s.faceUp.length > 5) problems.push('market overfull');
};
while (s.phase !== 'gameOver' && steps++ < maxSteps) {
const before = JSON.stringify(s);
if (s.pendingTickets) {
const pd = s.pendingTickets;
s = L.resolveTicketKeep(s, pd.seat, AI.chooseTicketsToKeep(s, pd.seat, pd.drawn, pd.minKeep, { skill: skillOf(pd.seat) }));
} else {
const seat = s.currentPlayer;
const a = AI.chooseAction(s, seat, { skill: skillOf(seat) });
if (a.type === 'claimRoute') s = L.claimRoute(s, seat, a.routeId, a.payment);
else if (a.type === 'drawTickets') s = L.drawTickets(s, seat);
else if (a.type === 'pass') { s = L.passTurn(s, seat); passes++; }
else {
s = L.drawTrainCard(s, seat, a.source, a.index);
if (s.currentPlayer === seat && s.drawnThisTurn === 1 && s.phase !== 'gameOver') {
const b = AI.chooseSecondDraw(s, seat, { skill: skillOf(seat) });
if (b.type === 'pass') { s = L.passTurn(s, seat); passes++; }
else s = L.drawTrainCard(s, seat, b.source, b.index);
if (s.currentPlayer === seat && s.drawnThisTurn === 1) problems.push(`second draw ignored (${JSON.stringify(b)})`);
}
}
if (JSON.stringify(s) === before) { problems.push(`stall: ${JSON.stringify(a)}`); break; }
}
check();
if (problems.length) break;
}
if (s.phase !== 'gameOver') problems.push(`unfinished after ${steps} steps`);
return { s, problems, passes };
}
// ── Rules ──────────────────────────────────────────────────────────────────────
section('Rules');
seedRandom(11);
{
const r = route(cid('Denver'), cid('Omaha')); // 4 purple
ok('Denver–Omaha is purple 4', r && r.color === 'purple' && r.length === 4);
const p = { hand: blankHand({ purple: 3, locomotive: 2 }) };
const opts = L.paymentOptions(p, r);
ok('payment: 3 purple + 1 loco first', opts[0].color === 'purple' && opts[0].colorCount === 3 && opts[0].locos === 1);
ok('payment: no pure-loco when only 2 locos', !opts.some((o) => o.colorCount === 0));
const g = route(cid('Los Angeles'), cid('Las Vegas')); // 2 gray
const p2 = { hand: blankHand({ red: 1, blue: 2, locomotive: 2 }) };
const o2 = L.paymentOptions(p2, g);
ok('gray: blue pair, red+loco, pure loco all offered', o2.length === 3 && o2[0].color === 'blue' && o2[0].locos === 0, JSON.stringify(o2));
ok('cardsForRoute = first option', JSON.stringify(L.cardsForRoute(p2, g)) === JSON.stringify(o2[0]));
}
{
// Double routes: <4 players one side closes the pair; 4+ the other stays open.
for (const n of [3, 4]) {
let s = started(n);
const [r0, r1] = ROUTES.filter((r) => r.doubleGroup === `${cid('Kansas City')}-${cid('Saint Louis')}`);
s.currentPlayer = 0; s.drawnThisTurn = 0;
s.players[0].hand = blankHand({ blue: 2, purple: 2 });
s = L.claimRoute(s, 0, r0.id);
ok(`${n}p: claimed one side`, s.claimed[r0.id] === 0);
ok(`${n}p: owner can't take the other side`, !L.routeClaimable(s, 0, r1.id));
ok(`${n}p: other seat ${n < 4 ? 'locked out' : 'may take it'}`, L.routeClaimable(s, 1, r1.id) === (n >= 4));
ok(`${n}p: lock reason text`, n < 4 ? /Double track/.test(L.routeLockReason(s, 1, r1.id) ?? '') : L.routeLockReason(s, 1, r1.id) === null);
}
}
{
// 3-locomotive sweep.
let s = started(3);
s.faceUp = ['red', 'locomotive', 'locomotive', 'blue', 'green'];
s.trainDeck[s.trainDeck.length - 1] = 'locomotive'; // next refill is the 3rd loco
const wipes = s.marketWipes;
s = L.drawTrainCard(s, 0, 'faceUp', 0);
ok('3 face-up locos sweep the market', s.marketWipes > wipes);
ok('market re-dealt to 5 with < 3 locos', s.faceUp.length === 5 && s.faceUp.filter((c) => c === 'locomotive').length < 3);
ok('cards conserved through a sweep', cardsInPlay(s) === 110);
}
{
// Face-up loco: first draw only, ends the turn.
let s = started(3);
s.faceUp = ['locomotive', 'red', 'blue', 'green', 'white'];
ok('legalFaceUp includes loco on first draw', L.legalFaceUp(s).includes(0));
const t = L.drawTrainCard(s, 0, 'faceUp', 0);
ok('face-up loco ends the turn', t.currentPlayer === 1);
let u = L.drawTrainCard(s, 0, 'faceUp', 1);
u.faceUp[0] = 'locomotive';
ok('legalFaceUp excludes loco on 2nd draw', !L.legalFaceUp(u).includes(0));
ok('2nd-draw face-up loco rejected', JSON.stringify(L.drawTrainCard(u, 0, 'faceUp', 0)) === JSON.stringify(u));
}
{
// End trigger: exactly one final turn for every player, including the trigger.
let s = started(3);
s.players[0].trainsLeft = 3;
s.players[0].hand = blankHand({ red: 5 });
const r = ROUTES.find((x) => x.length === 1);
s.currentPlayer = 0;
s = L.claimRoute(s, 0, r.id, { color: 'red', colorCount: 1, locos: 0 });
ok('≤2 trains triggers the last round', s.phase === 'lastRound' && s.endTriggered);
let turns = 0;
while (s.phase !== 'gameOver' && turns < 10) {
s = L.drawTrainCard(s, s.currentPlayer, 'deck');
s = L.drawTrainCard(s, s.currentPlayer, 'deck');
turns++;
}
ok('exactly 3 final turns in 3p', turns === 3, `got ${turns}`);
ok('scores computed', Array.isArray(s.scores) && s.winner != null);
ok('score rows carry ticket results + trail', s.scores.every((sc) => Array.isArray(sc.tickets) && Array.isArray(sc.longestRoutes)));
}
{
// Longest trail vs a reference DFS on random networks.
const ref = (s, seat) => {
const inc = new Map();
for (const rid of s.players[seat].routes) {
const r = ROUTES[rid];
for (const [x, y] of [[r.a, r.b], [r.b, r.a]]) { if (!inc.has(x)) inc.set(x, []); inc.get(x).push({ rid, y, len: r.length }); }
}
let best = 0;
const dfs = (n, used, t) => { best = Math.max(best, t); for (const e of inc.get(n) || []) if (!used.has(e.rid)) { used.add(e.rid); dfs(e.y, used, t + e.len); used.delete(e.rid); } };
for (const n of inc.keys()) dfs(n, new Set(), 0);
return best;
};
let mismatch = 0, badTrail = 0;
for (let i = 0; i < 300; i++) {
const s = started(2);
const pick = ROUTES.filter(() => Math.random() < 0.12).map((r) => r.id);
s.players[0].routes = pick;
const t = L.longestTrail(s, 0);
if (t.length !== ref(s, 0)) mismatch++;
// The trail must be a real walk using each route once.
const len = t.routes.reduce((a, r) => a + ROUTES[r].length, 0);
let walk = t.routes.length === 0 || t.cities.length === t.routes.length + 1;
for (let k = 0; walk && k < t.routes.length; k++) {
const r = ROUTES[t.routes[k]];
walk = (r.a === t.cities[k] && r.b === t.cities[k + 1]) || (r.b === t.cities[k] && r.a === t.cities[k + 1]);
}
if (len !== t.length || !walk || new Set(t.routes).size !== t.routes.length) badTrail++;
}
ok('longestTrail length = reference DFS (300 nets)', mismatch === 0, `${mismatch} mismatches`);
ok('longestTrail is a valid walk', badTrail === 0, `${badTrail} bad`);
}
{
// Ticket scoring + status.
const s = started(2);
const t = TICKETS.find((x) => x.points === 4); // Denver–El Paso
s.players[0].tickets = [{ ...t }];
s.players[0].routes = [route(cid('Denver'), cid('Santa Fe')).id, route(cid('Santa Fe'), cid('El Paso')).id];
ok('ticket completed → +points', L.ticketScore(s, 0).points === t.points);
ok('ticketStatus marks it done', L.ticketStatus(s, 0)[0].done === true);
s.players[0].routes = [];
ok('ticket missed → −points', L.ticketScore(s, 0).points === -t.points);
}
{
// Forced passes.
let s = started(3);
s.currentPlayer = 0;
ok('pass refused while a move exists', JSON.stringify(L.passTurn(s, 0)) === JSON.stringify(s));
// Soft-lock: 2nd draw, deck + discard empty, only locomotives face-up.
s.drawnThisTurn = 1;
const stash = [...s.trainDeck, ...s.discard, ...s.faceUp];
s.trainDeck = []; s.discard = []; s.faceUp = ['locomotive', 'locomotive'];
s.players[2].hand.red += stash.length - 2; // keep the 110 count honest
const la = L.legalActions(s, 0);
ok('stuck 2nd draw has no legal action', !la.any, JSON.stringify(la));
ok('AI 2nd draw passes when stuck', AI.chooseSecondDraw(s, 0, { skill: 5 }).type === 'pass');
const p = L.passTurn(s, 0);
ok('pass ends the turn', p.currentPlayer === 1 && p.drawnThisTurn === 0);
// Everyone stuck → stall guard scores the game.
let q = started(2);
const all = [...q.trainDeck, ...q.discard, ...q.faceUp];
q.trainDeck = []; q.discard = []; q.faceUp = []; q.ticketDeck = [];
for (const pl of q.players) pl.hand = L.emptyHand();
q.players[0].hand.red = all.length + 8; // red can't buy the remaining… keep count
q.players[1].hand = L.emptyHand();
for (const pl of q.players) pl.trainsLeft = 0; // nobody can claim
let guard = 0;
while (q.phase !== 'gameOver' && guard++ < 10) q = L.passTurn(q, q.currentPlayer);
ok('all-stuck round ends the game', q.phase === 'gameOver' && guard <= 3, `guard ${guard}`);
}
// ── Soak ───────────────────────────────────────────────────────────────────────
section('All-AI soak');
{
const N = QUICK ? 60 : 400;
let bad = 0, totalPasses = 0, turns = 0, first = '';
for (let i = 0; i < N; i++) {
seedRandom(1000 + i);
const players = 2 + (i % 4);
const skills = Array.from({ length: players }, (_, k) => 1 + ((i + k) % 5));
const { s, problems, passes } = playGame({ players, skills });
totalPasses += passes; turns += s.turn;
if (problems.length) { bad++; if (!first) first = `game ${i} (${players}p): ${problems[0]}`; }
}
ok(`${N} games finish cleanly`, bad === 0, `${bad} bad; first: ${first}`);
console.log(` avg turns ${(turns / N).toFixed(1)}, forced passes ${totalPasses}`);
}
{
// Starved deck: tiny decks force the pass/stall paths through the AI.
let bad = 0, first = '';
for (let i = 0; i < (QUICK ? 20 : 80); i++) {
seedRandom(5000 + i);
let s = L.createInitialState(5);
const { problems } = (() => {
// Hoard: move most of the deck into a phantom hand so the deck runs dry.
const keep = 12;
const moved = s.trainDeck.splice(0, Math.max(0, s.trainDeck.length - keep));
for (const c of moved) s.players[4].hand[c]++;
s.players[4].trainsLeft = 45;
const probs = [];
let steps = 0;
while (s.phase !== 'gameOver' && steps++ < 4000) {
const before = JSON.stringify(s);
if (s.pendingTickets) {
const pd = s.pendingTickets;
s = L.resolveTicketKeep(s, pd.seat, AI.chooseTicketsToKeep(s, pd.seat, pd.drawn, pd.minKeep, { skill: 3 }));
continue;
}
const seat = s.currentPlayer;
const a = AI.chooseAction(s, seat, { skill: 1 + (seat % 5) });
if (a.type === 'claimRoute') s = L.claimRoute(s, seat, a.routeId, a.payment);
else if (a.type === 'drawTickets') s = L.drawTickets(s, seat);
else if (a.type === 'pass') s = L.passTurn(s, seat);
else {
s = L.drawTrainCard(s, seat, a.source, a.index);
if (s.currentPlayer === seat && s.drawnThisTurn === 1) {
const b = AI.chooseSecondDraw(s, seat, { skill: 3 });
s = b.type === 'pass' ? L.passTurn(s, seat) : L.drawTrainCard(s, seat, b.source, b.index);
}
}
if (JSON.stringify(s) === before) { probs.push(`stall ${JSON.stringify(a)}`); break; }
if (cardsInPlay(s) !== 110) { probs.push('cards'); break; }
}
if (s.phase !== 'gameOver') probs.push('unfinished');
return { problems: probs };
})();
if (problems.length) { bad++; if (!first) first = `${i}: ${problems[0]}`; }
}
ok('starved-deck games never stall', bad === 0, first);
}
// ── Skill ladder ───────────────────────────────────────────────────────────────
section('Skill ladder (5 vs 3, mirrored)');
for (const players of [2, 4]) {
const N = QUICK ? 40 : 300;
let wins5 = 0, games = 0, pts5 = 0, pts3 = 0;
for (let i = 0; i < N; i++) {
for (const flip of [0, 1]) {
seedRandom(9000 + i);
const skills = Array.from({ length: players }, (_, k) => ((k + flip) % 2 === 0 ? 5 : 3));
const { s, problems } = playGame({ players, skills });
if (problems.length) continue;
games++;
const w = s.winner;
if (skills[w] === 5) wins5++;
s.scores.forEach((sc) => { if (skills[sc.seat] === 5) pts5 += sc.total; else pts3 += sc.total; });
}
}
const rate = wins5 / games;
const a5 = pts5 / games / (players / 2), a3 = pts3 / games / (players / 2);
console.log(` ${players}p: skill 5 wins ${(rate * 100).toFixed(1)}% of ${games} (avg pts 5:${a5.toFixed(1)} 3:${a3.toFixed(1)})`);
// With two of each skill at a 4p table the baseline is 50%; score margin is the steadier signal.
ok(`${players}p: skill 5 beats skill 3`, rate > (players === 2 ? 0.55 : 0.5) && a5 > a3 + 3, `${(rate * 100).toFixed(1)}%, +${(a5 - a3).toFixed(1)} pts`);
}
{
const N = QUICK ? 40 : 200;
let wins = 0, games = 0;
for (let i = 0; i < N; i++) for (const flip of [0, 1]) {
seedRandom(7000 + i);
const skills = flip ? [1, 3] : [3, 1];
const { s, problems } = playGame({ players: 2, skills });
if (problems.length) continue;
games++; if (skills[s.winner] === 3) wins++;
}
console.log(` 2p: skill 3 beats skill 1 ${(wins / games * 100).toFixed(1)}%`);
ok('skill 3 beats skill 1', wins / games > 0.55);
}
// ── Layout ─────────────────────────────────────────────────────────────────────
section('Layout');
{
for (const n of [1, 2, 3, 4]) {
const f = hudFurniture({ opponents: n });
for (const r of f) ok(`${r.name} on screen (${n} opp)`, 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}`, !rectsOverlap(f[i], f[j]), `${JSON.stringify(f[i])} ${JSON.stringify(f[j])}`);
}
}
const f = hudFurniture({ opponents: 4 });
const byName = Object.fromEntries(f.map((r) => [r.name, r]));
for (const k of furnitureChildren()) ok(`${k.name} inside ${k.parent}`, inside(k, byName[k.parent]), JSON.stringify(k));
// Pad furniture stays on the pad; rail furniture on the rail; the sheet clears both.
for (const r of f) {
const onPad = inside(r, PAD), onRail = inside(r, RAIL);
ok(`${r.name} sits on the pad or the rail`, onPad || onRail, JSON.stringify(r));
ok(`${r.name} clear of the map sheet`, !rectsOverlap(r, SHEET));
}
ok('sheet clear of pad + rail', !rectsOverlap(SHEET, PAD) && !rectsOverlap(SHEET, RAIL));
// Everything on the map sits inside the score track.
const innerX0 = SHEET.x + TRACK.inset + TRACK.band, innerY0 = SHEET.y + TRACK.inset + TRACK.band;
const innerX1 = SHEET.x + SHEET.w - TRACK.inset - TRACK.band, innerY1 = SHEET.y + SHEET.h - TRACK.inset - TRACK.band;
const inMap = (x, y, m = 0) => x >= innerX0 + m && x <= innerX1 - m && y >= innerY0 + m && y <= innerY1 - m;
let bad = 0;
for (const c of CITIES) if (!inMap(c.x, c.y, 12) || !inMap(c.x, c.y - 34)) bad++;
ok('cities + name tags inside the track', bad === 0, `${bad} out`);
bad = 0;
for (const r of ROUTES) for (const s of routeSegments(r)) if (!inMap(s.cx, s.cy, 6)) bad++;
ok('route slots inside the track', bad === 0, `${bad} out`);
ok('land inside the track', LAND_OUTLINE.every(([x, y]) => inMap(x, y)), '');
// Status ribbon clear of city tags.
const ribbon = { x: STATUS.x - 330, y: STATUS.y - 20, w: 660, h: 40 };
const tagHit = CITIES.filter((c) => rectsOverlap(ribbon, { x: c.x - 70, y: c.y - 36, w: 140, h: 22 }));
ok('status ribbon clear of city name tags', tagHit.length === 0, tagHit.map((c) => c.name).join(', '));
// Score track: 100 distinct squares inside the band.
const seen = new Set();
let outBand = 0;
for (let i = 0; i < TRACK_SQUARES; i++) {
const p = trackPos(i);
seen.add(`${Math.round(p.x)},${Math.round(p.y)}`);
if (p.x < SHEET.x || p.x > SHEET.x + SHEET.w || p.y < SHEET.y || p.y > SHEET.y + SHEET.h) outBand++;
}
ok('score track has 100 distinct squares on the sheet', seen.size === TRACK_SQUARES && outBand === 0);
ok('trackPos wraps', JSON.stringify(trackPos(103)) === JSON.stringify(trackPos(3)) && JSON.stringify(trackPos(-2)) === JSON.stringify(trackPos(98)));
ok('screen is 1920×1080', W === 1920 && H === 1080);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);