fertig-classic-games/tools/verifyPhase10.js

434 lines
25 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
// verifyPhase10.js — headless checks for Phase 10: rules (laydowns, run order,
// hits incl. wild bounds, skips, scoring, match end + tie round), the live
// staging helpers, the AI (always legal, skill-scaled timing, advice), the
// table layout for 2/3/4 players (everything on screen and on the table, mats /
// hands / plates / HUD clear of each other, hit-test round trips), and an
// all-AI soak (every round ends, cards are conserved, higher skill wins more).
// Usage: node tools/verifyPhase10.js [--quick]
import {
createInitialState, buildDeck, applyDrawFromDeck, applyDrawFromDiscard, applyLaydown, applyHit,
applyDiscard, canHit, runAssignedValues, getHitTargets, startNextRound, cardPoints, handPoints,
orderGroupCards, skipTargets, discardTop, cloneState,
} from '../src/games/phase10/Phase10Logic.js';
import {
PHASES, getPhase, validateLaydown, groupStatus, laidGroupLabel, groupGoalLabel, cardName,
} from '../src/games/phase10/PhaseSpec.js';
import { chooseAction, findLaydown, adviseHand, aiTiming, HAND_SPEED, PACE } from '../src/games/phase10/Phase10AI.js';
import {
W, H, CARD_W, CARD_H, SQ, PLATE, TOP_BUTTONS, DOCK, SORT_ROW, KEYS_BOX, layoutFor, handPose, handHit, handInsertIndex,
handZone, handBadge, handHome, groupAreas, groupCardPose, groupRect, areaRect, inRect, inPose, cardBounds,
deckTopPose, discardPose, plateRect, matCorners, onFelt, rectsOverlap, centreRect, spotFor,
} from '../src/games/phase10/Phase10Table.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 nextId = 1000;
const C = (value, color = 'red') => ({ value, color: value === 'wild' || value === 'skip' ? null : color, id: nextId++ });
const Wd = () => C('wild');
const Sk = () => C('skip');
// Put a hand + phase on seat `seat` and make it that seat's post-draw turn.
function rig(gs, seat, hand, phase = 1) {
gs.players[seat].hand = hand;
gs.players[seat].phase = phase;
gs.currentPlayer = seat;
gs.drawnThisTurn = true;
gs.laidDownThisTurn = false;
return gs;
}
function apply(gs, a) {
if (a.type === 'drawDeck') return applyDrawFromDeck(gs);
if (a.type === 'drawDiscard') return applyDrawFromDiscard(gs);
if (a.type === 'laydown') return applyLaydown(gs, a.groups);
if (a.type === 'hit') return applyHit(gs, a.handIdx, a.targetSeat, a.groupIdx, a.position);
return applyDiscard(gs, a.handIdx, a.skipTargetSeat ?? null);
}
const countCards = (gs) => gs.drawPile.length + gs.discardPile.length
+ gs.players.reduce((n, p) => n + p.hand.length + (p.laidDown ? p.laidDown.reduce((m, g) => m + g.cards.length, 0) : 0), 0);
// ── Rules ────────────────────────────────────────────────────────────────────
section('Rules');
{
const deck = buildDeck();
ok('108-card deck', deck.length === 108);
ok('8 wilds + 4 skips', deck.filter(c => c.value === 'wild').length === 8 && deck.filter(c => c.value === 'skip').length === 4);
ok('2 of each colour/value', [1, 6, 12].every(v => ['red', 'blue', 'yellow', 'green'].every(col => deck.filter(c => c.value === v && c.color === col).length === 2)));
ok('unique ids', new Set(deck.map(c => c.id)).size === 108);
for (const n of [2, 3, 4]) {
const gs = createInitialState({ playerCount: n, seed: 7 });
ok(`${n}p: 10 cards each`, gs.players.every(p => p.hand.length === 10));
ok(`${n}p: one card turned up`, gs.discardPile.length === 1);
ok(`${n}p: conserves 108`, countCards(gs) === 108);
ok(`${n}p: takes log empty`, Array.isArray(gs.takes) && gs.takes.length === 0);
}
ok('points: 5 / 10 / 15 / 25', cardPoints(C(9)) === 5 && cardPoints(C(10)) === 10 && cardPoints(Sk()) === 15 && cardPoints(Wd()) === 25);
ok('handPoints sums', handPoints([C(1), C(12), Wd()]) === 40);
}
{
const gs = createInitialState({ playerCount: 2, seed: 3 });
gs.discardPile.push(Sk());
ok('cannot take a Skip from the discard', applyDrawFromDiscard(gs) === gs);
gs.discardPile.push(C(7, 'blue'));
const next = applyDrawFromDiscard(gs);
ok('taking a discard logs it', next.takes.length === 1 && next.takes[0].seat === 0 && next.takes[0].value === 7 && next.takes[0].color === 'blue');
ok('takes survive a clone', cloneState(next).takes.length === 1);
ok('cannot draw twice', applyDrawFromDeck(next) === next);
}
{
// laydown validation per phase
const v = (ph, groups) => validateLaydown(ph, groups).ok;
ok('phase 1: two sets of 3', v(1, [{ kind: 'set', cards: [C(4), C(4, 'blue'), Wd()] }, { kind: 'set', cards: [C(9), C(9), C(9, 'green')] }]));
ok('phase 1: mismatched set rejected', !v(1, [{ kind: 'set', cards: [C(4), C(5), Wd()] }, { kind: 'set', cards: [C(9), C(9), C(9)] }]));
ok('phase 4: run of 7 any order', v(4, [{ kind: 'run', cards: [C(7), C(3), Wd(), C(5), C(6), C(4), C(8)] }]));
ok('phase 4: run past 12 rejected', !v(4, [{ kind: 'run', cards: [C(7), C(8), C(9), C(10), C(11), C(12), Wd()].slice(0, 6).concat([C(6)]).map((c, i) => (i === 6 ? C(12) : c)) }]));
ok('phase 8: 7 of one colour', v(8, [{ kind: 'color', cards: [C(1, 'blue'), C(3, 'blue'), C(3, 'blue'), C(9, 'blue'), C(11, 'blue'), Wd(), C(12, 'blue')] }]));
ok('phase 8: mixed colours rejected', !v(8, [{ kind: 'color', cards: [C(1, 'blue'), C(3, 'red'), C(3, 'blue'), C(9, 'blue'), C(11, 'blue'), Wd(), C(12, 'blue')] }]));
ok('all-wild laydown rejected', !v(9, [{ kind: 'set', cards: [Wd(), Wd(), Wd(), Wd(), Wd()] }, { kind: 'set', cards: [Wd(), Wd()] }]));
ok('skip in a laydown rejected', !v(1, [{ kind: 'set', cards: [C(4), C(4), Sk()] }, { kind: 'set', cards: [C(9), C(9), C(9)] }]));
}
{
// run order normalisation → hits work after an out-of-order laydown
const gs = createInitialState({ playerCount: 2, seed: 11 });
const run = [C(6), Wd(), C(3), C(4)]; // 3 4 5(W) 6
const set = [C(10), C(10, 'blue'), C(10, 'green')];
rig(gs, 0, [...run, ...set, C(2), C(7, 'blue'), C(12)], 2);
const next = applyLaydown(gs, [{ kind: 'set', cardIds: set.map(c => c.id) }, { kind: 'run', cardIds: run.map(c => c.id) }]);
ok('out-of-order run lays down', next !== gs);
const laidRun = next.players[0].laidDown.find(g => g.kind === 'run');
const vals = runAssignedValues(laidRun);
ok('run stored in position order', vals && vals.join(',') === '3,4,5,6', vals?.join(','));
ok('wild fills the 5', laidRun.cards[2].value === 'wild');
const gi = next.players[0].laidDown.indexOf(laidRun);
const tHigh = getHitTargets(next, next.players[0].hand.find(c => c.value === 7));
ok('7 hits the high end', tHigh.some(t => t.groupIdx === gi && t.position === 'high'));
const tLow = getHitTargets(next, next.players[0].hand.find(c => c.value === 2));
ok('2 hits the low end', tLow.some(t => t.groupIdx === gi && t.position === 'low'));
ok('12 hits nothing', getHitTargets(next, next.players[0].hand.find(c => c.value === 12)).length === 0);
ok('orderGroupCards: leftover wild goes high', orderGroupCards('run', [C(2), C(3), Wd()]).map(c => c.value).join() === '2,3,wild');
ok('orderGroupCards: wild goes low at the top', orderGroupCards('run', [C(11), C(12), Wd()]).map(c => c.value).join() === 'wild,11,12');
ok('orderGroupCards: set naturals first', orderGroupCards('set', [Wd(), C(5), C(5)]).map(c => c.value).join() === '5,5,wild');
}
{
// wild hits respect 1..12
const top = { kind: 'run', cards: [C(9), C(10), C(11), C(12)] };
ok('wild cannot extend past 12', !canHit(top, Wd(), 'high') && canHit(top, Wd(), 'low'));
const bottom = { kind: 'run', cards: [C(1), C(2), C(3)] };
ok('wild cannot extend below 1', !canHit(bottom, Wd(), 'low') && canHit(bottom, Wd(), 'high'));
ok('set takes matching or wild', canHit({ kind: 'set', cards: [C(5), C(5)] }, C(5, 'green')) && canHit({ kind: 'set', cards: [C(5), C(5)] }, Wd()) && !canHit({ kind: 'set', cards: [C(5), C(5)] }, C(6)));
ok('colour takes matching colour', canHit({ kind: 'color', cards: [C(1, 'blue')] }, C(9, 'blue')) && !canHit({ kind: 'color', cards: [C(1, 'blue')] }, C(9, 'red')));
ok('skips never hit', !canHit({ kind: 'set', cards: [C(5)] }, Sk()));
}
{
// skips
const gs = createInitialState({ playerCount: 2, seed: 5 });
const sk = Sk();
rig(gs, 0, [sk, C(3), C(4)]);
ok('skip needs a target while one exists', applyDiscard(gs, 0, null) === gs);
const next = applyDiscard(gs, 0, 1);
ok('2p skip: you go again', next.currentPlayer === 0 && !next.players[1].skipped);
const g3 = createInitialState({ playerCount: 3, seed: 5 });
rig(g3, 0, [Sk(), C(3), C(4)]);
const n3 = applyDiscard(g3, 0, 2);
ok('3p skip flags the target', n3.players[2].skipped && n3.currentPlayer === 1);
const n3b = rig(n3, 1, [Sk(), C(8)]);
ok('cannot skip an already-skipped seat', applyDiscard(n3b, 0, 2) === n3b);
ok('skipTargets excludes flagged + self', skipTargets(n3b, 1).join() === '0');
const n3c = applyDiscard(n3b, 0, 0);
ok('both others skipped → turn comes back around', n3c.currentPlayer === 1 && !n3c.players[0].skipped && !n3c.players[2].skipped);
// nobody skippable: a lone Skip may still be thrown
const g4 = createInitialState({ playerCount: 3, seed: 9 });
g4.players[1].skipped = true; g4.players[2].skipped = true;
rig(g4, 0, [Sk(), C(5)]);
const n4 = applyDiscard(g4, 0, null);
ok('skip with no valid target still discards', n4 !== g4 && discardTop(n4).value === 'skip');
}
{
// scoring, phase advance, match end, tie round
const gs = createInitialState({ playerCount: 2, seed: 21 });
const set1 = [C(4), C(4), C(4)], set2 = [C(8), C(8), C(8)];
rig(gs, 0, [...set1, ...set2, C(2)], 1);
let s = applyLaydown(gs, [{ kind: 'set', cardIds: set1.map(c => c.id) }, { kind: 'set', cardIds: set2.map(c => c.id) }]);
s.players[1].hand = [C(10), Wd(), C(3)];
s = applyDiscard(s, 0);
ok('going out ends the round', s.roundPhase === 'roundOver' && s.roundWinner === 0);
ok('loser scores their hand', s.players[1].score === 40 && s.players[0].score === 0);
ok('laid-down player advances', s.players[0].phase === 2 && s.players[1].phase === 1);
const r2 = startNextRound(s);
ok('next round deals fresh', r2.roundNum === 2 && r2.players.every(p => p.hand.length === 10 && !p.laidDown) && countCards(r2) === 108);
ok('next round: winner+1 starts', r2.currentPlayer === 1);
ok('takes reset each round', r2.takes.length === 0);
const end = createInitialState({ playerCount: 2, seed: 4 });
const a = [C(6), C(6), C(6), C(6), C(6)], b = [C(2), C(2), C(2)];
rig(end, 0, [...a, ...b, C(9)], 10);
end.players[1].phase = 10; end.players[1].clearedAt = null; end.players[1].hand = [C(1)];
let e = applyLaydown(end, [{ kind: 'set', cardIds: a.map(c => c.id) }, { kind: 'set', cardIds: b.map(c => c.id) }]);
e = applyDiscard(e, 0);
ok('clearing phase 10 ends the match', e.roundPhase === 'gameOver' && e.matchWinner === 0);
const tie = createInitialState({ playerCount: 2, seed: 4 });
const ta = [C(6), C(6), C(6), C(6), C(6)], tb = [C(2), C(2), C(2)];
rig(tie, 0, [...ta, ...tb, C(9)], 10);
tie.players[1].phase = 10; tie.players[1].clearedAt = 3; tie.players[1].score = 0;
tie.players[1].hand = [];
let t = applyLaydown(tie, [{ kind: 'set', cardIds: ta.map(c => c.id) }, { kind: 'set', cardIds: tb.map(c => c.id) }]);
t = applyDiscard(t, 0);
ok('tied finishers play another round', t.roundPhase === 'roundOver' && t.matchTied && t.matchWinner === null);
}
// ── Staging helpers ──────────────────────────────────────────────────────────
section('Staging helpers');
{
ok('empty group shows its goal', groupStatus('set', 3, []).text === 'Set of 3');
ok('partial set coaches', /needs 1 more 7/.test(groupStatus('set', 3, [C(7), C(7)]).text));
ok('wrong set value flagged', !groupStatus('set', 3, [C(7), C(8)]).valid);
ok('partial run with a gap is fine', groupStatus('run', 4, [C(3), C(5)]).valid);
ok('spread-out run flagged', !groupStatus('run', 4, [C(3), C(9)]).valid);
ok('repeat in a run flagged', !groupStatus('run', 4, [C(3), C(3)]).valid);
ok('run that cannot fit 1..12 flagged', !groupStatus('run', 9, [C(12), C(5)]).valid || !groupStatus('run', 9, [C(12), C(5)]).ok);
ok('complete run ok', groupStatus('run', 4, [C(5), Wd(), C(3), C(6)]).ok);
ok('skip never valid', !groupStatus('set', 3, [Sk()]).valid);
ok('colour coaching names the colour', /Blue/.test(groupStatus('color', 7, [C(2, 'blue')]).text));
ok('laid run label', laidGroupLabel({ kind: 'run', cards: [C(3), C(4)] }, [3, 4]) === 'Run 3–4');
ok('laid set label', laidGroupLabel({ kind: 'set', cards: [C(7), Wd()] }) === 'Set of 7s · 2');
ok('goal labels', groupGoalLabel('color', 7) === '7 of one color' && groupGoalLabel('run', 9) === 'Run of 9');
ok('card names', cardName(C(7, 'blue')) === 'Blue 7' && cardName(Wd()) === 'Wild' && cardName(Sk()) === 'Skip');
}
// ── AI ───────────────────────────────────────────────────────────────────────
section('AI');
{
ok('hand speeds as set for Nerts', HAND_SPEED[1] === 0.25 && HAND_SPEED[2] === 0.3 && HAND_SPEED[3] === 0.5 && HAND_SPEED[4] === 0.8 && HAND_SPEED[5] === 1);
let mono = true;
for (let k = 1; k < 5; k++) {
const a = aiTiming(k), b = aiTiming(k + 1);
if (!(a.reach > b.reach && a.carry > b.carry && a.think >= b.think)) mono = false;
}
ok('lower skill = slower hands', mono);
ok('pace scales timing', aiTiming(3, PACE.fast).carry < aiTiming(3, PACE.normal).carry && aiTiming(3, PACE.relaxed).carry > aiTiming(3).carry);
ok('skill 3 carry is half of skill 5', Math.abs(aiTiming(3).carry - 2 * aiTiming(5).carry) <= 1);
ok('even skill 1 turns stay reasonable', aiTiming(1).reach + aiTiming(1).carry < 2000);
// findLaydown always returns a legal laydown
let bad = 0, found = 0;
const trials = QUICK ? 400 : 2000;
for (let i = 0; i < trials; i++) {
const gs = createInitialState({ playerCount: 2, seed: 1000 + i });
const hand = [...gs.players[0].hand, gs.drawPile.pop(), gs.drawPile.pop(), gs.drawPile.pop()];
const phase = 1 + (i % 10);
const lay = findLaydown(hand, phase);
if (lay) {
found++;
if (!validateLaydown(phase, lay).ok) bad++;
const ids = lay.flatMap(g => g.cards.map(c => c.id));
if (new Set(ids).size !== ids.length) bad++;
}
}
ok('findLaydown results are legal', bad === 0, `${bad} bad of ${found}`);
ok('findLaydown finds some', found > trials * 0.05, `${found}/${trials}`);
// adviseHand
const gs = createInitialState({ playerCount: 2, seed: 77 });
const s1 = [C(4), C(4), C(4)], s2 = [C(9), C(9), Wd()];
rig(gs, 0, [...s1, ...s2, C(1), C(12, 'blue'), C(7, 'green'), C(2)], 1);
const adv = adviseHand(gs, 0);
ok('advice spots a laydown', !!adv.laydown);
ok('advice keeps the phase cards', [...s1, ...s2].every(c => adv.keepers.has(c.id)));
ok('advice never tosses a phase card or wild', adv.discardId != null && ![...s1, ...s2].some(c => c.id === adv.discardId));
}
// ── Layout ───────────────────────────────────────────────────────────────────
section('Layout');
const onScreen = (b, m = 0) => b.x0 >= -m && b.x1 <= W + m && b.y0 >= -m && b.y1 <= H + m;
for (const n of [2, 3, 4]) {
const L = layoutFor(n);
const furniture = [];
for (let s = 0; s < n; s++) furniture.push({ name: `plate ${s}`, r: plateRect(L, s) });
TOP_BUTTONS.forEach(b => furniture.push({ name: `button ${b.label}`, r: centreRect(b) }));
furniture.push({ name: 'dock', r: DOCK });
SORT_ROW.xs.forEach((x, i) => furniture.push({ name: `sort ${i}`, r: centreRect({ x, y: SORT_ROW.y, w: SORT_ROW.w, h: SORT_ROW.h }) }));
furniture.push({ name: 'keys line', r: KEYS_BOX });
// furniture vs furniture
for (let i = 0; i < furniture.length; i++) {
for (let j = i + 1; j < furniture.length; j++) {
ok(`${n}p: ${furniture[i].name} clear of ${furniture[j].name}`, !rectsOverlap(furniture[i].r, furniture[j].r));
}
}
const matBox = (s) => {
const c = matCorners(L, s, 10);
return { x0: Math.min(...c.map(p => p.x)), x1: Math.max(...c.map(p => p.x)), y0: Math.min(...c.map(p => p.y)), y1: Math.max(...c.map(p => p.y)) };
};
const handBox = (s, cards = 11) => {
let b = null;
for (let i = 0; i < cards; i++) {
const cb = cardBounds(handPose(L, s, i, cards, s === 0 ? 46 : 0));
b = b ? { x0: Math.min(b.x0, cb.x0), x1: Math.max(b.x1, cb.x1), y0: Math.min(b.y0, cb.y0), y1: Math.max(b.y1, cb.y1) } : cb;
}
return b;
};
const pileBox = (p) => cardBounds({ ...p, y: p.y - 14 });
const deckB = pileBox(L.deck), discB = pileBox(L.discard);
ok(`${n}p: deck and discard apart`, !rectsOverlap(deckB, discB));
for (let s = 0; s < n; s++) {
const mb = matBox(s);
ok(`${n}p seat ${s}: mat on the table`, matCorners(L, s, 10).every(p => onFelt(p)));
ok(`${n}p seat ${s}: mat clear of piles`, !rectsOverlap(mb, deckB) && !rectsOverlap(mb, discB));
for (let t = s + 1; t < n; t++) ok(`${n}p mats ${s}/${t} apart`, !rectsOverlap(mb, matBox(t)));
for (const f of furniture) ok(`${n}p seat ${s}: mat clear of ${f.name}`, !rectsOverlap(mb, f.r));
const hb = handBox(s);
ok(`${n}p seat ${s}: hand on screen`, onScreen(hb, s === 0 ? 40 : 6), JSON.stringify(hb));
for (let t = 0; t < n; t++) ok(`${n}p hand ${s} clear of mat ${t}`, !rectsOverlap(hb, matBox(t)), `${JSON.stringify(hb)} vs ${JSON.stringify(matBox(t))}`);
for (const f of furniture) ok(`${n}p hand ${s} clear of ${f.name}`, !rectsOverlap(hb, f.r), `${JSON.stringify(hb)} vs ${JSON.stringify(f.r)}`);
ok(`${n}p hand ${s} clear of piles`, !rectsOverlap(hb, deckB) && !rectsOverlap(hb, discB));
if (s > 0) {
const b = handBadge(L, s);
const br = { x0: b.x - 16, x1: b.x + 16, y0: b.y - 16, y1: b.y + 16 };
ok(`${n}p seat ${s}: badge on screen`, onScreen(br));
for (const f of furniture) ok(`${n}p seat ${s}: badge clear of ${f.name}`, !rectsOverlap(br, f.r));
const hh = handHome(L, s);
ok(`${n}p seat ${s}: ghost hand home on screen`, hh.x > 0 && hh.x < W && hh.y > 0 && hh.y < H);
}
// groups: long rows stay inside their area, cards on the felt, labels on screen
for (const gc of [1, 2]) {
const areas = groupAreas(L, s, gc);
for (let gi = 0; gi < gc; gi++) {
for (const len of [2, 5, 9, 12, 16]) {
const first = cardBounds(groupCardPose(L, s, gi, gc, 0, len));
const last = cardBounds(groupCardPose(L, s, gi, gc, len - 1, len));
const a = areas[gi];
ok(`${n}p seat ${s} g${gi}/${gc} len ${len}: inside area`, first.x0 >= a.x0 - 1 && last.x1 <= a.x1 + 1, `${first.x0.toFixed(0)}..${last.x1.toFixed(0)} vs ${a.x0.toFixed(0)}..${a.x1.toFixed(0)}`);
ok(`${n}p seat ${s} g${gi}/${gc} len ${len}: on felt`, onFelt({ x: first.x0, y: first.y0 }) && onFelt({ x: last.x1, y: last.y1 }));
}
const step12 = groupCardPose(L, s, gi, gc, 1, 12).x - groupCardPose(L, s, gi, gc, 0, 12).x;
ok(`${n}p seat ${s} g${gi}/${gc}: 12-card row stays readable`, step12 >= 18, step12.toFixed(1));
ok(`${n}p seat ${s} g${gi}/${gc}: label on the mat`, a0(areas[gi].labelY));
}
if (gc === 2) {
const r0 = areaRect(L, s, 0, 2, 0), r1 = areaRect(L, s, 1, 2, 0);
ok(`${n}p seat ${s}: two group areas apart`, !rectsOverlap(r0, r1));
}
}
const sp = spotFor(L, s);
ok(`${n}p seat ${s}: spotlight sized`, sp.w > 100 && sp.h > 100);
}
// human hand hit-tests round trip; insertion index is monotone
for (const cards of [1, 5, 10, 11]) {
let rt = true;
for (let i = 0; i < cards; i++) {
const p = handPose(L, 0, i, cards);
// aim at the visible left strip (later cards overlap the right side)
const pt = { x: p.x - CARD_W * 0.3, y: p.y - CARD_H * 0.3 };
if (handHit(L, cards, pt) !== i) rt = false;
}
ok(`${n}p: hand hit-test round trip (${cards})`, rt);
let monotone = true, prev = -1;
for (let x = 300; x <= 1620; x += 15) {
const k = handInsertIndex(L, cards, x);
if (k < prev) monotone = false;
prev = k;
}
ok(`${n}p: insert index monotone (${cards})`, monotone && handInsertIndex(L, cards, 0) === 0 && handInsertIndex(L, cards, W) === cards);
const z = handZone(L, cards);
ok(`${n}p: hand zone covers the fan (${cards})`, inRect(handPose(L, 0, 0, cards), z) && inRect(handPose(L, 0, cards - 1, cards), z));
}
ok(`${n}p: deck pose hit`, inPose(L.deck, deckTopPose(L, 80)) && inPose(L.discard, discardPose(L, 3, 4)));
// group rects cover their cards (hit targets)
for (let s = 0; s < n; s++) {
const r = groupRect(L, s, 1, 2, 7, 1, 10);
const p0 = groupCardPose(L, s, 1, 2, 0, 7), p6 = groupCardPose(L, s, 1, 2, 6, 7);
ok(`${n}p seat ${s}: group rect covers its cards`, inRect(p0, r) && inRect(p6, r));
}
}
function a0(y) { return y > 0 && y < H; }
void SQ; void PLATE;
// ── Soak ─────────────────────────────────────────────────────────────────────
section('Soak');
function playMatch(n, skills, seed, { maxRounds = 80 } = {}) {
let gs = createInitialState({ playerCount: n, seed });
let rounds = 0, turns = 0, noop = 0, conserve = true, stuck = false, loops = 0;
let rng = seed * 9301 + 49297;
const rand = () => { rng = (rng * 9301 + 49297) % 233280; return rng / 233280; };
while (gs.roundPhase !== 'gameOver' && rounds < maxRounds) {
let steps = 0;
while (gs.roundPhase === 'play' && steps < 3000) {
const a = chooseAction(gs, { skill: skills[gs.currentPlayer], rng: rand });
const next = apply(gs, a);
if (next === gs) {
noop++;
// the scene's safety net: discard the first card
const fb = applyDiscard(gs, 0, skipTargets(gs, gs.currentPlayer)[0] ?? null);
if (fb === gs) { stuck = true; break; }
gs = fb;
} else gs = next;
if (a.type === 'discard') turns++;
if (gs.takes?.length && gs.takes.filter(t => t.id === gs.takes[gs.takes.length - 1].id).length > 3) loops++;
if (countCards(gs) !== 108) conserve = false;
steps++;
}
if (stuck || gs.roundPhase === 'play') { stuck = true; break; }
rounds++;
if (gs.roundPhase === 'roundOver') gs = startNextRound(gs);
}
return { gs, rounds, turns, noop, conserve, stuck, loops, over: gs.roundPhase === 'gameOver' };
}
{
const N = QUICK ? 12 : 60;
for (const n of [2, 3, 4]) {
let ended = 0, noops = 0, conserved = true, stuck = 0, rounds = 0, scoreOk = true, loops = 0;
for (let i = 0; i < N; i++) {
const skills = Array.from({ length: n }, (_, s) => 1 + ((i + s * 2) % 5));
const r = playMatch(n, skills, 500 + i * 13 + n);
if (r.over) ended++;
noops += r.noop;
if (!r.conserve) conserved = false;
if (r.stuck) stuck++;
loops += r.loops;
rounds += r.rounds;
if (r.over) {
const w = r.gs.players[r.gs.matchWinner];
const fin = r.gs.players.filter(p => p.clearedAt != null);
if (!w || w.clearedAt == null || fin.some(p => p.score < w.score)) scoreOk = false;
}
}
ok(`${n}p soak: every match ends`, ended === N, `${ended}/${N}`);
ok(`${n}p soak: AI never plays an illegal action`, noops === 0, `${noops} no-ops`);
ok(`${n}p soak: 108 cards conserved`, conserved);
ok(`${n}p soak: no stuck rounds`, stuck === 0);
ok(`${n}p soak: no card passed around in a loop`, loops === 0, `${loops}`);
ok(`${n}p soak: winner is the lowest finisher`, scoreOk);
console.log(` ${n}p: ${N} matches, avg ${(rounds / N).toFixed(1)} rounds`);
}
// skill matters
const duel = (a, b, M) => {
let wa = 0;
for (let i = 0; i < M; i++) {
const seatA = i % 2;
const skills = seatA === 0 ? [a, b] : [b, a];
const r = playMatch(2, skills, 9000 + i * 7);
if (r.over && r.gs.matchWinner === seatA) wa++;
}
return wa / M;
};
const M = QUICK ? 40 : 160;
const r51 = duel(5, 1, M), r31 = duel(3, 1, M), r53 = duel(5, 3, M);
console.log(` win rates: skill 5 vs 1 ${(r51 * 100).toFixed(0)}%, 3 vs 1 ${(r31 * 100).toFixed(0)}%, 5 vs 3 ${(r53 * 100).toFixed(0)}%`);
// measured over 300 matches: 5v1 ≈ 84%, 3v1 ≈ 81%, 5v3 ≈ 60% (quick mode is noisier)
ok('skill 5 clearly beats skill 1', r51 >= (QUICK ? 0.65 : 0.72), `${(r51 * 100).toFixed(0)}%`);
ok('skill 3 beats skill 1', r31 >= (QUICK ? 0.6 : 0.68), `${(r31 * 100).toFixed(0)}%`);
ok('skill 5 beats skill 3', r53 >= (QUICK ? 0.42 : 0.52), `${(r53 * 100).toFixed(0)}%`);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);