fertig-classic-games/tools/verifyMexicanTrain.js

375 lines
23 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
// verifyMexicanTrain.js — headless checks for Mexican Train ("Sunday afternoon
// at the kitchen table"):
// • rules on hand-built positions: sets / hands / engines, train access,
// markers, draw → pass, doubles (cover and the 'relaxed' bonus play),
// the opening run, going out on a double, blocked rounds, 0-0 = 50,
// knocking + catching, descent vs points matches, voids
// • chain search against brute force; hints are always legal
// • AI soak over every set / player count / house rule: games finish, every
// tile accounted for after every action
// • skill ladder (mirrored seeds, two players)
// • layout: trains from real games never overlap, stay on the table, clear
// the hub; markers and HUD furniture don't collide
// Usage: node tools/verifyMexicanTrain.js [--quick]
import * as L from '../src/games/mexicantrain/MexicanTrainLogic.js';
import * as AI from '../src/games/mexicantrain/MexicanTrainAI.js';
import * as Lay from '../src/games/mexicantrain/MexicanTrainLayout.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 T = (a, b, set = 12) => L.makeTileSet(set).find((t) => t.a === Math.min(a, b) && t.b === Math.max(a, b));
const names = (n) => Array.from({ length: n }, (_, i) => ({ name: `P${i}`, isAI: i > 0 }));
/** A hand-built position: hands as [[a,b],…] per seat; trains as { key: [[l,r],…] }. */
function pos({ n = 2, set = 12, hub = 12, hands = [], trains = {}, markers = [], boneyard = null, current = 0, opts = {}, firstDone = true }) {
const s = L.createInitialState({ playerNames: names(n), opts: { set, ...opts }, seed: 1 });
s.hub = { value: hub, id: T(hub, hub, set).id };
const used = new Set([s.hub.id]);
s.players.forEach((p, i) => { p.hand = (hands[i] ?? []).map(([a, b]) => T(a, b, set)); p.hand.forEach((t) => used.add(t.id)); });
for (const k of L.trainKeys(n)) {
s.trains[k] = { tiles: (trains[k] ?? []).map(([l, r]) => { const t = T(l, r, set); used.add(t.id); return { id: t.id, left: l, right: r, by: 0 }; }), marker: markers.includes(k) };
}
s.boneyard = boneyard ? boneyard.map(([a, b]) => T(a, b, set)) : L.makeTileSet(set).filter((t) => !used.has(t.id));
s.current = current;
s.firstDone = s.players.map(() => firstDone);
s.turn = { seat: current, played: 0, drew: false, opening: !!s.opts.opening && !firstDone, run: false, bonus: false };
s.openDouble = null;
s.voids = s.players.map(() => ({}));
s.deferred = [];
return s;
}
const mv = (s) => L.getLegalMoves(s).map((m) => `${L.tileName(L.makeTileSet(s.opts.set)[m.tileId])}@${m.train}`).sort();
const play = (s, a, b, train) => L.playTile(s, { tileId: T(a, b, s.opts.set).id, train });
section('Sets, hands, deal');
{
ok('double-12 has 91 tiles', L.makeTileSet(12).length === 91 && L.tileCount(12) === 91);
ok('double-9 has 55, double-6 has 28', L.makeTileSet(9).length === 55 && L.makeTileSet(6).length === 28);
ok('hand sizes', L.handSizeFor(12, 4) === 15 && L.handSizeFor(9, 4) === 9 && L.handSizeFor(6, 4) === 5 && L.handSizeFor(6, 2) === 7);
for (const set of [6, 9, 12]) for (const n of [2, 3, 4]) {
const s = L.createInitialState({ playerNames: names(n), opts: { set }, seed: set * 10 + n });
const c = L.tileCensus(s);
ok(`deal d${set} ${n}p: every tile once`, c.total === c.expected && c.unique === c.expected, JSON.stringify(c));
ok(`deal d${set} ${n}p: engine ${set}-${set} in the hub`, s.hub.value === set && !s.players.some((p) => p.hand.some((t) => t.id === s.hub.id)));
ok(`deal d${set} ${n}p: hands`, s.players.every((p) => p.hand.length === L.handSizeFor(set, n)));
ok(`deal d${set} ${n}p: trains (${n} + Mexican), all empty`, Object.keys(s.trains).length === n + 1 && Object.values(s.trains).every((t) => !t.tiles.length && !t.marker));
}
ok('engines descend 12 → 0', [0, 1, 5, 12].map((r) => L.hubValueForRound(12, r)).join() === '12,11,7,0');
ok('points mode wraps the engines', L.hubValueForRound(6, 7) === 6 && L.hubValueForRound(6, 8) === 5);
}
section('Train access, markers, draw and pass');
{
let s = pos({ hands: [[[12, 3], [5, 6]], [[1, 1]]], trains: { 1: [[12, 5]] } });
ok('empty trains need the engine number; others closed', mv(s).join() === '3-12@0,3-12@mexican', mv(s).join());
s = pos({ hands: [[[12, 3], [5, 6]], [[1, 1]]], trains: { 1: [[12, 5]] }, markers: ['1'] });
ok('an open (marked) train is playable', mv(s).includes('5-6@1'), mv(s).join());
s = pos({ hands: [[[12, 3], [5, 6]], [[1, 1]]], markers: ['0'] });
s = play(s, 12, 3, '0');
ok('playing your own train takes your marker back', !s.trains['0'].marker && s.current === 1);
ok('…the tile is oriented to match', s.trains['0'].tiles[0].left === 12 && s.trains['0'].tiles[0].right === 3);
s = pos({ hands: [[[1, 2], [5, 6]], [[1, 1]]], boneyard: [[2, 3], [4, 4]] });
ok('no play → may draw, not pass', L.canDraw(s) && !L.canPass(s));
ok('may not draw while a play exists', !L.canDraw(pos({ hands: [[[12, 2]], [[1, 1]]] })));
s = L.drawTile(s);
ok('draw takes the top tile', s.players[0].hand.some((t) => t.a === 4 && t.b === 4) && s.boneyard.length === 1);
ok('one draw only', !L.canDraw(s) && L.canPass(s));
s = L.passTurn(s);
ok('pass marks your train and moves on', s.trains['0'].marker && s.current === 1 && s.lastEvent.marked);
ok('pass records the numbers you showed you lack', s.voids[0][12] === 0);
s = pos({ hands: [[[1, 2]], [[1, 1]]], boneyard: [] });
ok('empty boneyard → pass straight away', !L.canDraw(s) && L.canPass(s));
s = pos({ hands: [[[1, 2], [12, 0]], [[1, 1]]], boneyard: [[2, 3]] });
s = play(s, 12, 0, L.MEXICAN);
ok('the Mexican Train takes anyone', s.trains.mexican.tiles.length === 1 && s.current === 1);
ok('illegal plays are ignored', play(s, 1, 1, '0') === s || play(s, 1, 1, '0').trains['0'].tiles.length === 0);
}
section('Doubles');
{
let s = pos({ hands: [[[12, 12].map((x) => x), [12, 4], [5, 5]], [[4, 9], [12, 7]]], hub: 11, trains: { 0: [[11, 12]] } });
s = play(s, 12, 12, '0');
ok('a double keeps the turn', s.current === 0 && s.openDouble?.value === 12 && s.openDouble.by === 0);
ok('only the double can be covered', mv(s).join() === '4-12@0', mv(s).join());
s = play(s, 12, 4, '0');
ok('covering it passes the turn', s.current === 1 && !s.openDouble && s.stats[0].covered === 1);
s = pos({ hands: [[[12, 12], [1, 2]], [[4, 9], [12, 7]]], hub: 11, trains: { 0: [[11, 12]] }, boneyard: [[3, 3]] });
s = play(s, 12, 12, '0');
ok('can\'t cover → draw', L.canDraw(s));
s = L.drawTile(s);
s = L.passTurn(s);
ok('…then pass: your train opens and the double stays', s.trains['0'].marker && s.openDouble?.train === '0' && s.current === 1);
ok('the next player must cover it (on the now-open train)', mv(s).join() === '7-12@0', mv(s).join());
s = pos({ hands: [[[12, 12], [3, 4]], [[4, 9]]], hub: 11, trains: { 0: [[11, 12]] }, opts: { doubles: 'relaxed' } });
s = play(s, 12, 12, '0');
ok('relaxed: a double earns a bonus play, nothing to cover', s.current === 0 && !s.openDouble && s.turn.bonus);
s = pos({ hands: [[[12, 12], [3, 4]], [[4, 9]]], hub: 11, trains: { 0: [[11, 12]] }, opts: { doubles: 'relaxed' }, boneyard: [[6, 6]] });
s = play(s, 12, 12, '0');
s = L.drawTile(s); s = L.passTurn(s);
ok('relaxed: a missed bonus play doesn\'t open your train', !s.trains['0'].marker && s.current === 1);
s = pos({ hands: [[[12, 12]], [[4, 9]]], hub: 11, trains: { 0: [[11, 12]] } });
s = play(s, 12, 12, '0');
ok('going out on a double ends the round', s.phase !== 'playing' && s.roundWinner === 0 && s.stats[0].outs === 1);
}
section('One tile per turn (default) and the first-turn run (house rule)');
{
ok('default: no first-turn run', L.DEFAULT_OPTS.opening === false);
let s = pos({ hands: [[[12, 3], [3, 7], [7, 1]], [[4, 9]]], firstDone: false });
s = play(s, 12, 3, '0');
ok('default: one tile and the turn passes', s.current === 1 && s.trains['0'].tiles.length === 1);
s = pos({ hands: [[[12, 3], [3, 7], [7, 7], [7, 1], [12, 9]], [[4, 9]]], firstDone: false, opts: { opening: true } });
ok('run: first turn is own train only (no Mexican Train)', mv(s).every((m) => m.endsWith('@0')), mv(s).join());
s = play(s, 12, 3, '0');
ok('run: playing your own train keeps the turn', s.current === 0 && s.turn.run && L.canEndTurn(s));
s = play(s, 3, 7, '0'); s = play(s, 7, 7, '0');
ok('run: a double inside the run is just part of the chain', !s.openDouble && L.canEndTurn(s));
s = play(s, 7, 1, '0');
s = L.endTurn(s);
ok('run: End Turn passes play', s.current === 1 && s.firstDone[0] && s.trains['0'].tiles.length === 4);
s = pos({ n: 2, hands: [[[12, 5], [5, 5], [1, 2]], [[2, 9], [5, 8], [12, 4]]], firstDone: false, opts: { opening: true } });
s = play(s, 12, 5, '0'); s = play(s, 5, 5, '0'); s = L.endTurn(s);
ok('run ending on a double: not enforced during first turns', !s.openDouble && s.deferred.length === 1 && mv(s).join() === '4-12@1', mv(s).join());
s = play(s, 12, 4, '1'); s = L.endTurn(s);
ok('…enforced once everyone has had a first turn', s.current === 0 && s.openDouble?.value === 5 && s.openDouble.train === '0');
s = pos({ hands: [[[1, 2]], [[4, 9]]], firstDone: false, opts: { opening: true } });
ok('run: can\'t start → no draw, the train is marked', !L.canDraw(s) && L.canPass(s));
s = L.passTurn(s);
ok('…marked open', s.trains['0'].marker && s.current === 1);
}
section('Dead doubles');
{
// every other 6 is already on the table, so a 6-6 needs no cover
let s = pos({
set: 6, hub: 5, hands: [[[6, 6], [0, 0]], [[1, 1]]],
trains: { 0: [[5, 6]], mexican: [[5, 4], [4, 6], [6, 0]], 1: [[5, 3], [3, 6], [6, 1], [1, 2], [2, 6]] },
});
ok('setup: the 6-6 is the only 6 still unplayed', !L.numberLive({ ...s, players: s.players.map((p, i) => (i ? p : { ...p, hand: p.hand.filter((t) => !(t.a === 6 && t.b === 6)) })) }, 6));
const after = play(s, 6, 6, '0');
ok('a dead double needs no cover: the turn passes', after.current === 1 && !after.openDouble && after.lastEvent.dead);
let t = pos({ hands: [[[12, 12], [1, 2]], [[12, 7]]], hub: 11, trains: { 0: [[11, 12]] } });
t = play(t, 12, 12, '0');
ok('a live double still has to be covered', t.current === 0 && t.openDouble?.value === 12);
}
section('Round end, scoring, match');
{
let s = pos({ hands: [[[1, 2]], [[0, 0], [3, 4]]], boneyard: [], opts: { blank50: true } });
s = L.passTurn(s); s = L.passTurn(s);
ok('blocked round ends when everyone passes on an empty boneyard', s.phase !== 'playing' && s.blocked);
ok('blocked: fewest pips wins the round', s.roundWinner === 0);
ok('0-0 counts 50 with the house rule', s.lastRoundScores[1] === 57, String(s.lastRoundScores));
ok('history is kept', s.history.length === 1 && s.history[0].totals[1] === 57);
let g = L.createInitialState({ playerNames: names(2), opts: { set: 6 }, seed: 9 });
const rnd = mulberry32(5);
let guard = 0, rounds = 0;
while (g.phase !== 'gameover' && guard++ < 20000) {
if (g.phase === 'roundover') { const st = g.roundStarter; g = L.startNextRound(g); rounds++; if (g.roundStarter !== (st + 1) % 2) ok('starter rotates', false); continue; }
const a = AI.chooseAction(g, g.current, 3, rnd);
g = a.type === 'play' ? L.playTile(g, a) : a.type === 'draw' ? L.drawTile(g) : a.type === 'pass' ? L.passTurn(g) : L.endTurn(g);
}
ok('descent: exactly one round per engine (d6 → 7)', g.history.length === 7 && g.history.map((h) => h.hub).join() === '6,5,4,3,2,1,0', g.history.map((h) => h.hub).join());
g = L.createInitialState({ playerNames: names(3), opts: { set: 6, mode: 'points', target: 60 }, seed: 4 });
guard = 0;
while (g.phase !== 'gameover' && guard++ < 40000) {
if (g.phase === 'roundover') { g = L.startNextRound(g); continue; }
const a = AI.chooseAction(g, g.current, 3, rnd);
g = a.type === 'play' ? L.playTile(g, a) : a.type === 'draw' ? L.drawTile(g) : a.type === 'pass' ? L.passTurn(g) : L.endTurn(g);
}
ok('points: ends once someone reaches the target', g.phase === 'gameover' && g.players.some((p) => p.score >= 60) && g.history.slice(0, -1).every((h) => h.totals.every((t) => t < 60)));
ok('winners = lowest total', L.getWinners(g).every((i) => g.players[i].score === Math.min(...g.players.map((p) => p.score))));
const tie = { players: [{ score: 40 }, { score: 40 }, { score: 55 }], history: [{ scores: [20, 0, 30] }, { scores: [20, 40, 25] }] };
ok('tie on total → most 0-point rounds wins', L.getWinners(tie).join() === '1' && L.rankings(tie).join() === '1,0,2');
const tie2 = { players: [{ score: 30 }, { score: 30 }], history: [{ scores: [10, 18] }, { scores: [20, 12] }] };
ok('…then the lowest non-zero round', L.getWinners(tie2).join() === '0');
}
section('Knocking');
{
let s = pos({ hands: [[[12, 3], [5, 6]], [[1, 1], [2, 2]]], opts: { knock: true } });
s = play(s, 12, 3, '0');
ok('down to one without knocking → catchable', L.catchable(s, 0));
const c = L.catchKnock(s, 1, 0);
ok('caught: draw two', c.players[0].hand.length === 3 && c.stats[0].caught === 1 && !L.catchable(c, 0));
const k = L.knock(s, 0);
ok('knocked → safe', !L.catchable(k, 0) && k.players[0].knocked);
ok('no knock rule → never catchable', !L.catchable(play(pos({ hands: [[[12, 3], [5, 6]], [[1, 1]]] }), 12, 3, '0'), 0));
}
section('AI: chain search, hints');
{
const brute = (hand, v) => {
let best = 0;
const rec = (val, used, len) => {
best = Math.max(best, len);
hand.forEach((t, i) => { if (used & (1 << i)) return; if (t.a === val) rec(t.b, used | (1 << i), len + 1); else if (t.b === val) rec(t.a, used | (1 << i), len + 1); });
};
rec(v, 0, 0);
return best;
};
const rnd = mulberry32(77);
const all = L.makeTileSet(9);
let agree = 0;
for (let k = 0; k < 300; k++) {
const hand = all.slice().sort(() => rnd() - 0.5).slice(0, 9);
const v = Math.floor(rnd() * 10);
if (AI.bestChain(hand, v).path.length === brute(hand, v)) agree++;
}
ok('bestChain = brute-force longest trail (300 hands)', agree === 300, `${agree}/300`);
const ch = AI.bestChain([T(12, 3), T(3, 3), T(3, 9), T(9, 1), T(5, 6)], 12);
ok('chain takes the double on the way', ch.path.map((p) => `${p.left}${p.right}`).join(' ') === '123 33 39 91', ch.path.map((p) => `${p.left}${p.right}`).join(' '));
let hintOk = 0, hints = 0;
let g = L.createInitialState({ playerNames: names(3), opts: { set: 12 }, seed: 31 });
for (let i = 0; i < 400 && g.phase === 'playing'; i++) {
const h = AI.hint(g, g.current);
hints++;
if (h && (h.action.type !== 'play' || L.getLegalMoves(g).some((m) => m.tileId === h.action.tileId && m.train === h.action.train)) && h.text.length > 10) hintOk++;
const a = AI.chooseAction(g, g.current, 4, rnd);
g = a.type === 'play' ? L.playTile(g, a) : a.type === 'draw' ? L.drawTile(g) : a.type === 'pass' ? L.passTurn(g) : L.endTurn(g);
}
ok('hints are legal and explained', hintOk === hints, `${hintOk}/${hints}`);
}
// ── soak ─────────────────────────────────────────────────────────────────────
function applyA(g, a) { return a.type === 'play' ? L.playTile(g, a) : a.type === 'draw' ? L.drawTile(g) : a.type === 'pass' ? L.passTurn(g) : L.endTurn(g); }
function playGame({ n, set, skills, opts = {}, seed, onState = null }) {
const rnd = mulberry32(seed * 7 + 1);
let g = L.createInitialState({ playerNames: names(n), opts: { set, ...opts }, seed });
let guard = 0, problems = [];
while (g.phase !== 'gameover' && guard++ < 60000) {
if (g.phase === 'roundover') { g = L.startNextRound(g); continue; }
const a = AI.chooseAction(g, g.current, skills[g.current], rnd);
if (!a) { problems.push('no action'); break; }
const next = applyA(g, a);
if (next === g) { problems.push(`no-op ${a.type}`); break; }
g = next;
if (g.opts.knock && L.catchable(g, (g.current + g.n - 1) % g.n) && rnd() < 0.3) g = L.catchKnock(g, g.current, (g.current + g.n - 1) % g.n);
const c = L.tileCensus(g);
if (c.total !== c.expected || c.unique !== c.expected) { problems.push('census'); break; }
onState?.(g, a);
}
if (g.phase !== 'gameover') problems.push('unfinished');
return { g, problems };
}
section('AI soak');
{
const games = QUICK ? 24 : 90;
let bad = 0, rounds = 0;
for (let k = 0; k < games; k++) {
const n = 2 + (k % 3), set = [12, 9, 6][Math.floor(k / 3) % 3];
const opts = { opening: k % 4 !== 1, doubles: k % 5 === 2 ? 'relaxed' : 'cover', blank50: k % 2 === 1, knock: k % 3 === 0, ...(k % 7 === 6 ? { mode: 'points', target: 150 } : {}) };
const skills = Array.from({ length: n }, (_, i) => 1 + ((k + i) % 5));
const { g, problems } = playGame({ n, set, skills, opts, seed: 900 + k });
rounds += g.history.length;
if (problems.length) { bad++; console.error(` soak ${k}: ${problems.join(', ')}`); }
}
ok(`${games} games across sets / players / house rules finish cleanly`, bad === 0, `${bad} bad`);
console.log(` (${rounds} rounds played)`);
}
section('Skill ladder (2 players, mirrored seeds, double-12)');
{
const pairs = QUICK ? 10 : 40;
const ladder = QUICK ? [[2, 1], [5, 3]] : [[2, 1], [3, 2], [4, 3], [5, 4]];
for (const [hi, lo] of ladder) {
let w = 0, cnt = 0, margin = 0;
for (let k = 0; k < pairs; k++) {
for (const order of [[hi, lo], [lo, hi]]) {
const { g } = playGame({ n: 2, set: 12, skills: order, seed: 4000 + k });
const me = order[0] === hi ? 0 : 1, you = 1 - me;
const a = g.players[me].score, b = g.players[you].score;
w += a < b ? 1 : a === b ? 0.5 : 0;
margin += b - a;
cnt++;
}
}
const pct = (100 * w) / cnt;
console.log(` skill ${hi} vs ${lo}: ${pct.toFixed(1)}% wins, avg margin ${(margin / cnt).toFixed(1)} (${cnt} games)`);
// lowest total wins, so the average margin is the steadier signal (win % swings ±10 at this sample size)
ok(`skill ${hi} beats skill ${lo} on average score`, margin / cnt > 0, `${(margin / cnt).toFixed(1)} pts, ${pct.toFixed(1)}%`);
}
}
section('Layout');
{
const corners = (p, z, pad = 0) => {
const hw = Lay.TILE.u * z + pad, hh = (Lay.TILE.u * z) / 2 + pad, c = Math.cos(p.rot), s = Math.sin(p.rot);
return [[1, 1], [1, -1], [-1, -1], [-1, 1]].map(([i, j]) => ({ x: p.x + c * hw * i - s * hh * j, y: p.y + s * hw * i + c * hh * j }));
};
const overlap = (A, B) => {
for (const P of [A, B]) for (let i = 0; i < 4; i++) {
const a = P[i], b = P[(i + 1) % 4], nx = -(b.y - a.y), ny = b.x - a.x, len = Math.hypot(nx, ny);
const pa = A.map((q) => q.x * nx + q.y * ny), pb = B.map((q) => q.x * nx + q.y * ny);
if (Math.max(...pa) < Math.min(...pb) + 0.5 * len || Math.max(...pb) < Math.min(...pa) + 0.5 * len) return false;
}
return true;
};
for (const n of [2, 3, 4]) {
let checks = 0, overlaps = 0, outside = 0, hub = 0, minZoom = 1, markerHits = 0, links = 0, breaks = 0, bends = 0;
const games = QUICK ? 3 : 10;
for (let k = 0; k < games; k++) {
let zoom = 1, step = 0;
playGame({ n, set: 12, skills: Array(n).fill(3), seed: 7000 + k * 3 + n, onState: (g, a) => {
if (g.phase === 'playing' && g.lastEvent.type === 'deal') zoom = 1;
if (a.type !== 'play' || (++step % 5 && g.phase === 'playing')) return;
zoom = Lay.fitZoom(n, g.trains, zoom);
minZoom = Math.min(minZoom, zoom);
const all = Lay.layoutAll(n, g.trains, zoom);
const boxes = [];
for (const [key, r] of Object.entries(all.trains)) r.poses.forEach((p) => boxes.push({ key, p, c: corners(p, zoom) }));
// a contiguous train: every tile touches the one before it (within the tile gap), bends included
for (const r of Object.values(all.trains)) for (let i = 1; i < r.poses.length; i++) {
links++;
if (r.poses[i].corner) bends++;
const pad = (Lay.TILE.gap * zoom) / 2 + 0.6;
if (!overlap(corners(r.poses[i - 1], zoom, pad), corners(r.poses[i], zoom, pad))) breaks++;
}
for (const b of boxes) {
if (b.c.some((q) => q.x < Lay.TABLE.l - 2 || q.x > Lay.TABLE.r + 2 || q.y < Lay.TABLE.t - 2 || q.y > Lay.TABLE.b + 2)) outside++;
if (Math.hypot(b.p.x - Lay.HUB.x, b.p.y - Lay.HUB.y) < Lay.HUB.r + 10) hub++;
}
for (let i = 0; i < boxes.length; i++) for (let j = i + 1; j < boxes.length; j++) { checks++; if (overlap(boxes[i].c, boxes[j].c)) overlaps++; }
for (const key of L.trainKeys(n)) {
const m = Lay.markerSpot(n, key);
const hl = Lay.MARKER.len / 2, hw = Lay.MARKER.wid / 2;
const mc = [[-hl, -hw], [hl, -hw], [hl, hw], [-hl, hw]].map(([dx, dy]) => ({ x: m.x + dx * Math.cos(m.rot) - dy * Math.sin(m.rot), y: m.y + dx * Math.sin(m.rot) + dy * Math.cos(m.rot) }));
for (const b of boxes) if (b.key !== key && overlap(mc, b.c)) markerHits++;
}
} });
}
ok(`${n}p: no two tiles overlap (${checks} pairs)`, overlaps === 0, `${overlaps}`);
ok(`${n}p: every tile on the table, clear of the hub`, outside === 0 && hub === 0, `${outside} outside, ${hub} on the hub`);
ok(`${n}p: open-train engines don't sit on other trains`, markerHits === 0, `${markerHits}`);
ok(`${n}p: trains are unbroken — every tile touches the last, round the bends too (${links} links, ${bends} bends)`, breaks === 0 && bends > 0, `${breaks} breaks`);
console.log(` ${n}p: smallest zoom ${minZoom}`);
}
// furniture
const inter = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
for (const n of [2, 3, 4]) {
const f = Lay.hudFurniture(n);
let hits = [];
for (let i = 0; i < f.length; i++) for (let j = i + 1; j < f.length; j++) if (inter(f[i][1], f[j][1])) hits.push(`${f[i][0]}×${f[j][0]}`);
ok(`${n}p: HUD furniture doesn't overlap`, hits.length === 0, hits.join(' '));
const table = { x: Lay.TABLE.l, y: Lay.TABLE.t, w: Lay.TABLE.r - Lay.TABLE.l, h: Lay.TABLE.b - Lay.TABLE.t };
const onTable = f.filter(([, r]) => inter(r, table)).map(([k]) => k);
ok(`${n}p: HUD furniture stays off the train area`, onTable.length === 0, onTable.join(' '));
for (const p of f) ok(`${n}p: ${p[0]} on screen`, p[1].x >= 0 && p[1].y >= 0 && p[1].x + p[1].w <= Lay.W && p[1].y + p[1].h <= Lay.H);
}
const rs = Lay.rackSlots(25);
ok('a 25-tile rack fits on the rack', rs.xs[0] - Lay.RACK_TILE.u / 2 >= Lay.RACK.x && rs.xs[24] + Lay.RACK_TILE.u / 2 <= Lay.RACK.x + Lay.RACK.w);
ok('rack hit-test round-trips', [0, 7, 14].every((i) => Lay.rackIndexAt(Lay.rackSlots(15).xs[i], 15) === i));
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);