388 lines
23 KiB
JavaScript
388 lines
23 KiB
JavaScript
#!/usr/bin/env node
|
|
// verifyFreecell.js — headless checks for the Night Study Freecell: the rules
|
|
// engine (deal, every move type, the supermove limit, safe auto-play, undo
|
|
// snapshots, numbered/daily deals), the solver (solves deals, every line
|
|
// replays legally, honest "unsolvable"), the scene's decisions (what a press
|
|
// picks up, drop targets, smart-click ranking, refusal reasons), the desk
|
|
// layout (19-card columns fit, nothing under the HUD) and the records store.
|
|
// Usage: node tools/verifyFreecell.js [--quick]
|
|
|
|
import { Card } from '../src/games/cards/Deck.js';
|
|
import {
|
|
FreecellEngine, freshDeck, deckForDeal, dailyDealNumber, randomDealNumber, MAX_DEAL, FOUNDATION_ORDER,
|
|
} from '../src/games/freecell/FreecellLogic.js';
|
|
import { FreecellSolver, stateFromEngine, autoSafe, exactKey, stateKey } from '../src/games/freecell/FreecellSolver.js';
|
|
import {
|
|
W, H, S, CW, CH, colX, cellPose, foundPose, foundCardPose, columnPosesFor, columnZone, cellZone, foundZone, hudRects,
|
|
MAX_BOTTOM, TAB_TOP, BLOTTER, DECK,
|
|
} from '../src/games/freecell/FreecellTable.js';
|
|
import { cardBounds, columnPoses } from '../src/ui/solitaire/SolitaireGeometry.js';
|
|
import { recordGame, loadStats, recordBest, formatTime } from '../src/ui/solitaire/SolitaireStats.js';
|
|
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
|
|
import FreecellGame from '../src/games/freecell/FreecellGame.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 PV = { A: 1, T: 10, J: 11, Q: 12, K: 13 };
|
|
let nid = 500;
|
|
const C = (key) => Object.assign(new Card(key[0], key[1]), { id: nid++, pval: PV[key[0]] ?? Number(key[0]) });
|
|
const cards = (s) => (s ? s.split(' ').map(C) : []);
|
|
|
|
/** Build an engine from a sketch: cols = ['Ks Qh', …] (bottom → top), cells = ['Ah', null…], found = { s: 3, … }. */
|
|
function pos({ cols = [], cells = [], found = {} }) {
|
|
const snap = {
|
|
tableau: Array.from({ length: 8 }, (_, i) => cards(cols[i] ?? '')),
|
|
freecells: [0, 1, 2, 3].map(i => (cells[i] ? C(cells[i]) : null)),
|
|
foundations: Object.fromEntries(FOUNDATION_ORDER.map(s => {
|
|
const n = found[s] ?? 0;
|
|
return [s, Array.from({ length: n }, (_, k) => C(`${['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'][k]}${s}`))];
|
|
})),
|
|
moveCount: 0,
|
|
};
|
|
return FreecellEngine.fromSnapshot(snap);
|
|
}
|
|
const M = (fromKind, fi, toKind, ti, n = 1) => ({ from: { kind: fromKind, i: fi }, to: { kind: toKind, ...(ti != null ? { i: ti } : {}) }, n });
|
|
const keysOf = (e) => e.allCards().map(c => c.key).sort().join(',');
|
|
const FULL = (() => { const d = freshDeck(); return d.map(c => c.key).sort().join(','); })();
|
|
|
|
// ── Deal ─────────────────────────────────────────────────────────────────────
|
|
section('Deal');
|
|
{
|
|
const e = FreecellEngine.fromDeal(1);
|
|
ok('52 cards dealt', e.allCards().length === 52);
|
|
ok('every card once', keysOf(e) === FULL);
|
|
ok('ids unique', new Set(e.allCards().map(c => c.id)).size === 52);
|
|
ok('columns 7,7,7,7,6,6,6,6', e.tableau.map(c => c.length).join(',') === '7,7,7,7,6,6,6,6');
|
|
ok('cells + foundations empty', e.freecells.every(c => c === null) && e.homeCount() === 0);
|
|
ok('deal is numbered', e.deal === 1);
|
|
const a = deckForDeal(12345).map(c => c.key).join(), b = deckForDeal(12345).map(c => c.key).join(), c = deckForDeal(12346).map(c => c.key).join();
|
|
ok('same number → same deal', a === b);
|
|
ok('different number → different deal', a !== c);
|
|
const d1 = dailyDealNumber(new Date(2026, 10, 25)), d2 = dailyDealNumber(new Date(2026, 10, 25, 23, 59)), d3 = dailyDealNumber(new Date(2026, 10, 26));
|
|
ok('daily deal stable through the day', d1 === d2);
|
|
ok('daily deal changes each day', d1 !== d3);
|
|
ok('daily deal in range', d1 >= 1 && d1 <= MAX_DEAL);
|
|
const rng = mulberry32(9);
|
|
ok('random deal numbers in range', Array.from({ length: 200 }, () => randomDealNumber(rng)).every(n => n >= 1 && n <= MAX_DEAL));
|
|
}
|
|
|
|
// ── Moves ────────────────────────────────────────────────────────────────────
|
|
section('Moves');
|
|
{
|
|
let e = pos({ cols: ['5s Ah', '9d 8c', '7h', ''], cells: ['2h'] });
|
|
ok('ace goes home', e.isLegal(M('col', 0, 'found')));
|
|
ok('two can\'t go home before its ace', !e.isLegal(M('cell', 0, 'found')));
|
|
e.apply(M('col', 0, 'found'));
|
|
ok('then the two can', e.isLegal(M('cell', 0, 'found')));
|
|
ok('7♥ onto 8♣', e.isLegal(M('col', 2, 'col', 1)));
|
|
ok('5♠ not onto 7♥', !e.isLegal(M('col', 0, 'col', 2)));
|
|
ok('any card to an empty column', e.isLegal(M('col', 0, 'col', 3)));
|
|
ok('cell card onto a column needs a fit', !e.isLegal(M('cell', 0, 'col', 1)));
|
|
ok('cell card to empty column', e.isLegal(M('cell', 0, 'col', 3)));
|
|
ok('cell to cell is not a move', !e.isLegal(M('cell', 0, 'cell', 1)));
|
|
ok('column card to a free cell', e.isLegal(M('col', 2, 'cell', 1)));
|
|
ok('not into a taken cell', !e.isLegal(M('col', 2, 'cell', 0)));
|
|
const before = e.moveCount;
|
|
const moved = e.apply(M('col', 2, 'col', 1));
|
|
ok('apply returns the moved cards', moved.length === 1 && moved[0].key === '7h');
|
|
ok('move counted', e.moveCount === before + 1);
|
|
ok('illegal apply does nothing', e.apply(M('col', 0, 'col', 1)).length === 0 && e.moveCount === before + 1);
|
|
e = pos({ cols: ['Ks', 'Kh'], cells: ['Qs', 'Qh', 'Qd', 'Qc'] });
|
|
ok('full cells: no cell move', !e.isLegal(M('col', 0, 'cell')));
|
|
// classic wrappers still work
|
|
e = pos({ cols: ['Ah', '3s', '4h'], cells: [] });
|
|
ok('moveToFoundation wrapper', e.moveToFoundation('tableau', 0) === true);
|
|
ok('moveRun wrapper', e.moveRun(1, 0, 2) === true && e.tableau[2].length === 2);
|
|
ok('moveToFreecell wrapper', e.moveToFreecell(2) === true && e.freecells[0]?.key === '3s');
|
|
}
|
|
|
|
// ── Supermoves ───────────────────────────────────────────────────────────────
|
|
section('Supermove limit');
|
|
{
|
|
// a 4-card run in col 0, a black 9 in col 1 to receive it (8♥ 7♠ 6♥ 5♠)
|
|
const fill = ['Kc', 'Kd', 'Ks', 'Kh'];
|
|
let e = pos({ cols: ['8h 7s 6h 5s', '9c', 'Qc', 'Qd', 'Qs', 'Qh', 'Jc', 'Jd'], cells: fill });
|
|
ok('no cells, no columns → move 1', e.maxMovable(1) === 1);
|
|
ok('the 4-card run is blocked by space', e.runBlocker(0, 0, 1) === 'space');
|
|
ok('…but the single top card isn\'t limited', e.maxMovable() >= 1);
|
|
e = pos({ cols: ['8h 7s 6h 5s', '9c', 'Qc', 'Qd', 'Qs', 'Qh', 'Jc', 'Jd'], cells: ['Kc', 'Kd', 'Ks'] });
|
|
ok('1 free cell → 2', e.maxMovable(1) === 2);
|
|
e = pos({ cols: ['8h 7s 6h 5s', '9c', '', 'Qd', 'Qs', 'Qh', 'Jc', 'Jd'], cells: ['Kc', 'Kd', 'Ks'] });
|
|
ok('1 cell + 1 empty column → 4', e.maxMovable(1) === 4);
|
|
ok('the 4-card run now fits', e.canMoveRun(0, 0, 1));
|
|
ok('into the empty column itself → 2', e.maxMovable(2) === 2);
|
|
ok('4 cards into that empty column: no room', e.runBlocker(0, 0, 2) === 'space');
|
|
ok('2 cards into it: fine', e.canMoveRun(0, 2, 2));
|
|
e = pos({ cols: ['8h 7s 6h 5s', '9c', '', '', 'Qs', 'Qh', 'Jc', 'Jd'], cells: [] });
|
|
ok('4 cells + 2 empty columns → 20', e.maxMovable(1) === 20);
|
|
ok('…onto an empty column → 10', e.maxMovable(2) === 10);
|
|
e = pos({ cols: ['8h 7s 5h', '9c'] });
|
|
ok('an unordered run can\'t move', e.runBlocker(0, 0, 1) === 'unordered');
|
|
e = pos({ cols: ['8h 7s 6h', 'Tc'] });
|
|
ok('a run that doesn\'t fit', e.runBlocker(0, 0, 1) === 'mismatch');
|
|
ok('runStart finds the ordered tail', pos({ cols: ['2c 9h 8s 7d'] }).runStart(0) === 1);
|
|
}
|
|
|
|
// ── Safe auto-play ───────────────────────────────────────────────────────────
|
|
section('Safe auto-play');
|
|
{
|
|
let e = pos({ cols: ['3h'], found: { h: 2, s: 1, c: 2 } });
|
|
ok('3♥ not safe while 2♠ is out', !e.isSafeHome(e.tableau[0][0]));
|
|
e = pos({ cols: ['3h'], found: { h: 2, s: 2, c: 2 } });
|
|
ok('3♥ safe once both black twos are home', e.isSafeHome(e.tableau[0][0]));
|
|
e = pos({ cols: ['Ac', '2c'], found: {} });
|
|
ok('aces always safe', e.isSafeHome(e.tableau[0][0]));
|
|
e = pos({ cols: ['5s'], cells: ['Ad'], found: {} });
|
|
ok('cells are checked first', JSON.stringify(e.nextSafeMove()) === JSON.stringify(M('cell', 0, 'found')));
|
|
// engine safe sequence == solver autoSafe on random mid-game positions
|
|
let same = true;
|
|
for (let d = 1; d <= 30; d++) {
|
|
const g = FreecellEngine.fromDeal(d);
|
|
const rng = mulberry32(d);
|
|
for (let k = 0; k < 25; k++) { const ms = g.legalMoves(); if (!ms.length) break; g.apply(ms[Math.floor(rng() * ms.length)]); }
|
|
const st = stateFromEngine(g);
|
|
autoSafe(st);
|
|
for (let m = g.nextSafeMove(); m; m = g.nextSafeMove()) g.apply(m);
|
|
if (exactKey(st) !== exactKey(stateFromEngine(g))) same = false;
|
|
}
|
|
ok('engine safe plays match the solver\'s', same);
|
|
}
|
|
|
|
// ── Legal moves, conservation, undo snapshots ────────────────────────────────
|
|
section('Random play: legality, conservation, snapshots');
|
|
{
|
|
let allLegal = true, conserved = true, roundTrip = true, countsOk = true;
|
|
const games = QUICK ? 40 : 160;
|
|
for (let d = 1; d <= games; d++) {
|
|
const e = FreecellEngine.fromDeal(1000 + d);
|
|
const rng = mulberry32(d * 7);
|
|
const snaps = [];
|
|
for (let k = 0; k < 120; k++) {
|
|
const ms = e.legalMoves();
|
|
if (!ms.length) break;
|
|
for (const m of ms) if (!e.isLegal(m)) allLegal = false;
|
|
snaps.push({ snap: e.snapshot(), key: exactKey(stateFromEngine(e)), n: e.moveCount });
|
|
const m = ms[Math.floor(rng() * ms.length)];
|
|
const before = e.moveCount;
|
|
if (!e.apply(m).length) allLegal = false;
|
|
if (e.moveCount !== before + 1) countsOk = false;
|
|
if (keysOf(e) !== FULL) conserved = false;
|
|
}
|
|
// unwind: every snapshot restores exactly
|
|
for (let i = snaps.length - 1; i >= 0; i--) {
|
|
e.restore(snaps[i].snap);
|
|
if (exactKey(stateFromEngine(e)) !== snaps[i].key || e.moveCount !== snaps[i].n) roundTrip = false;
|
|
}
|
|
}
|
|
ok('every listed move is legal and applies', allLegal);
|
|
ok('52 cards conserved through every move', conserved);
|
|
ok('each move counts once', countsOk);
|
|
ok('snapshots restore exactly (undo)', roundTrip);
|
|
const e = FreecellEngine.fromDeal(77);
|
|
const s0 = e.snapshot();
|
|
e.apply(e.legalMoves()[0]);
|
|
ok('snapshot is a copy, not a reference', s0.tableau.map(c => c.length).join() === '7,7,7,7,6,6,6,6');
|
|
}
|
|
|
|
// ── Solver ───────────────────────────────────────────────────────────────────
|
|
section('Solver');
|
|
{
|
|
const N = QUICK ? 15 : 60;
|
|
let solved = 0, replayOk = true, worst = 0, total = 0;
|
|
for (let d = 1; d <= N; d++) {
|
|
const e = FreecellEngine.fromDeal(d);
|
|
const t0 = performance.now();
|
|
const r = new FreecellSolver(e).run();
|
|
const ms = performance.now() - t0;
|
|
total += ms; worst = Math.max(worst, ms);
|
|
if (r.status !== 'solved') continue;
|
|
solved++;
|
|
for (const m of r.moves) if (!e.apply(m).length) { replayOk = false; break; }
|
|
if (!e.isWon()) replayOk = false;
|
|
}
|
|
ok(`solves ≥ 97% of the first ${N} deals`, solved >= Math.ceil(N * 0.97), `${solved}/${N}`);
|
|
ok('every solution replays to a win on the engine', replayOk);
|
|
ok('average solve under 250 ms', total / N < 250, `${(total / N).toFixed(0)} ms`);
|
|
console.log(` solver: ${solved}/${N} deals, avg ${(total / N).toFixed(0)} ms, worst ${worst.toFixed(0)} ms`);
|
|
|
|
// mid-game positions solve and replay too
|
|
let midOk = true, midSolved = 0;
|
|
for (let d = 1; d <= (QUICK ? 8 : 25); d++) {
|
|
const e = FreecellEngine.fromDeal(d + 300);
|
|
const first = new FreecellSolver(e).run();
|
|
if (first.status !== 'solved') continue;
|
|
for (const m of first.moves.slice(0, 30)) e.apply(m);
|
|
const r = new FreecellSolver(e).run();
|
|
if (r.status !== 'solved') continue;
|
|
midSolved++;
|
|
for (const m of r.moves) if (!e.apply(m).length) { midOk = false; break; }
|
|
if (!e.isWon()) midOk = false;
|
|
}
|
|
ok('mid-game positions solve and replay', midOk && midSolved > 0, `${midSolved}`);
|
|
|
|
// a dead position: cells full of kings, every column topped by a black card, aces buried
|
|
const dead = pos({
|
|
cols: ['Ah 5d 7d Qs', 'Ad 5h 7h Qc', 'As 9h 9d Js', 'Ac Th Td Jc', '2h 2d 3h 3d 4h Ts', '4d 6h 6d 8h 8d Tc', '2s 3s 4s 5s 6s 7s 8s 9s', '2c 3c 4c 5c 6c 7c 8c Jh Jd Qh Qd 9c'],
|
|
cells: ['Ks', 'Kh', 'Kd', 'Kc'],
|
|
});
|
|
ok('dead position is a full deck', keysOf(dead) === FULL);
|
|
ok('dead position: no legal moves', dead.legalMoves().length === 0);
|
|
const rd = new FreecellSolver(dead).run();
|
|
ok('solver says unsolvable (honestly)', rd.status === 'unsolvable');
|
|
// a tiny budget gives up rather than lying
|
|
const hard = new FreecellSolver(FreecellEngine.fromDeal(5), { maxNodes: 3 }).run();
|
|
ok('out of budget → "gaveup", never "unsolvable"', hard.status === 'gaveup' || hard.status === 'solved');
|
|
// canonical keys: swapping two columns is the same position, but not the same exact key
|
|
const a = stateFromEngine(pos({ cols: ['Ks', 'Qh'] })), b = stateFromEngine(pos({ cols: ['Qh', 'Ks'] }));
|
|
ok('canonical key ignores column order', stateKey(a) === stateKey(b));
|
|
ok('exact key keeps column order (hint replay safety)', exactKey(a) !== exactKey(b));
|
|
// time-slicing gives the same answer as one go
|
|
const e1 = FreecellEngine.fromDeal(42);
|
|
const sliced = new FreecellSolver(e1);
|
|
let steps = 0;
|
|
while (!sliced.step(50)) steps++;
|
|
const whole = new FreecellSolver(FreecellEngine.fromDeal(42)).run();
|
|
ok('step(budget) is resumable and deterministic', sliced.result.status === whole.status && sliced.result.moves?.length === whole.moves?.length && steps > 0);
|
|
}
|
|
|
|
// ── Auto-complete ────────────────────────────────────────────────────────────
|
|
section('Auto-complete');
|
|
{
|
|
const e = pos({ cols: ['Kh Qh Jh', 'Ks', 'Kd', 'Kc'], cells: ['Th'], found: { s: 12, d: 12, c: 12, h: 9 } });
|
|
ok('canAutoComplete when only foundation plays remain', e.canAutoComplete());
|
|
let n = 0;
|
|
for (let s = e.autoCompleteStep(); s && n < 60; s = e.autoCompleteStep(), n++) e.apply(s.move);
|
|
ok('auto-complete clears the board', e.isWon(), `${e.homeCount()} home`);
|
|
const stuck = pos({ cols: ['Ah 2h', 'Ks'], found: {} });
|
|
ok('a buried ace blocks auto-complete', !stuck.canAutoComplete());
|
|
}
|
|
|
|
// ── Scene decisions (FreecellGame logic, no Phaser) ──────────────────────────
|
|
section('Scene: picking, targets, smart click, reasons');
|
|
{
|
|
const g = new FreecellGame();
|
|
g.settings = { autoPlay: true, analysis: true, click: 'smart', anim: 'normal' };
|
|
g.gs = pos({ cols: ['9d 8c', '7h', 'Ah', '5s 4h 3s', '', 'Qs', 'Kd 2c', 'Td'], cells: ['6c'] });
|
|
const poses = (c) => columnPosesFor(c, g.gs.tableau[c].length);
|
|
const top = (c) => poses(c)[g.gs.tableau[c].length - 1];
|
|
let src = g.pickAt(top(1));
|
|
ok('a press on a top card picks it', src?.kind === 'col' && src.i === 1 && src.n === 1 && src.ids.length === 1);
|
|
src = g.pickAt({ x: poses(3)[0].x, y: poses(3)[0].y - CH * 0.3 });
|
|
ok('a press on a buried card picks the run from it', src?.kind === 'col' && src.i === 3 && src.idx === 0 && src.n === 3);
|
|
ok('press on a free-cell card', g.pickAt(cellPose(0))?.kind === 'cell');
|
|
ok('press on empty felt picks nothing', g.pickAt({ x: colX(4), y: TAB_TOP }) === null);
|
|
ok('press on a foundation picks nothing', g.pickAt(foundPose(0)) === null);
|
|
const best = (s) => g.bestMove(s);
|
|
const m1 = best(g.pickAt(top(2)));
|
|
ok('smart click sends an ace home', m1?.to.kind === 'found');
|
|
const m2 = best(g.pickAt(top(1)));
|
|
ok('smart click builds 7♥ onto 8♣', m2?.to.kind === 'col' && m2.to.i === 0);
|
|
const m3 = best(g.pickAt(cellPose(0)));
|
|
ok('smart click plays the cell 6♣ onto 7♥', m3?.to.kind === 'col' && m3.to.i === 1);
|
|
const tgts = g.movesFor(g.pickAt(top(5)));
|
|
ok('drag targets include every empty cell', tgts.filter(t => t.kind === 'cell').length === 3);
|
|
ok('drag targets include the empty column', tgts.some(t => t.kind === 'col' && t.move.to.i === 4));
|
|
ok('targets have anchors on screen', tgts.every(t => t.anchor.x > 0 && t.anchor.x < W && t.anchor.y > 0 && t.anchor.y < H));
|
|
ok('every target move is legal', tgts.every(t => g.gs.isLegal(t.move)));
|
|
// reasons
|
|
const unordered = pos({ cols: ['9d 3c 8c'] });
|
|
g.gs = unordered;
|
|
ok('grabbing an unordered run is refused with a reason', /ordered/.test(g.grabBlocker({ kind: 'col', i: 0, idx: 0, n: 3 }) ?? ''));
|
|
g.gs = pos({ cols: ['8h 7s 6h 5s', '9c', 'Qc', 'Qd', 'Qs', 'Qh', 'Jc', 'Jd'], cells: ['Kc', 'Kd', 'Ks', 'Kh'] });
|
|
ok('too-long run explains the room', /room to move 1/.test(g.noMoveReason({ kind: 'col', i: 0, idx: 0, n: 4 })));
|
|
ok('drop explains space', /move 1/.test(g.dropBlocker({ kind: 'col', i: 0, idx: 0, n: 4 }, { x: colX(1), y: TAB_TOP }) ?? ''));
|
|
ok('drop explains colours', /goes on a red 6/.test(g.dropBlocker({ kind: 'col', i: 0, idx: 3, n: 1 }, { x: colX(2), y: TAB_TOP }) ?? ''));
|
|
ok('drop explains the foundation', /spades need the Ace/.test(g.dropBlocker({ kind: 'col', i: 0, idx: 3, n: 1 }, foundPose(0)) ?? ''));
|
|
ok('drop explains a taken cell', /taken/.test(g.dropBlocker({ kind: 'col', i: 0, idx: 3, n: 1 }, cellPose(1)) ?? ''));
|
|
// auto-play hook
|
|
g.gs = pos({ cols: ['5s Ac'], found: {} });
|
|
ok('auto-play offers the safe ace', g.nextAutoMove()?.to.kind === 'found');
|
|
g.settings.autoPlay = false;
|
|
ok('auto-play off → nothing', g.nextAutoMove() === null);
|
|
g.finishing = true;
|
|
ok('finishing always plays home', g.nextAutoMove()?.to.kind === 'found');
|
|
g.finishing = false;
|
|
// fallback hint is a legal move
|
|
g.gs = FreecellEngine.fromDeal(9);
|
|
const fb = g.fallbackMove();
|
|
ok('fallback hint is legal', fb && g.gs.isLegal(fb));
|
|
// the layout lists all 52 cards
|
|
const { visible } = g.computeLayout();
|
|
ok('layout places all 52 cards', visible.size === 52);
|
|
ok('layout poses are flat (q = 1)', [...visible.values()].every(v => v.pose.q === 1));
|
|
}
|
|
|
|
// ── Desk layout ──────────────────────────────────────────────────────────────
|
|
section('Desk layout');
|
|
{
|
|
const huds = hudRects();
|
|
const rectsOverlap = (a, b) => a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1;
|
|
let fits = true, clear = true, onScreen = true, minStep = Infinity;
|
|
for (let c = 0; c < 8; c++) {
|
|
for (let n = 1; n <= 19; n++) {
|
|
const ps = columnPosesFor(c, n);
|
|
const last = cardBounds(ps[n - 1]);
|
|
if (last.y1 > MAX_BOTTOM + 0.5) fits = false;
|
|
for (const p of ps) {
|
|
const b = cardBounds(p);
|
|
if (b.x0 < 0 || b.x1 > W || b.y0 < 0 || b.y1 > H) onScreen = false;
|
|
for (const h of huds) if (rectsOverlap(b, h.r)) clear = false;
|
|
}
|
|
if (n > 1) minStep = Math.min(minStep, ps[1].y - ps[0].y);
|
|
}
|
|
}
|
|
ok('19-card columns fit above the bottom edge', fits);
|
|
ok('column cards never sit under the HUD', clear);
|
|
ok('column cards stay on screen', onScreen);
|
|
ok('fan step stays readable (≥ 25 px)', minStep >= 25, `${minStep.toFixed(1)}`);
|
|
const slotsClear = [0, 1, 2, 3].every(i => huds.every(h => !rectsOverlap(cardBounds(cellPose(i)), h.r) && !rectsOverlap(cardBounds(foundPose(i)), h.r)));
|
|
ok('cells + foundations clear of the HUD', slotsClear);
|
|
let zonesApart = true;
|
|
for (let a = 0; a < 8; a++) for (let b = a + 1; b < 8; b++) if (rectsOverlap(columnZone(a), columnZone(b))) zonesApart = false;
|
|
ok('column drop zones don\'t overlap', zonesApart);
|
|
let slotZones = true;
|
|
const zs = [0, 1, 2, 3].flatMap(i => [cellZone(i), foundZone(i)]);
|
|
for (let a = 0; a < zs.length; a++) for (let b = a + 1; b < zs.length; b++) if (rectsOverlap(zs[a], zs[b])) slotZones = false;
|
|
ok('cell + foundation drop zones don\'t overlap', slotZones);
|
|
ok('cards sit on the blotter', [0, 7].every(c => { const b = cardBounds(columnPosesFor(c, 1)[0]); return b.x0 >= BLOTTER.x0 && b.x1 <= BLOTTER.x1; }));
|
|
ok('the deck sits off the blotter', cardBounds(DECK).x1 < BLOTTER.x0);
|
|
ok('foundation pile grows but stays put', Math.abs(foundCardPose(0, 12).y - foundPose(0).y) <= 3);
|
|
const sq = columnPoses(25, null, { x: 100, top: 100, s: 1, maxBottom: 600, step: 34, minStep: 16 });
|
|
ok('columnPoses squeezes long columns', sq[24].y + 134 / 2 <= 600 + 0.5);
|
|
const fd = columnPoses(6, [false, false, false, true, true, true], { x: 0, top: 0, s: 1, step: 30, downStep: 10 });
|
|
ok('face-down cards use the tighter step', fd[1].y - fd[0].y === 10 && fd[4].y - fd[3].y === 30);
|
|
ok('card scale is the desk scale', Math.abs(CW - 96 * S) < 0.01 && Math.abs(CH - 134 * S) < 0.01);
|
|
}
|
|
|
|
// ── Records ──────────────────────────────────────────────────────────────────
|
|
section('Records (SolitaireStats)');
|
|
{
|
|
const mem = new Map();
|
|
const store = { getItem: (k) => mem.get(k) ?? null, setItem: (k, v) => mem.set(k, v) };
|
|
recordGame('t', { won: true, time: 90000, moves: 110 }, store);
|
|
let r = recordGame('t', { won: true, time: 80000, moves: 120 }, store);
|
|
ok('second win: streak 2', r.stats.streak === 2 && r.stats.bestStreak === 2);
|
|
ok('faster time is a new best', r.newBest.time === true && r.stats.bestTime === 80000);
|
|
ok('more moves is not a best', !r.newBest.moves && r.stats.fewestMoves === 110);
|
|
r = recordGame('t', { won: false }, store);
|
|
ok('a loss resets the streak, keeps the best', r.stats.streak === 0 && r.stats.bestStreak === 2);
|
|
const st = loadStats('t', 'default', store);
|
|
ok('played/won tallied', st.played === 3 && st.won === 2);
|
|
ok('recent list newest-first', st.recent[0].won === false && st.recent.length === 3);
|
|
ok('modes are separate', loadStats('t', 'other', store).played === 0);
|
|
ok('first best isn\'t "beaten"', recordBest('t', 'golf', 12, {}, store) === false);
|
|
ok('a lower score beats it', recordBest('t', 'golf', 8, {}, store) === true);
|
|
ok('a higher one doesn\'t', recordBest('t', 'golf', 20, {}, store) === false);
|
|
ok('formatTime', formatTime(65000) === '1:05' && formatTime(3725000) === '1:02:05' && formatTime(null) === '—');
|
|
ok('no storage → no crash', (() => { try { recordGame('x', { won: true }, { getItem() { throw new Error('nope'); }, setItem() { throw new Error('nope'); } }); return true; } catch { return false; } })());
|
|
}
|
|
|
|
console.log(`\n${pass} passed, ${fail} failed`);
|
|
process.exit(fail ? 1 : 0);
|