436 lines
26 KiB
JavaScript
436 lines
26 KiB
JavaScript
#!/usr/bin/env node
|
|
// verifyCribbage.js — headless checks for Cribbage ("The Keeper's Cottage"):
|
|
// hand scoring (fixtures + an independent brute-force scorer), the counted-
|
|
// aloud breakdown, pegging, the rules engine (deal, lay-away, cut / his
|
|
// heels, go / last card / 31, show order and stopping on a win, skunks,
|
|
// match play, the 61 game, saves), the AI (legal, exact lay-away EV, the
|
|
// crib tables, the skill ladder on paired deals), the table + board layout,
|
|
// and an all-AI soak (52 cards conserved, points add up).
|
|
// Usage: node tools/verifyCribbage.js [--quick]
|
|
|
|
import {
|
|
makeCard, cardFromId, fullDeck, scoreHand, scoreHandDetailed, scorePlay, skunkLines, gamesNeeded, DEFAULT_RULES,
|
|
} from '../src/games/cribbage/CribbageData.js';
|
|
import * as G from '../src/games/cribbage/CribbageLogic.js';
|
|
import {
|
|
chooseDiscard, choosePlay, rankDiscards, coachDiscard, coachPlay, cribEV, evalPlay,
|
|
} from '../src/games/cribbage/CribbageAI.js';
|
|
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
|
|
import {
|
|
W, H as SCREEN_H, cardBounds, fanBounds, rectsOverlap, onScreen, hudFurniture, pointInPoly, DOCK, plateRect,
|
|
} from '../src/ui/cardtable/TableGeometry.js';
|
|
import {
|
|
L, boardGeometry, boardOutline, boardRect, rowPose, prevPose, showPose, cribPose, handPose, skunkLinesFor,
|
|
} from '../src/games/cribbage/CribbageTable.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 = (s) => s.split(' ').filter(Boolean).map(cardFromId);
|
|
const clone = (o) => JSON.parse(JSON.stringify(o));
|
|
|
|
function shuffled(rng) {
|
|
const d = fullDeck();
|
|
for (let i = d.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [d[i], d[j]] = [d[j], d[i]]; }
|
|
return d;
|
|
}
|
|
|
|
// ── Hand scoring ─────────────────────────────────────────────────────────────
|
|
section('Hand scoring');
|
|
{
|
|
const r = scoreHand(C('Jh 5s 5c 5d'), cardFromId('5h'));
|
|
ok('29 hand', r.total === 29, `got ${r.total}`);
|
|
ok(' 16 in fifteens · 12 in pairs · 1 nobs', r.fifteens === 16 && r.pairs === 12 && r.nobs === 1);
|
|
ok('double double run 4 4 5 5 + 6 = 24', scoreHand(C('4s 4h 5c 5d'), cardFromId('6h')).total === 24);
|
|
ok('3 4 4 5 + 6 = 14', scoreHand(C('3h 4d 4s 5c'), cardFromId('6c')).total === 14);
|
|
ok('a "nineteen": 2 4 6 8 + Q (mixed suits) = 0', scoreHand(C('2h 4d 6s 8c'), cardFromId('Qh')).total === 0);
|
|
ok('4-card hand flush off-suit = 4', scoreHand(C('2s 4s 6s 9s'), cardFromId('Kh')).flush === 4);
|
|
ok('5-card hand flush = 5', scoreHand(C('2s 4s 6s 9s'), cardFromId('Ks')).flush === 5);
|
|
ok('crib 4-flush does not count', scoreHand(C('2s 4s 6s 9s'), cardFromId('Kh'), true).flush === 0);
|
|
ok('crib 5-flush counts 5', scoreHand(C('2s 4s 6s 9s'), cardFromId('Ks'), true).flush === 5);
|
|
ok('nobs needs the starter\'s suit', scoreHand(C('Jd 3s 7c 9h'), cardFromId('Ad')).nobs === 1 && scoreHand(C('Jd 3s 7c 9h'), cardFromId('Ac')).nobs === 0);
|
|
ok('starter jack is not nobs', scoreHand(C('3d 3s 7c 9h'), cardFromId('Jd')).nobs === 0);
|
|
ok('ace is low only: Q K A no run', scoreHand(C('Qs Kh Ad 7c'), cardFromId('2c')).runs === 0);
|
|
ok('A 2 3 is a run', scoreHand(C('As 2h 3d 9c'), cardFromId('Kc')).runs === 3);
|
|
}
|
|
|
|
// An independent scorer: fifteens/pairs by subsets, runs = the largest run size
|
|
// any subset makes, times how many subsets of that size are runs.
|
|
function brute(hand4, starter, isCrib) {
|
|
const all = [...hand4, starter];
|
|
let pts = 0;
|
|
for (let m = 1; m < 32; m++) {
|
|
const sub = all.filter((_, i) => m & (1 << i));
|
|
if (sub.reduce((s, c) => s + c.val, 0) === 15) pts += 2;
|
|
if (sub.length === 2 && sub[0].rank === sub[1].rank) pts += 2;
|
|
}
|
|
for (let k = 5; k >= 3; k--) {
|
|
let n = 0;
|
|
for (let m = 1; m < 32; m++) {
|
|
const sub = all.filter((_, i) => m & (1 << i));
|
|
if (sub.length !== k) continue;
|
|
const r = sub.map((c) => c.run).sort((a, b) => a - b);
|
|
if (r.every((v, i) => !i || v === r[i - 1] + 1)) n++;
|
|
}
|
|
if (n) { pts += n * k; break; }
|
|
}
|
|
const suit = hand4[0].suit;
|
|
if (hand4.every((c) => c.suit === suit)) pts += starter.suit === suit ? 5 : isCrib ? 0 : 4;
|
|
if (hand4.some((c) => c.rank === 'J' && c.suit === starter.suit)) pts += 1;
|
|
return pts;
|
|
}
|
|
{
|
|
const rng = mulberry32(7);
|
|
let agree = true, detailOk = true, bad = '';
|
|
const N = QUICK ? 4000 : 30000;
|
|
for (let t = 0; t < N; t++) {
|
|
// bias toward rich hands: a third of the time draw from a narrow band of ranks
|
|
let d = shuffled(rng);
|
|
if (t % 3 === 0) d = d.filter((c) => c.run >= 3 && c.run <= 8 || c.rank === 'J');
|
|
const hand = d.slice(0, 4), st = d[4], crib = t % 2 === 1;
|
|
const a = scoreHand(hand, st, crib).total, b = brute(hand, st, crib);
|
|
if (a !== b) { agree = false; bad = `${hand.map((c) => c.id)} + ${st.id}: ${a} vs ${b}`; break; }
|
|
const det = scoreHandDetailed(hand, st, crib);
|
|
const ids = new Set([...hand, st].map((c) => c.id));
|
|
const sumPts = det.combos.reduce((s, c) => s + c.pts, 0);
|
|
if (det.total !== a || sumPts !== a || det.combos.some((c, i) => !c.ids.every((id) => ids.has(id))
|
|
|| c.running !== det.combos.slice(0, i + 1).reduce((s, x) => s + x.pts, 0) || !c.say)) {
|
|
detailOk = false; bad = `detail ${hand.map((c) => c.id)} + ${st.id}`; break;
|
|
}
|
|
}
|
|
ok(`scoreHand agrees with brute force (${N} hands)`, agree, bad);
|
|
ok('counted-aloud breakdown adds up, cards belong to the hand', detailOk, bad);
|
|
const det = scoreHandDetailed(C('Jh 5s 5c 5d'), cardFromId('5h'));
|
|
ok('29 is said "Fifteen 2 … and one for his nobs, 29"', det.combos[0].say === 'Fifteen 2' && /nobs, 29$/.test(det.combos[det.combos.length - 1].say));
|
|
ok('four fives call "double pair royal"', det.combos.some((c) => c.kind === 'doublePairRoyal' && c.pts === 12));
|
|
const dr = scoreHandDetailed(C('3h 4d 4s 5c'), cardFromId('6c'));
|
|
ok('a double run is two calls of four', dr.combos.filter((c) => c.kind === 'run' && c.pts === 4).length === 2);
|
|
}
|
|
|
|
// ── Pegging ──────────────────────────────────────────────────────────────────
|
|
section('Pegging');
|
|
{
|
|
const sp = (s) => scorePlay(C(s));
|
|
ok('15 pegs 2', sp('7s 8d').points === 2);
|
|
ok('31 pegs 2', sp('Ks Td 6c 5h').points === 2);
|
|
ok('pair 2 · pair royal 6 · double pair royal 12', sp('4s 4d').points === 2 && sp('4s 4d 4c').points === 6 && sp('4s 4d 4c 4h').points === 12);
|
|
ok('run of 3 in any order', sp('3s 5d 4c').points === 3);
|
|
ok('run of 4', sp('3s 5d 4c 6h').points === 4);
|
|
ok('a pair breaks the run', sp('3s 4d 4c 5h').points === 0 && sp('3s 4d 4c').points === 2);
|
|
ok('run is the newest cards only', sp('2s 9d 3c 4h').points === 0 && sp('9d 2s 3c 4h').points === 3);
|
|
ok('15 + run together', sp('4s 6d 5c').points === 5);
|
|
ok('score ids: pair royal lights three cards', sp('4s 4d 4c').scoreIds.length === 3);
|
|
}
|
|
|
|
// ── Rules engine ─────────────────────────────────────────────────────────────
|
|
section('Rules engine');
|
|
/** A play-phase state with given kept hands; pone (seat 1 - dealer) leads. */
|
|
function playState({ dealer = 0, h0, h1, scores = [0, 0], rules = {} }) {
|
|
let gs = G.createGame({ seed: 1, dealer, rules });
|
|
const used = new Set([...h0, ...h1].map((c) => c.id));
|
|
const rest = fullDeck().filter((c) => !used.has(c.id));
|
|
gs = clone(gs);
|
|
gs.hands = [[...h0, rest[0], rest[1]], [...h1, rest[2], rest[3]]];
|
|
gs.kept = [h0, h1];
|
|
gs.layaway = [[rest[0].id, rest[1].id], [rest[2].id, rest[3].id]];
|
|
gs.crib = rest.slice(0, 4);
|
|
gs.starter = rest.find((c) => c.rank !== 'J' && !used.has(c.id) && c.id !== rest[0].id && c.id !== rest[1].id && c.id !== rest[2].id && c.id !== rest[3].id && c.rank !== '5');
|
|
gs.deck = rest.slice(4).filter((c) => c.id !== gs.starter.id);
|
|
gs.scores = scores.slice();
|
|
gs.back = scores.map((s) => (s ? s - 1 : -1));
|
|
gs.phase = 'cut';
|
|
return gs;
|
|
}
|
|
{
|
|
const gs = G.createGame({ seed: 5, dealer: 0 });
|
|
ok('six cards each, 40 in the deck', gs.hands[0].length === 6 && gs.hands[1].length === 6 && gs.deck.length === 40);
|
|
ok('52 cards in play', G.cardsInPlay(gs) === 52);
|
|
ok('bad lay-away is refused', G.discard(gs, 0, [gs.hands[0][0].id]) === gs && G.discard(gs, 0, [gs.hands[1][0].id, gs.hands[0][0].id]) === gs);
|
|
const a = G.discard(gs, 0, gs.hands[0].slice(0, 2).map((c) => c.id));
|
|
ok('one lay-away: still in discard', a.phase === 'discard' && a.crib.length === 2 && G.discard(a, 0, a.hands[0].slice(2, 4).map((c) => c.id)) === a);
|
|
const b = G.discard(a, 1, a.hands[1].slice(0, 2).map((c) => c.id));
|
|
ok('both: phase cut, crib of four', b.phase === 'cut' && b.crib.length === 4);
|
|
const c = G.cutStarter(b);
|
|
ok('the cut turns a starter and starts the play', c.phase === 'play' && c.starter && !c.deck.some((x) => x.id === c.starter.id) && c.play.next === 1);
|
|
ok('still 52 cards after the cut', G.cardsInPlay(c) === 52);
|
|
// his heels
|
|
let heels = null;
|
|
for (let s = 1; s < 400 && !heels; s++) {
|
|
let g = G.createGame({ seed: s, dealer: 1 });
|
|
g = G.discard(g, 0, g.hands[0].slice(0, 2).map((x) => x.id));
|
|
g = G.discard(g, 1, g.hands[1].slice(0, 2).map((x) => x.id));
|
|
g = G.cutStarter(g);
|
|
if (g.starter.rank === 'J') heels = g;
|
|
}
|
|
ok('his heels: 2 to the dealer', heels && heels.scores[1] === 2 && heels.scores[0] === 0 && heels.history.length === 0 && heels.stats[1].heels === 2);
|
|
// cut for deal
|
|
const cg = G.createGame({ seed: 77 });
|
|
const last = cg.cuts[cg.cuts.length - 1].map(cardFromId);
|
|
ok('cut for deal: low card deals', last[0].run !== last[1].run && cg.dealer === (last[0].run < last[1].run ? 0 : 1));
|
|
ok('cut for deal: ties recut', cg.cuts.slice(0, -1).every(([x, y]) => cardFromId(x).run === cardFromId(y).run));
|
|
}
|
|
{
|
|
// Go: pone (seat 1) leads K; dealer plays Q (20); pone plays T (30); dealer
|
|
// can't play 9 → go; pone can't either (has 5) → pone pegs 1 for the go.
|
|
let gs = G.cutStarter(playState({ dealer: 0, h0: C('Qs 9h 9d 9c'), h1: C('Kh Td 5s 5c') }));
|
|
gs = G.play(gs, 1, 'Kh');
|
|
gs = G.play(gs, 0, 'Qs');
|
|
ok('a play out of turn is refused', G.play(gs, 0, '9h') === gs);
|
|
gs = G.play(gs, 1, 'Td');
|
|
ok('count 30', gs.play.count === 0 || gs.play.series.length === 1);
|
|
const goEv = gs.log.filter((e) => e.kind === 'go');
|
|
const goPt = gs.log.find((e) => e.kind === 'peg' && e.why === 'go');
|
|
ok('dealer says go', goEv.length === 1 && goEv[0].seat === 0);
|
|
ok('pone pegs 1 for the go', goPt && goPt.seat === 1 && goPt.pts === 1);
|
|
ok('count resets; dealer (who didn\'t play last) leads', gs.play.count === 0 && gs.play.next === 0 && gs.play.series.length === 1);
|
|
// play out: dealer 9h, pone 5s (14)… finish and check last card
|
|
let guard = 0;
|
|
while (gs.phase === 'play' && guard++ < 20) {
|
|
const s = gs.play.next;
|
|
gs = G.play(gs, s, G.legalPlays(gs, s)[0].id);
|
|
}
|
|
ok('play ends in the show', gs.phase === 'show');
|
|
ok('exactly one "last card" point', gs.log.filter((e) => e.kind === 'peg' && e.why === 'last').length === 1 || gs.log.some((e) => e.kind === 'play' && e.count === 31));
|
|
}
|
|
{
|
|
// Running out of cards is not a "go": pone plays its only... dealer holds
|
|
// the last two and plays them on alone without any "go" from the empty hand.
|
|
let gs = G.cutStarter(playState({ dealer: 0, h0: C('2s 3h 4d 6c'), h1: C('As Ah Ad Ac') }));
|
|
let guard = 0;
|
|
while (gs.phase === 'play' && guard++ < 20) { const s = gs.play.next; gs = G.play(gs, s, G.legalPlays(gs, s)[0].id); }
|
|
ok('no "go" when a hand is simply empty', !gs.log.some((e) => e.kind === 'go'));
|
|
}
|
|
{
|
|
// 31 on the very last card: 2 for 31, no extra point for last card.
|
|
let gs = G.cutStarter(playState({ dealer: 0, h0: C('Ts 5h Th 6c'), h1: C('Ks 6s Kh 5c') }));
|
|
const seq = [[1, 'Ks'], [0, 'Ts'], [1, '6s'], [0, '5h'], [1, 'Kh'], [0, 'Th'], [1, '5c'], [0, '6c']];
|
|
for (const [s, id] of seq) {
|
|
const nx = G.play(gs, s, id);
|
|
if (nx === gs) { ok(`scripted play ${id}`, false, `count ${gs.play.count}, next ${gs.play.next}`); break; }
|
|
gs = nx;
|
|
}
|
|
const pts = gs.log.filter((e) => e.kind === 'peg');
|
|
ok('31 pegs 2 on the last card, no "last card" point', pts.some((e) => e.why === 'play' && e.reasons.includes('31')) && !pts.some((e) => e.why === 'last'));
|
|
}
|
|
{
|
|
// The show: pone counts first and the game ends the moment they peg out.
|
|
let gs = G.cutStarter(playState({ dealer: 0, h0: C('2s 3h 4d 6c'), h1: C('5s 5h Ts Kd'), scores: [100, 118] }));
|
|
let guard = 0;
|
|
while (gs.phase === 'play' && guard++ < 20) { const s = gs.play.next; gs = G.play(gs, s, G.legalPlays(gs, s)[0].id); }
|
|
if (gs.phase === 'show') gs = G.finishShow(gs);
|
|
ok('pone pegs out first in the show', gs.phase === 'gameOver' && gs.winner === 1);
|
|
ok('the dealer\'s hand is never counted', !gs.show || gs.show.items.length === 1);
|
|
ok('the winner stops at the target', gs.scores[1] === 121);
|
|
ok('a game won is recorded', gs.history.length === 1 && gs.gameResult.winner === 1);
|
|
}
|
|
{
|
|
// Skunks and match play.
|
|
const finish = (scores, rules) => {
|
|
let gs = G.cutStarter(playState({ dealer: 0, h0: C('2s 3h 4d 6c'), h1: C('5s 5h Ts Kd'), scores, rules }));
|
|
let guard = 0;
|
|
while (gs.phase === 'play' && guard++ < 20) { const s = gs.play.next; gs = G.play(gs, s, G.legalPlays(gs, s)[0].id); }
|
|
return G.finishShow(gs);
|
|
};
|
|
ok('skunk lines: 91 / 61 (with the rule) / 31 for 61', skunkLines({ target: 121 }).skunk === 91 && skunkLines({ target: 121, doubleSkunk: true }).double === 61 && skunkLines({ target: 61 }).skunk === 31);
|
|
ok('games needed: best of 1/3/5/7', [1, 3, 5, 7].map(gamesNeeded).join() === '1,2,3,4');
|
|
const single = finish([80, 118], {});
|
|
ok('single game: a skunk is marked, 1 game', single.gameResult.skunk === 1 && single.games[1] === 1 && single.matchWinner === 1);
|
|
const m3 = finish([80, 118], { bestOf: 3 });
|
|
ok('best of 3: a skunk counts 2 games and wins it', m3.games[1] === 2 && m3.matchWinner === 1);
|
|
const ds = finish([50, 118], { bestOf: 5, doubleSkunk: true });
|
|
ok('double skunk counts 3 games', ds.gameResult.skunk === 2 && ds.games[1] === 3 && ds.matchWinner === 1);
|
|
const noDs = finish([50, 118], { bestOf: 5 });
|
|
ok('double skunk off: just a skunk', noDs.gameResult.skunk === 1 && noDs.games[1] === 2 && noDs.matchWinner == null);
|
|
const ng = G.nextGame(noDs);
|
|
ok('next game: fresh pegs, the loser deals', ng.scores.join() === '0,0' && ng.dealer === 0 && ng.gameNo === 2 && ng.phase === 'discard' && ng.games[1] === 2);
|
|
ok('nextGame refused once the match is won', G.nextGame(m3) === m3);
|
|
const plain = finish([95, 118], { bestOf: 3 });
|
|
ok('no skunk past 90: 1 game', plain.gameResult.skunk === 0 && plain.games[1] === 1 && plain.matchWinner == null);
|
|
}
|
|
{
|
|
// Saves
|
|
const gs = G.createGame({ seed: 3 });
|
|
ok('a fresh deal is a valid save', G.isValidSave(gs));
|
|
ok('a tampered save is refused', !G.isValidSave({ ...gs, deck: gs.deck.slice(1) }) && !G.isValidSave({ ...gs, version: 0 }));
|
|
ok('a save survives JSON', G.isValidSave(JSON.parse(JSON.stringify(gs))));
|
|
}
|
|
|
|
// ── AI ───────────────────────────────────────────────────────────────────────
|
|
section('AI');
|
|
{
|
|
let sym = true, suitedUp = true;
|
|
for (let a = 0; a < 13; a++) for (let b = 0; b < 13; b++) {
|
|
const x = cribEV(makeCard(DEFAULT_RANK(a), 's'), makeCard(DEFAULT_RANK(b), 'h'));
|
|
const y = cribEV(makeCard(DEFAULT_RANK(b), 'd'), makeCard(DEFAULT_RANK(a), 'c'));
|
|
if (Math.abs(x - y) > 1e-9) sym = false;
|
|
if (a !== b && cribEV(makeCard(DEFAULT_RANK(a), 's'), makeCard(DEFAULT_RANK(b), 's')) < x - 1e-9) suitedUp = false;
|
|
}
|
|
ok('crib table symmetric', sym);
|
|
ok('suited lay-aways never worth less', suitedUp);
|
|
ok('5-5 is the best crib pair', cribEV(cardFromId('5s'), cardFromId('5h')) > 8.5);
|
|
// exact hand EV for one keep, by hand
|
|
const hand = C('5s 5h Jd Qc 9s Kh');
|
|
const opts = rankDiscards(hand, true);
|
|
const keep = C('5s 5h Jd Qc');
|
|
const unseen = fullDeck().filter((c) => !hand.some((h) => h.id === c.id));
|
|
const ev = unseen.reduce((s, st) => s + scoreHand(keep, st).total, 0) / unseen.length;
|
|
const o = opts.find((x) => x.keep.map((c) => c.id).sort().join() === keep.map((c) => c.id).sort().join());
|
|
ok('lay-away EV is exact over the 46 starters', Math.abs(o.hand - ev) < 1e-9, `${o.hand} vs ${ev}`);
|
|
ok('15 options, best first', opts.length === 15 && opts.every((x, i) => !i || opts[i - 1].total >= x.total));
|
|
ok('dealer: a five + 9 to its own crib beats keeping 5 5 J Q', opts[0].discard.some((c) => c.rank === '5'));
|
|
ok('pone never gives away a five here', rankDiscards(hand, false)[0].keep.filter((c) => c.rank === '5').length === 2);
|
|
const coach = coachDiscard({ hands: [hand, []], dealer: 0 }, 0);
|
|
ok('the Coach agrees with the ranking', coach.best === coach.options[0]);
|
|
}
|
|
{
|
|
// legality + taking the win
|
|
const rng = mulberry32(11);
|
|
let legal = true, steps = 0;
|
|
for (let g = 0; g < (QUICK ? 30 : 120); g++) {
|
|
let gs = G.createGame({ seed: 500 + g });
|
|
while (gs.phase !== 'gameOver' && steps++ < 1e6) {
|
|
if (gs.phase === 'discard') for (const s of [0, 1]) {
|
|
const ids = chooseDiscard(gs, s, { skill: 1 + ((g + s) % 5), rng });
|
|
const nx = G.discard(gs, s, ids);
|
|
if (nx === gs) legal = false;
|
|
gs = nx;
|
|
} else if (gs.phase === 'cut') gs = G.cutStarter(gs);
|
|
else if (gs.phase === 'play') {
|
|
const s = gs.play.next;
|
|
const nx = G.play(gs, s, choosePlay(gs, s, { skill: 1 + ((g + s) % 5), rng }));
|
|
if (nx === gs) { legal = false; break; }
|
|
gs = nx;
|
|
} else if (gs.phase === 'show') gs = G.showStep(gs);
|
|
else gs = G.nextRound(gs);
|
|
}
|
|
}
|
|
ok('every AI move is legal (all skills)', legal);
|
|
let gs = G.cutStarter(playState({ dealer: 0, h0: C('7s 2h 9d Kc'), h1: C('8s 3h 3d 4c'), scores: [119, 60] }));
|
|
gs = G.play(gs, 1, '8s');
|
|
ok('pegging AI takes the winning fifteen', choosePlay(gs, 0, { skill: 3 }) === '7s');
|
|
const tip = coachPlay(gs, 0);
|
|
ok('the Coach finds it too', tip.id === '7s' && /pegs out|wins/.test(tip.reason));
|
|
let lead = G.cutStarter(playState({ dealer: 0, h0: C('2s 3h 4d 6c'), h1: C('5s 4h Ts Kd') }));
|
|
ok('skill 5 never leads a five here', choosePlay(lead, 1, { skill: 5 }) !== '5s');
|
|
const e = evalPlay(lead, 1, cardFromId('4h'));
|
|
ok('evalPlay: a 4 lead can\'t be fifteened', e.reply < 1.5);
|
|
}
|
|
{
|
|
// Skill ladder: paired deals (same cards, seats swapped), points per deal.
|
|
const N = QUICK ? 250 : 1500;
|
|
const dealDiff = (skA, skB) => {
|
|
let diff = 0;
|
|
for (let i = 0; i < N; i++) {
|
|
for (const swap of [false, true]) {
|
|
const sk = swap ? [skB, skA] : [skA, skB];
|
|
const rng = mulberry32(9000 + i);
|
|
let gs = G.createGame({ seed: 31337 + i, dealer: i % 2 });
|
|
while (!['roundOver', 'gameOver'].includes(gs.phase)) {
|
|
if (gs.phase === 'discard') for (const s of [0, 1]) gs = G.discard(gs, s, chooseDiscard(gs, s, { skill: sk[s], rng }));
|
|
else if (gs.phase === 'cut') gs = G.cutStarter(gs);
|
|
else if (gs.phase === 'play') gs = G.play(gs, gs.play.next, choosePlay(gs, gs.play.next, { skill: sk[gs.play.next], rng }));
|
|
else if (gs.phase === 'show') gs = G.showStep(gs);
|
|
}
|
|
const a = swap ? 1 : 0;
|
|
diff += gs.scores[a] - gs.scores[1 - a];
|
|
}
|
|
}
|
|
return diff / (2 * N);
|
|
};
|
|
const ladder = [[2, 1], [3, 2], [4, 3], [5, 4], [5, 3]].map(([a, b]) => ({ a, b, d: dealDiff(a, b) }));
|
|
for (const { a, b, d } of ladder) ok(`skill ${a} ≥ skill ${b} (${d >= 0 ? '+' : ''}${d.toFixed(2)} pts/deal)`, d >= (QUICK ? -0.15 : 0));
|
|
console.log(` ladder (points per deal): ${ladder.map(({ a, b, d }) => `${a}v${b} ${d >= 0 ? '+' : ''}${d.toFixed(2)}`).join(' · ')}`);
|
|
}
|
|
|
|
// ── Layout ───────────────────────────────────────────────────────────────────
|
|
section('Layout');
|
|
for (const target of [121, 61]) {
|
|
const geo = boardGeometry(target);
|
|
const outline = boardOutline();
|
|
const all = [];
|
|
for (let s = 0; s < 2; s++) {
|
|
ok(`${target}: ${target + 1} holes per player`, geo.holes[s].length === target + 1);
|
|
all.push(...geo.holes[s], geo.alt[s], ...geo.gameHoles[s]);
|
|
}
|
|
ok(`${target}: every hole on the board`, all.every((p) => pointInPoly(p, outline)));
|
|
let minD = Infinity;
|
|
for (let i = 0; i < all.length; i++) for (let j = i + 1; j < all.length; j++) minD = Math.min(minD, Math.hypot(all[i].x - all[j].x, all[i].y - all[j].y));
|
|
ok(`${target}: holes never touch (min gap ${minD.toFixed(1)}px)`, minD > geo.holeR * 2 * 0.75);
|
|
// consecutive holes are neighbours (the track never jumps)
|
|
let maxStep = 0;
|
|
for (let s = 0; s < 2; s++) for (let n = 1; n <= target; n++) maxStep = Math.max(maxStep, Math.hypot(geo.holes[s][n].x - geo.holes[s][n - 1].x, geo.holes[s][n].y - geo.holes[s][n - 1].y));
|
|
ok(`${target}: the track walks hole to hole (max step ${maxStep.toFixed(0)}px)`, maxStep < 100);
|
|
for (const { line } of skunkLinesFor(target, true)) ok(`${target}: skunk line ${line} sits between holes`, geo.skunk(line).every(({ a, b }) => a && b));
|
|
}
|
|
{
|
|
const br = boardRect();
|
|
const furn = hudFurniture();
|
|
ok('board on screen', onScreen(br));
|
|
ok('board clear of the top buttons and plates', !furn.some((f) => f.name.startsWith('button') && rectsOverlap(f.r, br)) && !rectsOverlap(plateRect(L.plates[1]), { ...br, y0: br.y0 + 20 }));
|
|
const row8 = cardBounds(rowPose(7));
|
|
const dial = { x0: L.dial.x - 76, x1: L.dial.x + 76, y0: L.dial.y - 76, y1: L.dial.y + 76 };
|
|
ok('8 cards on the row stay clear of the gauge', !rectsOverlap(row8, dial));
|
|
ok('the earlier series stack stays clear of the deck', !rectsOverlap(cardBounds(prevPose(0)), cardBounds(L.deck)));
|
|
ok('the earlier series stack stays left of the row', cardBounds(prevPose(7)).x1 < cardBounds(rowPose(0)).x1);
|
|
for (const d of [0, 1]) ok(`crib (${d ? 'Murph' : 'yours'}) clear of the gauge and the board`, !rectsOverlap(cardBounds(cribPose(d)), dial) && cardBounds(cribPose(d)).y0 > br.y1 - 40);
|
|
const show = [0, 1, 2, 3, 4].map((i) => cardBounds(showPose(i, 4)));
|
|
ok('the show row is on screen and clear of the deck', show.every((r) => onScreen(r)) && !show.some((r) => rectsOverlap(r, cardBounds(L.deck))));
|
|
const fan6 = (() => { let b = null; for (let i = 0; i < 6; i++) { const r = cardBounds(handPose(0, i, 6, 18)); b = b ? { x0: Math.min(b.x0, r.x0), x1: Math.max(b.x1, r.x1), y0: Math.min(b.y0, r.y0), y1: Math.max(b.y1, r.y1) } : r; } return b; })();
|
|
ok('your six-card fan clears the dock and your plate', !rectsOverlap(fan6, DOCK) && !rectsOverlap(fan6, plateRect(L.plates[0])));
|
|
ok('Murph\'s fan on screen, clear of his plate', [0, 1, 2, 3, 4, 5].every((i) => onScreen(cardBounds(handPose(1, i, 6)), 4)) && !rectsOverlap(fanBounds(L.fans[1], 6), plateRect(L.plates[1])));
|
|
const pend = [0, 1].map((i) => cardBounds({ x: 1190 + i * 92, y: 918 - 18, rot: 0.07 + i * 0.05, s: 1, q: 1 }));
|
|
ok('the pair going to the crib clears the dock', pend.every((r) => !rectsOverlap(r, DOCK) && r.y1 <= SCREEN_H + 30));
|
|
void W;
|
|
}
|
|
|
|
// ── Soak ─────────────────────────────────────────────────────────────────────
|
|
section('Soak');
|
|
{
|
|
const games = QUICK ? 60 : 400;
|
|
let okCards = true, okSum = true, okMono = true, okEnd = true, bad = '';
|
|
const wins = [0, 0];
|
|
for (let g = 0; g < games; g++) {
|
|
const rng = mulberry32(70000 + g);
|
|
const rules = { target: g % 5 === 0 ? 61 : 121, bestOf: g % 7 === 0 ? 3 : 1, doubleSkunk: g % 3 === 0 };
|
|
let gs = G.createGame({ seed: 123 + g, rules });
|
|
let prev = gs.scores.slice(), steps = 0;
|
|
for (;;) {
|
|
if (++steps > 20000) { okEnd = false; bad = `game ${g} did not end`; break; }
|
|
if (!['gameOver'].includes(gs.phase) && G.cardsInPlay(gs) !== 52) { okCards = false; bad = `game ${g} ${gs.phase}: ${G.cardsInPlay(gs)} cards`; }
|
|
if (gs.scores.some((v, i) => v < prev[i] && gs.round > 1) || gs.scores.some((v) => v > gs.rules.target)) { okMono = false; bad = `scores ${prev} → ${gs.scores}`; }
|
|
prev = gs.scores.slice();
|
|
if (gs.phase === 'gameOver') {
|
|
const st = gs.stats;
|
|
for (const s of [0, 1]) {
|
|
const fromStats = st[s].peg + st[s].hand + st[s].crib + st[s].heels;
|
|
const fromHist = gs.history.reduce((a, h) => a + h.peg[s] + h.hand[s] + h.crib[s] + h.heels[s], 0);
|
|
if (fromStats !== gs.scores[s] || fromHist !== gs.scores[s]) { okSum = false; bad = `game ${g} seat ${s}: ${fromStats}/${fromHist} vs ${gs.scores[s]}`; }
|
|
}
|
|
if (gs.matchWinner != null) { wins[gs.matchWinner]++; break; }
|
|
gs = G.nextGame(gs);
|
|
prev = [0, 0];
|
|
continue;
|
|
}
|
|
if (gs.phase === 'discard') for (const s of [0, 1]) gs = G.discard(gs, s, chooseDiscard(gs, s, { skill: 1 + (g % 5), rng }));
|
|
else if (gs.phase === 'cut') gs = G.cutStarter(gs, rng());
|
|
else if (gs.phase === 'play') gs = G.play(gs, gs.play.next, choosePlay(gs, gs.play.next, { skill: 1 + ((g + 2) % 5), rng }));
|
|
else if (gs.phase === 'show') gs = G.showStep(gs);
|
|
else if (gs.phase === 'roundOver') gs = G.nextRound(gs);
|
|
}
|
|
}
|
|
ok(`${games} matches all end`, okEnd, bad);
|
|
ok('52 cards at every step', okCards, bad);
|
|
ok('scores only climb, never past the target', okMono, bad);
|
|
ok('pegging + hands + cribs + heels = the score', okSum, bad);
|
|
ok('both seats win some', wins[0] > 0 && wins[1] > 0, `${wins}`);
|
|
}
|
|
|
|
console.log(`\n${pass} passed, ${fail} failed`);
|
|
process.exit(fail ? 1 : 0);
|
|
|
|
function DEFAULT_RANK(i) { return ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'][i]; }
|