438 lines
25 KiB
JavaScript
438 lines
25 KiB
JavaScript
#!/usr/bin/env node
|
||
// verifyNerts.js — headless checks for Nerts: rules, the table layout for
|
||
// 2/3/4 players (everything on screen, seats/foundations/furniture clear of
|
||
// each other, human hit-tests and drop snapping round-trip), and an AI soak
|
||
// where every seat is played by the AI (rounds must end, cards are conserved,
|
||
// scores add up). Usage: node tools/verifyNerts.js [--quick]
|
||
|
||
import {
|
||
createInitialState, canPlayOnFoundation, canPlayOnWork, playToFoundation, playToWork,
|
||
flipStock, endRound, allStuck, nertsTop, getValidPlays, validRunFromIndex, maxRunStart,
|
||
liveFoundationCounts, isFoundationComplete, rotateStocks, reshuffleAllStocks, rv,
|
||
NERTS_PILE_SIZE, WORK_PILE_COUNT, FOUNDATION_SUITS,
|
||
} from '../src/games/nerts/NertsLogic.js';
|
||
import {
|
||
chooseAction, reachDelay, carryDelay, handSpeed, HAND_SPEED, rankedPlays, PACE, PERCEPTION, planMove, createMind, noteOwnChange, noticeAt,
|
||
isUsefulPlay, usefulPlays,
|
||
} from '../src/games/nerts/NertsAI.js';
|
||
import {
|
||
W, H, CARD_W, CARD_H, layoutFor, cardPose, pileBase, foundationPose, cardBounds, cardCorners,
|
||
humanHit, dropTargetAt, targetPose, dragScale, fanStep, placematCorners, nertsBadge, seatHome,
|
||
dealSpot, SCORE_PAD, onTable, FELT_K, HUMAN_TEMPLATE, OPP_TEMPLATE, inPose,
|
||
} from '../src/games/nerts/NertsTable.js';
|
||
import { Card } from '../src/games/cards/Deck.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 C = (key, owner = 0, id = 0) => Object.assign(new Card(key[0], key[1]), { owner, id });
|
||
|
||
// ── Rules ────────────────────────────────────────────────────────────────────
|
||
section('Rules');
|
||
for (const n of [2, 3, 4]) {
|
||
const gs = createInitialState({ playerCount: n });
|
||
ok(`${n}p: foundations = 4 × players`, gs.foundations.length === 4 * n);
|
||
for (const p of gs.players) {
|
||
ok(`${n}p seat ${p.seat}: 13 nerts`, p.nerts.length === NERTS_PILE_SIZE);
|
||
ok(`${n}p seat ${p.seat}: 4 work piles of 1`, p.work.length === WORK_PILE_COUNT && p.work.every(w => w.length === 1));
|
||
ok(`${n}p seat ${p.seat}: 35 in stock`, p.stockDraw.length === 35 && p.stockWaste.length === 0);
|
||
const all = [...p.nerts, ...p.work.flat(), ...p.stockDraw];
|
||
ok(`${n}p seat ${p.seat}: owns its 52`, all.length === 52 && all.every(c => c.owner === p.seat));
|
||
}
|
||
const ids = gs.players.flatMap(p => [...p.nerts, ...p.work.flat(), ...p.stockDraw].map(c => c.id));
|
||
ok(`${n}p: card ids unique`, new Set(ids).size === ids.length);
|
||
}
|
||
{
|
||
const gs = createInitialState({ playerCount: 2 });
|
||
gs.foundations.fill(null);
|
||
ok('empty slot takes only its suit\'s ace', canPlayOnFoundation(gs, C('As'), 0) && !canPlayOnFoundation(gs, C('Ah'), 0));
|
||
ok('slot 1 wants hearts', canPlayOnFoundation(gs, C('Ah'), 1) && FOUNDATION_SUITS[1] === 'h');
|
||
ok('non-ace cannot start a slot', !canPlayOnFoundation(gs, C('2s'), 0));
|
||
gs.foundations[0] = { suit: 's', cards: [C('As')] };
|
||
ok('builds up by suit', canPlayOnFoundation(gs, C('2s'), 0) && !canPlayOnFoundation(gs, C('2c'), 0) && !canPlayOnFoundation(gs, C('3s'), 0));
|
||
const p = gs.players[0];
|
||
p.work[0] = [C('9h')];
|
||
ok('work builds down alternating colour', canPlayOnWork(gs, 0, C('8s'), 0) && !canPlayOnWork(gs, 0, C('8d'), 0) && !canPlayOnWork(gs, 0, C('7s'), 0));
|
||
p.work[1] = [];
|
||
ok('empty work pile takes anything', canPlayOnWork(gs, 0, C('Kd'), 1));
|
||
ok('valid run detection', validRunFromIndex([C('9h'), C('8s'), C('7d')], 0) && !validRunFromIndex([C('9h'), C('8h')], 0));
|
||
ok('maxRunStart', maxRunStart([C('5c'), C('9h'), C('8s'), C('7d')]) === 1);
|
||
ok('rank values ace-low', rv(C('As')) === 1 && rv(C('Kd')) === 13 && rv(C('Td')) === 10);
|
||
const full = { suit: 'd', cards: 'A23456789TJQK'.split('').map(r => C(`${r}d`)) };
|
||
gs.foundations[2] = full;
|
||
ok('complete foundation detected', isFoundationComplete(gs, 2) && !isFoundationComplete(gs, 0));
|
||
ok('nothing plays on a completed foundation', !canPlayOnFoundation(gs, C('Ad'), 2));
|
||
}
|
||
{
|
||
// stock: draw 3 / draw 1, recycle order
|
||
for (const dc of [3, 1]) {
|
||
const gs = createInitialState({ playerCount: 2, drawCount: dc });
|
||
const p = gs.players[0];
|
||
const order = [...p.stockDraw].reverse().map(c => c.id);
|
||
const seen = [];
|
||
let guard = 0;
|
||
while (p.stockDraw.length && guard++ < 100) {
|
||
const before = p.stockWaste.length;
|
||
flipStock(gs, 0);
|
||
seen.push(...p.stockWaste.slice(before).map(c => c.id));
|
||
ok(`draw ${dc}: flips ${dc} (or the rest)`, p.stockWaste.length - before === Math.min(dc, 35 - before));
|
||
}
|
||
ok(`draw ${dc}: cards come off in pile order`, seen.join() === order.join());
|
||
const r = flipStock(gs, 0);
|
||
ok(`draw ${dc}: empty draw recycles`, r?.type === 'recycle' && p.stockDraw.length === 35 && p.stockWaste.length === 0);
|
||
const again = [...p.stockDraw].reverse().map(c => c.id);
|
||
ok(`draw ${dc}: recycle keeps the order`, again.join() === order.join());
|
||
}
|
||
// rotateStocks: the next card to come off moves to the bottom
|
||
const gs = createInitialState({ playerCount: 3 });
|
||
for (const p of gs.players) { flipStock(gs, p.seat); flipStock(gs, p.seat); }
|
||
const seqs = gs.players.map(p => [...p.stockDraw].reverse().concat(p.stockWaste).map(c => c.id));
|
||
rotateStocks(gs);
|
||
gs.players.forEach((p, i) => {
|
||
const now = [...p.stockDraw].reverse().map(c => c.id);
|
||
ok(`rotateStocks seat ${i}: waste gathered`, p.stockWaste.length === 0 && p.stockDraw.length === 35);
|
||
ok(`rotateStocks seat ${i}: top card to the bottom`, now.join() === [...seqs[i].slice(1), seqs[i][0]].join());
|
||
});
|
||
reshuffleAllStocks(gs);
|
||
ok('reshuffle keeps every stock card', gs.players.every(p => p.stockDraw.length === 35 && p.stockWaste.length === 0));
|
||
}
|
||
{
|
||
// scoring
|
||
const gs = createInitialState({ playerCount: 2, targetScore: 10 });
|
||
gs.foundations.fill(null);
|
||
gs.foundations[0] = { suit: 's', cards: [C('As', 0), C('2s', 1), C('3s', 0)] };
|
||
gs.players[0].nerts = [];
|
||
gs.players[1].nerts = gs.players[1].nerts.slice(0, 5);
|
||
gs.nertsCaller = 0;
|
||
ok('live counts by owner', liveFoundationCounts(gs).join() === '2,1');
|
||
const sum = endRound(gs);
|
||
ok('caller wins the round', gs.winner === 0);
|
||
ok('+1 per centre card', sum[0].roundScore === 2);
|
||
ok('−2 per card left in Nerts', sum[1].roundScore === 1 - 10);
|
||
ok('round only, below target', gs.phase === 'roundover');
|
||
}
|
||
|
||
// ── AI helpers ───────────────────────────────────────────────────────────────
|
||
section('AI pacing');
|
||
const band = (cls, skill) => PERCEPTION[cls][skill];
|
||
for (let skill = 1; skill <= 5; skill++) {
|
||
ok(`skill ${skill}: pouncing on an awaited card beats noticing in general`, band('pounce', skill)[1] <= band('notice', skill)[0] + 200);
|
||
ok(`skill ${skill}: building on your own play is quicker than a fresh read`, band('chain', skill)[1] <= band('read', skill)[1] && band('chain', skill)[0] < band('read', skill)[0]);
|
||
ok(`skill ${skill}: the opening scan is the slowest look`, band('scan', skill)[0] >= band('read', skill)[1] * 0.9);
|
||
if (skill > 1) {
|
||
for (const cls of Object.keys(PERCEPTION)) {
|
||
ok(`${cls}: skill ${skill} quicker than skill ${skill - 1}`, band(cls, skill)[1] < band(cls, skill - 1)[1]);
|
||
}
|
||
}
|
||
for (const [name, mult] of Object.entries(PACE)) {
|
||
// fresh deal: nothing may happen before the opening scan has had time
|
||
const gs = createInitialState({ playerCount: 2 });
|
||
const mind = createMind(skill, 0);
|
||
const early = band('scan', skill)[0] * mult - 1;
|
||
const plan = planMove(gs, 1, mind, { now: early, pace: mult, foundationAt: [] });
|
||
ok(`skill ${skill} ${name}: no move before the opening scan`, !plan.action && plan.wait > 0, JSON.stringify(plan));
|
||
// after a flip the seat must read before it does anything new
|
||
const fresh = createMind(skill, 0);
|
||
noteOwnChange(fresh, 10000, 'flip');
|
||
const p2 = planMove(gs, 1, fresh, { now: 10000 + band('read', skill)[0] * mult - 1, pace: mult, foundationAt: [] });
|
||
ok(`skill ${skill} ${name}: reads before acting after a flip`, !p2.action);
|
||
ok(`skill ${skill} ${name}: waits are finite and positive`, Number.isFinite(p2.wait) && p2.wait > 0);
|
||
}
|
||
if (skill > 1) {
|
||
ok(`skill ${skill}: hand at least as fast as skill ${skill - 1}`, handSpeed(skill) >= handSpeed(skill - 1)
|
||
&& reachDelay(skill) < reachDelay(skill - 1) && carryDelay(skill) < carryDelay(skill - 1));
|
||
}
|
||
}
|
||
ok('hand speeds: ¼ · 0.3 · ½ · 0.8 · full', [1, 2, 3, 4, 5].map(k => HAND_SPEED[k]).join() === '0.25,0.3,0.5,0.8,1');
|
||
ok('skill 5 hand unchanged (190ms reach)', Math.abs(reachDelay(5) - 190) < 1e-9 && Math.abs(carryDelay(5) - 300) < 1e-9);
|
||
ok('skill 3 hand at half speed', Math.abs(reachDelay(3) - 600) < 1e-9 && Math.abs(carryDelay(3) - 600) < 1e-9);
|
||
ok('skill 1 hand at quarter speed', Math.abs(reachDelay(1) - 1680) < 1e-9);
|
||
{
|
||
// pounce vs notice: someone plays the A♥ our Nerts 2♥ was waiting for
|
||
const gs = createInitialState({ playerCount: 2 });
|
||
gs.foundations.fill(null);
|
||
const two = C('2h', 1, 990);
|
||
gs.players[1].nerts.push(two);
|
||
gs.foundations[1] = { suit: 'h', cards: [C('Ah', 0, 991)] };
|
||
const mind = createMind(3, 0);
|
||
noteOwnChange(mind, 1000, 'move');
|
||
const fAt = []; fAt[1] = { at: 5000, seat: 0 };
|
||
const play = { kind: 'foundation', source: { type: 'nerts' }, dest: 1, card: two };
|
||
const t = noticeAt(1, mind, play, { pace: 1, foundationAt: fAt }) - 5000;
|
||
ok('a Nerts card someone else unlocks is pounced on', t >= band('pounce', 3)[0] && t <= band('pounce', 3)[1], String(t));
|
||
const wplay = { kind: 'foundation', source: { type: 'waste' }, dest: 1, card: two };
|
||
const tw = noticeAt(1, mind, wplay, { pace: 1, foundationAt: fAt }) - 5000;
|
||
ok('a waste card someone else unlocks takes longer to notice', tw >= band('notice', 3)[0] && tw <= band('notice', 3)[1], String(tw));
|
||
fAt[1] = { at: 1000, seat: 1 };
|
||
const tc = noticeAt(1, mind, play, { pace: 1, foundationAt: fAt }) - 1000;
|
||
ok('building on your own play is a quick chain', tc >= band('chain', 3)[0] && tc <= band('chain', 3)[1], String(tc));
|
||
const again = noticeAt(1, mind, play, { pace: 1, foundationAt: fAt });
|
||
ok('the same play keeps the same notice time (no flicker)', again - 1000 === tc);
|
||
}
|
||
{
|
||
// no busy-work: split runs and whole-pile-to-empty moves are filtered, and
|
||
// repeatedly applying useful work→work moves never loops
|
||
const gs = createInitialState({ playerCount: 2 });
|
||
const p = gs.players[0];
|
||
p.work = [[C('Kc', 0, 800), C('Qh', 0, 801), C('Js', 0, 802)], [C('Qd', 0, 803)], [], [C('5s', 0, 804), C('Th', 0, 805)]];
|
||
const split = { kind: 'work', source: { type: 'work', idx: 0, count: 1 }, dest: 1, card: p.work[0][2] };
|
||
ok('splitting a run is not useful', !isUsefulPlay(gs, 0, split));
|
||
const whole = { kind: 'work', source: { type: 'work', idx: 0, count: 3 }, dest: 2, card: p.work[0][0] };
|
||
ok('a whole pile onto an empty pile is not useful', !isUsefulPlay(gs, 0, whole));
|
||
const uncover = { kind: 'work', source: { type: 'work', idx: 3, count: 1 }, dest: 2, card: p.work[3][1] };
|
||
ok('lifting a card off a non-sequence card is useful', isUsefulPlay(gs, 0, uncover));
|
||
for (let trial = 0; trial < 200; trial++) {
|
||
const g = createInitialState({ playerCount: 2 });
|
||
const seen = new Set();
|
||
let looped = false;
|
||
for (let step = 0; step < 60; step++) {
|
||
const moves = usefulPlays(g, 0).filter(m => m.kind === 'work' && m.source.type === 'work');
|
||
if (!moves.length) break;
|
||
const m = moves[Math.floor(Math.random() * moves.length)];
|
||
playToWork(g, 0, m.source, m.dest);
|
||
const key = g.players[0].work.map(w => w.map(c => c.id).join('.')).join('|');
|
||
if (seen.has(key)) { looped = true; break; }
|
||
seen.add(key);
|
||
}
|
||
if (looped) { ok('useful work moves never loop', false); break; }
|
||
}
|
||
ok('useful work moves never loop', true);
|
||
}
|
||
{
|
||
const gs = createInitialState({ playerCount: 2 });
|
||
const plays = rankedPlays(gs, 0);
|
||
ok('rankedPlays returns sensible legal plays', plays.length === usefulPlays(gs, 0).length);
|
||
ok('chooseAction still works headless', chooseAction(gs, 1, 3) !== undefined);
|
||
}
|
||
|
||
// ── Layout ───────────────────────────────────────────────────────────────────
|
||
section('Layout');
|
||
const onScreen = (b, m = 0) => b.x0 >= -m && b.y0 >= -m && b.x1 <= W + m && b.y1 <= H + m;
|
||
const boxOf = (pts) => ({
|
||
x0: Math.min(...pts.map(p => p.x)), x1: Math.max(...pts.map(p => p.x)),
|
||
y0: Math.min(...pts.map(p => p.y)), y1: Math.max(...pts.map(p => p.y)),
|
||
});
|
||
const union = (bs) => ({ x0: Math.min(...bs.map(b => b.x0)), x1: Math.max(...bs.map(b => b.x1)), y0: Math.min(...bs.map(b => b.y0)), y1: Math.max(...bs.map(b => b.y1)) });
|
||
const overlap = (a, b, pad = 0) => a.x0 < b.x1 + pad && b.x0 < a.x1 + pad && a.y0 < b.y1 + pad && b.y0 < a.y1 + pad;
|
||
const rectBox = (r) => ({ x0: r.x - r.w / 2, x1: r.x + r.w / 2, y0: r.y - r.h / 2, y1: r.y + r.h / 2 });
|
||
const PLATE = { w: 268, h: 92 };
|
||
|
||
// Every card a seat could show at worst: 13-deep work piles, a full waste fan, full stacks.
|
||
function seatCardBoxes(L, seat) {
|
||
const out = [];
|
||
out.push(cardBounds(cardPose(L, seat, 'nerts', 0, 12, 13)));
|
||
for (let w = 0; w < 4; w++) for (let i = 0; i < 13; i++) out.push(cardBounds(cardPose(L, seat, 'work', w, i, 13)));
|
||
out.push(cardBounds(cardPose(L, seat, 'stock', 0, 34, 35)));
|
||
for (let i = 0; i < 3; i++) out.push(cardBounds(cardPose(L, seat, 'waste', 0, 30 + i, 33)));
|
||
return out;
|
||
}
|
||
|
||
for (const n of [2, 3, 4]) {
|
||
const L = layoutFor(n);
|
||
ok(`${n}p: one seat per player`, L.seats.length === n);
|
||
const seatBoxes = [];
|
||
for (let seat = 0; seat < n; seat++) {
|
||
const boxes = seatCardBoxes(L, seat);
|
||
ok(`${n}p seat ${seat}: every card on screen`, boxes.every(b => onScreen(b, 2)), JSON.stringify(union(boxes)));
|
||
// the base row sits on the felt; fans may run onto the rail but not off the table
|
||
const base = [cardPose(L, seat, 'nerts', 0, 0, 1), ...[0, 1, 2, 3].map(w => pileBase(L, seat, 'work', w)), pileBase(L, seat, 'stock'), pileBase(L, seat, 'waste')];
|
||
ok(`${n}p seat ${seat}: pile bases on the felt`, base.every(p => onTable(p, FELT_K)));
|
||
seatBoxes[seat] = { boxes, all: union(boxes) };
|
||
const badge = nertsBadge(L, seat);
|
||
ok(`${n}p seat ${seat}: nerts badge on screen`, badge.x > 20 && badge.x < W - 20 && badge.y > 20 && badge.y < H - 20);
|
||
const plate = rectBox({ ...L.seats[seat].plate, ...PLATE });
|
||
ok(`${n}p seat ${seat}: nameplate on screen`, onScreen(plate));
|
||
const d = dealSpot(L, seat), h = seatHome(L, seat);
|
||
ok(`${n}p seat ${seat}: deal spot / hand rest on screen`, d.x > 0 && d.x < W && d.y > -40 && d.y < H && h.y > -60);
|
||
}
|
||
// seats never overlap each other (card by card)
|
||
for (let a = 0; a < n; a++) {
|
||
for (let b = a + 1; b < n; b++) {
|
||
const hit = seatBoxes[a].boxes.some(x => seatBoxes[b].boxes.some(y => overlap(x, y, 6)));
|
||
ok(`${n}p: seat ${a} clear of seat ${b}`, !hit);
|
||
}
|
||
}
|
||
// foundations: on the felt, no overlap with each other, clear of every seat
|
||
const fBoxes = L.foundations.map((f, i) => cardBounds(foundationPose(L, i, 13)));
|
||
ok(`${n}p: foundations on the felt`, L.foundations.every(f => onTable(f, FELT_K * 0.95)));
|
||
ok(`${n}p: foundations don't overlap`, fBoxes.every((x, i) => fBoxes.every((y, j) => i === j || !overlap(x, y))));
|
||
const fAll = union(fBoxes);
|
||
for (let seat = 0; seat < n; seat++) {
|
||
ok(`${n}p: foundations clear of seat ${seat}`, !seatBoxes[seat].boxes.some(b => overlap(b, fAll, 20)));
|
||
}
|
||
// plates / score pad / stall widget clear of every seat's cards and the foundations
|
||
const furniture = [
|
||
...L.seats.map(st => ['plate ' + st.seat, rectBox({ ...st.plate, ...PLATE })]),
|
||
['score pad', rectBox(SCORE_PAD)],
|
||
['stall widget', rectBox({ x: 200, y: 760, w: 300, h: 92 })],
|
||
['top buttons', { x0: 19, x1: 291, y0: 22, y1: 66 }],
|
||
];
|
||
for (const [name, box] of furniture) {
|
||
for (let seat = 0; seat < n; seat++) {
|
||
ok(`${n}p: ${name} clear of seat ${seat} cards`, !seatBoxes[seat].boxes.some(b => overlap(b, box, 4)));
|
||
}
|
||
ok(`${n}p: ${name} clear of the foundations`, !overlap(box, fAll, 4));
|
||
}
|
||
for (let i = 0; i < furniture.length; i++) {
|
||
for (let j = i + 1; j < furniture.length; j++) {
|
||
ok(`${n}p: ${furniture[i][0]} clear of ${furniture[j][0]}`, !overlap(furniture[i][1], furniture[j][1], 4));
|
||
}
|
||
}
|
||
|
||
// human hit-testing round-trips on a crafted tableau
|
||
const gs = createInitialState({ playerCount: n });
|
||
const p = gs.players[0];
|
||
p.work[0] = [C('9h', 0, 900), C('8s', 0, 901), C('7d', 0, 902)];
|
||
p.work[1] = [];
|
||
p.work[2] = Array.from({ length: 13 }, (_, i) => C('5c', 0, 910 + i));
|
||
flipStock(gs, 0);
|
||
const pile0 = p.work[0];
|
||
pile0.forEach((_, k) => {
|
||
const pose = cardPose(L, 0, 'work', 0, k, pile0.length);
|
||
// a point inside the visible strip of card k (above the next card's top edge)
|
||
const pt = k === pile0.length - 1 ? pose : { x: pose.x, y: pose.y - (CARD_H / 2) * 0.9 + 6 };
|
||
const hit = humanHit(L, p, pt);
|
||
ok(`${n}p: hit work card ${k}`, hit?.kind === 'work' && hit.idx === 0 && hit.k === k, JSON.stringify(hit));
|
||
});
|
||
const deep = cardPose(L, 0, 'work', 2, 12, 13);
|
||
ok(`${n}p: hit top of a 13-deep pile`, humanHit(L, p, deep)?.k === 12);
|
||
ok(`${n}p: hit the nerts top`, humanHit(L, p, cardPose(L, 0, 'nerts', 0, 12, 13))?.kind === 'nerts');
|
||
ok(`${n}p: hit the waste top`, humanHit(L, p, cardPose(L, 0, 'waste', 0, 2, 3))?.kind === 'waste');
|
||
ok(`${n}p: hit the stock`, humanHit(L, p, cardPose(L, 0, 'stock', 0, 31, 32))?.kind === 'stock');
|
||
ok(`${n}p: empty work pile is a target`, humanHit(L, p, pileBase(L, 0, 'work', 1))?.k === -1);
|
||
ok(`${n}p: felt centre hits nothing`, humanHit(L, p, { x: 960, y: L.foundations[0].y }) === null);
|
||
|
||
// drop snapping: each legal target snaps from its own landing spot, and only legal ones
|
||
const targets = [...L.foundations.map((_, i) => ({ type: 'foundation', idx: i })), ...[0, 1, 2, 3].map(i => ({ type: 'work', idx: i }))];
|
||
for (const t of targets) {
|
||
const at = targetPose(L, p, t);
|
||
const got = dropTargetAt(L, p, at, [t]);
|
||
ok(`${n}p: drop snaps to ${t.type} ${t.idx}`, got && got.type === t.type && got.idx === t.idx);
|
||
ok(`${n}p: illegal ${t.type} ${t.idx} never snaps`, dropTargetAt(L, p, at, targets.filter(x => x !== t))?.idx !== t.idx || dropTargetAt(L, p, at, targets.filter(x => x !== t))?.type !== t.type);
|
||
}
|
||
ok(`${n}p: drop far from everything snaps to nothing`, dropTargetAt(L, p, { x: 40, y: 500 }, targets) === null);
|
||
const top = dragScale(L, 200), near = dragScale(L, L.seats[0].anchor.y);
|
||
ok(`${n}p: a dragged card shrinks toward the middle`, top < near && near <= 1.04 && top >= 0.74);
|
||
}
|
||
ok('fan compresses long piles', fanStep(HUMAN_TEMPLATE, 13) * 12 <= HUMAN_TEMPLATE.fanMax + 1e-9 && fanStep(OPP_TEMPLATE, 3) === OPP_TEMPLATE.fan);
|
||
|
||
// ── AI soak ──────────────────────────────────────────────────────────────────
|
||
// Every seat is an AI. Simulated time: each seat acts on its own think timer;
|
||
// foundation cooldowns mirror the scene; stalls rotate then reshuffle stocks.
|
||
section('AI soak');
|
||
function countCards(gs) {
|
||
const counts = new Array(gs.players.length).fill(0);
|
||
for (const p of gs.players) {
|
||
for (const c of [...p.nerts, ...p.work.flat(), ...p.stockDraw, ...p.stockWaste]) counts[c.owner]++;
|
||
}
|
||
for (const s of gs.foundations) if (s) for (const c of s.cards) counts[c.owner]++;
|
||
return counts;
|
||
}
|
||
|
||
// Mirrors NertsGame's AI loop on a simulated play clock: each seat polls
|
||
// planMove (≤250ms apart), an action lands after the hand's reach, the seat
|
||
// re-plans 60ms after its move. Records every AI action's time per seat.
|
||
function soakRound(n, skills, drawCount, pace = 1) {
|
||
const gs = createInitialState({ playerCount: n, drawCount });
|
||
const minds = skills.map(s => createMind(s, 0));
|
||
const foundationAt = [];
|
||
const next = skills.map(() => 100 + Math.random() * 200); // next poll per seat
|
||
const pending = skills.map(() => null); // { at, action }
|
||
const actionTimes = skills.map(() => []);
|
||
let now = 0, lastProgress = 0, lastRotate = -Infinity, rotations = 0, actions = 0, conserved = true, foundationOk = true;
|
||
let gaveUp = false, fumbles = 0;
|
||
while (gs.nertsCaller === null && !allStuck(gs) && now < 30 * 60 * 1000) {
|
||
let seat = 0, t = Infinity;
|
||
for (let s = 0; s < n; s++) {
|
||
const ts = pending[s] ? pending[s].at : next[s];
|
||
if (ts < t) { t = ts; seat = s; }
|
||
}
|
||
now = t;
|
||
if (!pending[seat]) {
|
||
const plan = planMove(gs, seat, minds[seat], { now, pace, foundationAt, stalledMs: now - lastProgress });
|
||
if (!plan.action) { next[seat] = now + Math.min(250, plan.wait ?? 250); continue; }
|
||
const reach = reachDelay(skills[seat], pace, plan.action.kind === 'flip' ? 'flip' : 'move');
|
||
pending[seat] = { at: now + reach, action: plan.action };
|
||
continue;
|
||
}
|
||
const a = pending[seat].action;
|
||
pending[seat] = null;
|
||
if (a.kind === 'flip') { flipStock(gs, seat); noteOwnChange(minds[seat], now, 'flip'); }
|
||
else if (a.kind === 'foundation') {
|
||
const log = playToFoundation(gs, seat, a.source, a.dest);
|
||
if (log) { foundationAt[a.dest] = { at: now, seat }; lastProgress = now; noteOwnChange(minds[seat], now, 'move'); }
|
||
else { fumbles++; noteOwnChange(minds[seat], now, 'fumble'); }
|
||
} else if (a.kind === 'work') {
|
||
const log = playToWork(gs, seat, a.source, a.dest);
|
||
if (log && a.source.type === 'nerts') lastProgress = now;
|
||
noteOwnChange(minds[seat], now, 'move');
|
||
}
|
||
actionTimes[seat].push(now);
|
||
actions++;
|
||
// the hand finishes carrying a played card before it reaches again
|
||
next[seat] = now + (a.kind === 'flip' ? 60 : carryDelay(skills[seat], pace));
|
||
// mirrors NertsGame.updateStall: rotate at 60s idle (30s apart), give up at 180s
|
||
if (now - lastProgress >= 60000 && now - lastRotate >= 30000) {
|
||
if (rotations === 0) rotateStocks(gs); else reshuffleAllStocks(gs);
|
||
for (const m of minds) noteOwnChange(m, now, 'flip');
|
||
rotations++;
|
||
lastRotate = now;
|
||
}
|
||
if (now - lastProgress >= 180000) { gaveUp = true; break; }
|
||
if (actions % 50 === 0) {
|
||
if (!countCards(gs).every(c => c === 52)) conserved = false;
|
||
for (const s of gs.foundations) {
|
||
if (!s) continue;
|
||
s.cards.forEach((c, i) => { if (c.suit !== s.suit || rv(c) !== i + 1) foundationOk = false; });
|
||
}
|
||
}
|
||
}
|
||
if (!countCards(gs).every(c => c === 52)) conserved = false;
|
||
const live = liveFoundationCounts(gs);
|
||
const nertsLeft = gs.players.map(p => p.nerts.length);
|
||
const ended = gs.nertsCaller !== null || allStuck(gs) || gaveUp;
|
||
const summary = endRound(gs);
|
||
const scoresOk = summary.every(s => s.founded === live[s.seat] && s.roundScore === s.founded - 2 * nertsLeft[s.seat]);
|
||
return { ended, gaveUp, conserved, foundationOk, scoresOk, minutes: now / 60000, rotations, caller: gs.nertsCaller, actions, actionTimes, fumbles };
|
||
}
|
||
|
||
const ROUNDS = QUICK ? 24 : 150;
|
||
const stats = { ended: 0, gaveUp: 0, minutes: [], rotations: 0, wins: [0, 0, 0, 0], fumbles: 0, gaps: {} };
|
||
for (let r = 0; r < ROUNDS; r++) {
|
||
const n = 2 + (r % 3);
|
||
const skills = [3, ...Array.from({ length: n - 1 }, (_, i) => 1 + ((r + i * 2) % 5))];
|
||
const res = soakRound(n, skills, r % 4 === 3 ? 1 : 3);
|
||
ok(`round ${r} (${n}p): ended`, res.ended, `${res.minutes.toFixed(1)} min, ${res.rotations} rotations`);
|
||
ok(`round ${r}: cards conserved`, res.conserved);
|
||
ok(`round ${r}: foundations build A→K by suit`, res.foundationOk);
|
||
ok(`round ${r}: scores = +1/centre card −2/nerts card`, res.scoresOk);
|
||
if (res.ended) stats.ended++;
|
||
if (res.gaveUp) stats.gaveUp++;
|
||
stats.minutes.push(res.minutes);
|
||
stats.rotations += res.rotations;
|
||
if (res.caller !== null) stats.wins[res.caller]++;
|
||
stats.fumbles += res.fumbles;
|
||
res.actionTimes.forEach((times, seat) => {
|
||
const g = (stats.gaps[skills[seat]] ??= []);
|
||
for (let i = 1; i < times.length; i++) g.push(times[i] - times[i - 1]);
|
||
});
|
||
}
|
||
const mins = stats.minutes.sort((a, b) => a - b);
|
||
console.log(` ${stats.ended}/${ROUNDS} rounds ended (${stats.gaveUp} stalled out) · median ${mins[Math.floor(mins.length / 2)].toFixed(1)} sim-min · max ${mins[mins.length - 1].toFixed(1)} · ${stats.rotations} stock rotations · callers by seat ${stats.wins.join('/')}`);
|
||
|
||
const avg = (a) => a.reduce((x, y) => x + y, 0) / a.length;
|
||
const paceLine = Object.keys(stats.gaps).sort().map(sk => `skill ${sk} ${(avg(stats.gaps[sk]) / 1000).toFixed(2)}s`).join(' · ');
|
||
console.log(` avg time between a seat's actions: ${paceLine} · ${stats.fumbles} lost races`);
|
||
for (const sk of Object.keys(stats.gaps)) {
|
||
const a = avg(stats.gaps[sk]) / 1000;
|
||
ok(`skill ${sk}: plays at a human pace (${a.toFixed(2)}s/action)`, a >= 0.7 && a <= 6);
|
||
}
|
||
if (stats.gaps[1] && stats.gaps[5]) ok('skill 5 plays faster than skill 1', avg(stats.gaps[5]) < avg(stats.gaps[1]));
|
||
|
||
console.log(`\n${pass} passed, ${fail} failed`);
|
||
process.exit(fail ? 1 : 0);
|