fertig-classic-games/tools/verifyMahjong.js

581 lines
31 KiB
JavaScript

// Headless verification for Mahjong (Hong Kong style).
// node tools/verifyMahjong.js [--quick] [--ladder]
// Exits non-zero on any failure.
//
// 1. Tile catalog: 144-tile wall, label assets exist on disk.
// 2. Faan evaluator fixtures: known hands score the expected faan rows,
// including limit hands, contextual faan and house-rule caps.
// 3. Payments: zero-sum, points ladder monotonic and capped.
// 4. Robbing the kong: a forced scenario end to end.
// 5. Wall geometry: dice break, every stack holds exactly two tiles.
// 6. Advisor: waits, unseen counts and discard advice agree with brute force.
// 7. Layout: every slot lands on the table, rivers never overlap.
// 8. AI self-play under several house rules, with per-step invariants (tile
// conservation, hand sizes, legal claims, minimum faan, scores sum to the
// stakes, termination) AND the tile ledger checked against the engine.
// 9. (--ladder) skill ladder: 3 beats 2 beats 1 over mirrored seats.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
TILES, buildWall, BASE_POINTS, LIMIT_FAAN, MIN_FAAN,
} from '../src/games/mahjong/MahjongData.js';
import {
createInitialState, dealHand, discardTile, claimOptionsFor, resolveClaims,
selfActions, declareKong, declareWin, startNextHand, isGameOver, getWinners,
counts34, decompose, isThirteenOrphans, canWinWith, winningTiles, shanten,
evaluateWin,
} from '../src/games/mahjong/MahjongLogic.js';
import {
chooseDiscard, chooseClaim, chooseSelfAction,
} from '../src/games/mahjong/MahjongAI.js';
import { Ledger } from '../src/games/mahjong/MahjongLedger.js';
import {
unseenCounts, waitsOf, discardAdvice, dangerMap, patternCompass, readTable,
} from '../src/games/mahjong/MahjongAdvisor.js';
import * as Lay from '../src/games/mahjong/MahjongLayout.js';
import { stackOfIndex, wallRemaining } from '../src/games/mahjong/MahjongLogic.js';
const QUICK = process.argv.includes('--quick');
const LADDER = process.argv.includes('--ladder');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const IMG_DIR = path.join(__dirname, '../assets/images/mahjong');
let failures = 0;
function check(ok, msg) {
if (!ok) { failures++; console.error(` ✗ ${msg}`); }
return ok;
}
// kind shorthands for fixtures
const b = (n) => n - 1, c = (n) => 9 + n - 1, ch = (n) => 18 + n - 1;
const E = 27, S = 28, W = 29, N = 30, R = 31, G = 32, Wh = 33;
// ── 1. Tile catalog ──────────────────────────────────────────────────────────
console.log('Tile catalog:');
check(TILES.length === 42, `kind count ${TILES.length}, expected 42`);
const wall = buildWall();
check(wall.length === 144, `wall ${wall.length} tiles, expected 144`);
const wc = new Array(42).fill(0);
for (const k of wall) wc[k]++;
for (let k = 0; k < 34; k++) check(wc[k] === 4, `kind ${k} has ${wc[k]} copies, expected 4`);
for (let k = 34; k < 42; k++) check(wc[k] === 1, `bonus kind ${k} has ${wc[k]} copies, expected 1`);
for (const t of TILES) {
if (!t.label) continue; // white dragon is drawn procedurally
const file = path.join(IMG_DIR, `${t.label.replace(/^mahjong-/, '')}.png`);
check(fs.existsSync(file), `missing label asset for ${t.id}: ${file}`);
}
console.log(' ok');
// ── 2. Faan fixtures ─────────────────────────────────────────────────────────
// Build a minimal state around one player's completed hand. For discard wins
// `hand` excludes the winning tile; for self-draws it includes it.
function fixtureState({ hand, melds = [], bonus = [], seat = 0, dealer = 0,
byDiscard, winTile, lastKong = false, wallEmpty = false, opts, ctx = {}, from }) {
const players = [];
for (let s = 0; s < 4; s++) {
players.push({ name: `P${s + 1}`, seat: s, score: 0, skill: 3, isAI: s !== 0,
hand: [], melds: [], bonus: [] });
}
players[seat] = { ...players[seat], hand: hand.slice(), melds, bonus };
return {
players, dealer, roundWind: 0,
wallPos: wallEmpty ? 1 : 0, wallEnd: wallEmpty ? 0 : 90,
lastDrawWasKongReplacement: lastKong,
lastDiscard: byDiscard ? { kind: winTile, from: from ?? (seat + 1) % 4, rob: !!ctx.rob } : null,
opts: opts ?? { minFaan: 1, faanCap: 13, bonusTiles: true },
claimCount: ctx.claimCount ?? 3, kongCount: ctx.kongCount ?? 0, discardCount: ctx.discardCount ?? 9,
};
}
function checkFixture(name, args, expectFaan, mustHave = [], mustNotHave = []) {
const state = fixtureState(args);
const res = evaluateWin(state, args.seat ?? 0, args.winTile, !!args.byDiscard);
const ids = res.faanList.map((r) => r.id);
check(res.faan === expectFaan, `${name}: faan ${res.faan}, expected ${expectFaan} [${ids.join(', ')}]`);
for (const id of mustHave) check(ids.includes(id), `${name}: missing faan row '${id}'`);
for (const id of mustNotHave) check(!ids.includes(id), `${name}: unexpected faan row '${id}'`);
check(res.payments.reduce((a, x) => a + x, 0) === 0, `${name}: payments not zero-sum`);
return res;
}
console.log('Faan fixtures:');
const exposedPung = (k, from = 1) => ({ type: 'pung', kinds: [k, k, k], concealed: false, from });
checkFixture('thirteen orphans',
{ hand: [b(1), b(1), b(9), c(1), c(9), ch(1), ch(9), E, S, W, N, R, G, Wh], byDiscard: false, winTile: b(1) },
13, ['thirteen-orphans']);
checkFixture('pure one suit',
{ hand: [b(2), b(2), b(2), b(3), b(4), b(5), b(5), b(6), b(7), b(7), b(8), b(9), b(9)],
byDiscard: true, winTile: b(9) },
8, ['pure-one-suit', 'concealed', 'no-bonus'], ['mixed-one-suit']);
checkFixture('nine gates (limit replaces every other row)',
{ hand: [b(1), b(1), b(1), b(2), b(3), b(4), b(4), b(5), b(6), b(7), b(8), b(9), b(9)],
byDiscard: true, winTile: b(9) },
13, ['nine-gates'], ['pure-one-suit', 'concealed', 'no-bonus']);
checkFixture('mixed one suit + round wind',
{ hand: [c(1), c(2), c(3), c(4), c(5), c(6), c(7), c(8), c(9), E, E, R, R],
seat: 1, byDiscard: true, winTile: E },
6, ['mixed-one-suit', 'round-wind', 'concealed', 'no-bonus'], ['seat-wind', 'pure-one-suit']);
checkFixture('all pungs (exposed)',
{ hand: [b(2), b(2), c(5), c(5), c(5), ch(7), ch(7), ch(7), b(9), b(9)],
melds: [exposedPung(N)], seat: 2, byDiscard: true, winTile: b(2) },
4, ['all-pungs', 'no-bonus'], ['concealed', 'seat-wind', 'round-wind']);
checkFixture('common hand',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9)],
byDiscard: true, winTile: c(9) },
3, ['common-hand', 'concealed', 'no-bonus']);
checkFixture('chicken hand scores zero',
{ hand: [c(2), c(3), c(4), c(5), c(6), c(7), ch(3), ch(4), ch(8), ch(8)],
melds: [exposedPung(b(2))], bonus: [35], byDiscard: true, winTile: ch(5) },
0, [], ['no-bonus', 'seat-flower', 'common-hand']);
checkFixture('dealer east pung stacks seat + round wind',
{ hand: [b(2), b(3), b(5), b(6), b(7), ch(3), ch(3), ch(3), c(9), c(9)],
melds: [exposedPung(E)], seat: 0, dealer: 0, byDiscard: true, winTile: b(4) },
3, ['seat-wind', 'round-wind', 'no-bonus']);
checkFixture('great dragons',
{ hand: [Wh, Wh, Wh, b(2), b(3), c(5), c(5)],
melds: [exposedPung(R), exposedPung(G)], byDiscard: true, winTile: b(4) },
9, ['great-dragons', 'no-bonus'], ['dragon-pung', 'small-dragons']);
checkFixture('small dragons',
{ hand: [Wh, Wh, b(2), b(3), b(4), c(6), c(7)],
melds: [exposedPung(R), exposedPung(G)], byDiscard: true, winTile: c(8) },
6, ['small-dragons', 'no-bonus'], ['dragon-pung', 'great-dragons']);
checkFixture('all honors capped at limit',
{ hand: [E, E, E, S, S, S, R, R, R, G, G, G, N, N], byDiscard: false, winTile: N },
13, ['all-honors'], ['all-pungs', 'mixed-one-suit']);
checkFixture('self draw context',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9), c(9)],
byDiscard: false, winTile: c(9) },
4, ['common-hand', 'self-draw', 'concealed', 'no-bonus']);
checkFixture('kong replacement context',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9), c(9)],
byDiscard: false, winTile: c(9), lastKong: true },
5, ['kong-draw', 'self-draw']);
checkFixture('ambiguous 111222333 read as chows',
{ hand: [b(1), b(1), b(1), b(2), b(2), b(2), b(3), b(3), b(3), ch(7), ch(8), ch(9), c(5)],
byDiscard: true, winTile: c(5) },
3, ['common-hand', 'concealed', 'no-bonus']);
checkFixture('flowers: own + full set',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9)],
bonus: [34, 35, 36, 37], byDiscard: true, winTile: c(9) },
5, ['common-hand', 'concealed', 'seat-flower', 'flower-set'], ['no-bonus']);
const concealedKong = (k) => ({ type: 'kong', kinds: [k, k, k, k], concealed: true, from: null });
const exposedKong = (k) => ({ type: 'kong', kinds: [k, k, k, k], concealed: false, from: 1 });
checkFixture('all terminals (limit)',
{ hand: [b(1), b(1), b(1), b(9), b(9), b(9), c(1), c(1), c(1), ch(9), ch(9), ch(9), c(9)], byDiscard: true, winTile: c(9) },
13, ['all-terminals'], ['all-pungs', 'concealed']);
checkFixture('mixed terminals + all pungs',
{ hand: [b(1), b(1), b(1), c(9), c(9), c(9), N, N, N, S], melds: [exposedPung(ch(1))], seat: 2, byDiscard: true, winTile: S },
5, ['mixed-terminals', 'all-pungs', 'no-bonus'], ['all-terminals']);
checkFixture('four kongs (limit)',
{ hand: [c(5)], melds: [concealedKong(b(2)), exposedKong(b(7)), exposedKong(ch(3)), concealedKong(c(8))], byDiscard: true, winTile: c(5) },
13, ['four-kongs']);
checkFixture('four concealed pungs, self-drawn (limit)',
{ hand: [b(2), b(2), b(2), c(4), c(4), c(4), ch(6), ch(6), ch(6), b(8), b(8), b(8), c(1), c(1)], byDiscard: false, winTile: b(8) },
13, ['four-concealed-pungs']);
checkFixture('four concealed pungs on a discard needs the pair wait',
{ hand: [b(2), b(2), b(2), c(4), c(4), c(4), ch(6), ch(6), ch(6), b(8), b(8), b(8), c(1)], byDiscard: true, winTile: c(1) },
13, ['four-concealed-pungs']);
checkFixture('…but not when the discard completes a pung',
{ hand: [b(2), b(2), b(2), c(4), c(4), c(4), ch(6), ch(6), ch(6), b(8), b(8), c(1), c(1)], byDiscard: true, winTile: b(8) },
5, ['all-pungs', 'concealed', 'no-bonus'], ['four-concealed-pungs']);
checkFixture('heavenly hand',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9), c(9)], byDiscard: false, winTile: c(9),
ctx: { claimCount: 0, kongCount: 0, discardCount: 0 } },
13, ['heavenly-hand']);
checkFixture('earthly hand (dealer\'s first discard)',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9)], seat: 1, byDiscard: true, winTile: c(9), from: 0,
ctx: { claimCount: 0, kongCount: 0, discardCount: 1 } },
13, ['earthly-hand']);
checkFixture('robbing the kong is a faan',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9)], byDiscard: true, winTile: c(9), ctx: { rob: true } },
4, ['rob-kong', 'common-hand', 'concealed', 'no-bonus']);
checkFixture('last discard after the wall runs out',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9)], byDiscard: true, winTile: c(9), wallEmpty: true },
4, ['last-discard'], ['last-tile']);
checkFixture('a 10-faan cap makes a limit hand worth 10',
{ hand: [b(1), b(1), b(9), c(1), c(9), ch(1), ch(9), E, S, W, N, R, G, Wh], byDiscard: false, winTile: b(1), opts: { minFaan: 1, faanCap: 10, bonusTiles: true } },
10, ['thirteen-orphans']);
checkFixture('no flowers in play: no "no bonus" faan',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9)], byDiscard: true, winTile: c(9), opts: { minFaan: 1, faanCap: 13, bonusTiles: false } },
2, ['common-hand', 'concealed'], ['no-bonus']);
// decomposer / shanten sanity
{
const tenpai = counts34([b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9)]);
check(shanten(tenpai, 0) === 0, `tenpai hand shanten ${shanten(tenpai, 0)}, expected 0`);
const complete = counts34([b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9), c(9)]);
check(shanten(complete, 0) === -1, `complete hand shanten ${shanten(complete, 0)}, expected -1`);
check(decompose(complete, 4).length > 0, 'complete hand fails to decompose');
const waits = winningTiles([b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9)], []);
check(waits.length === 1 && waits[0] === c(9), `waits [${waits.join(',')}], expected [${c(9)}]`);
check(canWinWith([b(1), b(1), b(9), c(1), c(9), ch(1), ch(9), E, S, W, N, R, G], [], Wh),
'thirteen orphans not recognised by canWinWith');
check(isThirteenOrphans(counts34([b(1), b(1), b(9), c(1), c(9), ch(1), ch(9), E, S, W, N, R, G, Wh])),
'isThirteenOrphans rejects a valid hand');
}
console.log(` ${failures === 0 ? 'ok' : 'see failures above'}`);
// ── 3. Points ladder ─────────────────────────────────────────────────────────
console.log('Points ladder:');
check(BASE_POINTS.length === LIMIT_FAAN + 1, 'BASE_POINTS does not cover 0..LIMIT_FAAN');
for (let i = 1; i < BASE_POINTS.length; i++) {
check(BASE_POINTS[i] > BASE_POINTS[i - 1], `BASE_POINTS not monotonic at faan ${i}`);
}
console.log(' ok');
// ── 4. Robbing the kong ──────────────────────────────────────────────────────
console.log('Robbing the kong:');
{
const st = createInitialState({ names: ['A', 'B', 'C', 'D'], seed: 4242 });
const sumBefore = st.players.reduce((a, p) => a + p.score, 0);
// seat 0 (on turn) holds an exposed pung of 5 Circle and the fourth copy;
// seat 1 is ready on 5 Circle (4-6 circle chow wait).
st.players[0].hand = [c(5), b(1), b(2), b(3), b(4), b(5), b(6), ch(1), ch(2), ch(3), E];
st.players[0].melds = [{ type: 'pung', kinds: [c(5), c(5), c(5)], concealed: false, from: 2 }];
st.players[1].hand = [c(4), c(6), b(7), b(8), b(9), ch(4), ch(5), ch(6), ch(7), ch(8), ch(9), S, S];
st.players[1].melds = [];
st.turn = 0; st.phase = 'awaitDiscard'; st.drawnTile = c(5);
const acts = selfActions(st);
check(acts.addedKongs.includes(c(5)), 'added kong not offered');
check(declareKong(st, { type: 'added', kind: c(5) }), 'added kong refused');
check(st.phase === 'awaitRob', `phase after a robbable kong is ${st.phase}`);
const o1 = claimOptionsFor(st, 1);
check(!!o1?.win && !o1.pung && !o1.chows.length, 'robber should be offered the win only');
check(!claimOptionsFor(st, 0), 'the kong owner cannot rob himself');
resolveClaims(st, [{ seat: 1, claim: { type: 'win' } }]);
check(st.phase === 'handOver' && st.result.winner === 1 && st.result.rob, 'rob did not win the hand');
check(st.result.faanList.some((r) => r.id === 'rob-kong'), 'rob-kong faan missing');
check(st.players[0].melds[0].type === 'pung' && st.players[0].melds[0].kinds.length === 3, 'robbed kong did not revert to a pung');
check(st.result.payments[0] < 0 && st.result.payments[2] === 0, 'the kong owner should pay alone');
check(st.players.reduce((a, p) => a + p.score, 0) === sumBefore, 'rob payments not zero-sum');
// with the house rule off the kong just stands
const st2 = createInitialState({ names: ['A', 'B', 'C', 'D'], seed: 4242, opts: { robKong: false } });
st2.players[0].hand = st.players[0].hand.slice(); st2.players[0].hand.push(c(5));
st2.players[0].hand = [c(5), b(1), b(2), b(3), b(4), b(5), b(6), ch(1), ch(2), ch(3), E];
st2.players[0].melds = [{ type: 'pung', kinds: [c(5), c(5), c(5)], concealed: false, from: 2 }];
st2.players[1].hand = [c(4), c(6), b(7), b(8), b(9), ch(4), ch(5), ch(6), ch(7), ch(8), ch(9), S, S];
st2.turn = 0; st2.phase = 'awaitDiscard'; st2.drawnTile = c(5);
declareKong(st2, { type: 'added', kind: c(5) });
check(st2.phase === 'awaitDiscard' || st2.phase === 'handOver', `robKong off: phase ${st2.phase}`);
}
console.log(` ${failures === 0 ? 'ok' : 'see failures above'}`);
// ── 5. Wall geometry ─────────────────────────────────────────────────────────
console.log('Wall geometry:');
for (const bonusTiles of [true, false]) {
for (let seed = 1; seed <= 30; seed++) {
const st = createInitialState({ seed, opts: { bonusTiles } });
const n = st.wall.length;
check(n === (bonusTiles ? 144 : 136), `wall length ${n}`);
check(st.stacks === n / 2, 'stack count');
const per = new Map();
for (let i = 0; i < n; i++) {
const info = stackOfIndex(st, i);
check(info.stack >= 0 && info.stack < st.stacks && info.j >= 0 && info.j < st.stacks / 4, `bad stack for ${i}`);
per.set(info.stack, (per.get(info.stack) ?? 0) + 1);
}
check(per.size === st.stacks && [...per.values()].every((v) => v === 2), 'every stack must hold two tiles');
const total = st.dice.reduce((a, d) => a + d, 0);
check(st.dice.every((d) => d >= 1 && d <= 6), 'dice out of range');
check(st.breakWall === (st.dealer + total - 1) % 4, 'wrong wall broken');
check(stackOfIndex(st, 0).stack === st.breakStack, 'first tile not at the break');
}
}
console.log(` ${failures === 0 ? 'ok' : 'see failures above'}`);
// ── 6. Advisor ───────────────────────────────────────────────────────────────
console.log('Advisor:');
{
let checked = 0;
for (let seed = 1; seed <= (QUICK ? 6 : 16); seed++) {
const st = createInitialState({ seed: 500 + seed, skills: { 0: 3, 1: 3, 2: 3, 3: 3 } });
for (let step = 0; step < 400 && st.phase !== 'handOver'; step++) {
if (st.phase === 'awaitDiscard') {
const seat = st.turn;
if (step % 5 === 0) {
const adv = discardAdvice(st, seat);
const p = st.players[seat];
for (const row of adv.slice(0, 4)) {
const cc = counts34(p.hand); cc[row.kind]--;
check(shanten(cc, p.melds.length) === row.shanten, `advice shanten wrong for kind ${row.kind}`);
check(row.danger >= 0 && row.danger <= 1, 'danger out of range');
}
for (let i = 1; i < adv.length; i++) check(adv[i - 1].shanten <= adv[i].shanten, 'advice not sorted by shanten');
const un = unseenCounts(st, seat);
check(un.every((x) => x >= 0 && x <= 4), 'unseen out of range');
const comp = patternCompass(st, seat);
check(comp.sure >= 0 && Array.isArray(comp.items), 'compass malformed');
check(readTable(st, seat).every((r) => r.threat >= 0 && r.threat <= 1), 'threat out of range');
check(dangerMap(st, seat).every((x) => x >= 0 && x <= 1), 'danger map out of range');
checked++;
}
const sa = chooseSelfAction(st, st.turn, selfActions(st), 3);
if (sa?.type === 'win') { declareWin(st, st.turn, { byDiscard: false }); break; }
if (sa?.type === 'kong') { declareKong(st, sa.spec); continue; }
discardTile(st, chooseDiscard(st, st.turn, 3));
continue;
}
// between turns: the waits helper must agree with winningTiles
for (let seat = 0; seat < 4; seat++) {
const p = st.players[seat];
if (p.hand.length !== 13 - 3 * p.melds.length) continue;
const w = waitsOf(st, seat).map((x) => x.kind).join();
check(w === winningTiles(p.hand, p.melds).join(), `waitsOf disagrees with winningTiles for seat ${seat}`);
}
const intents = [];
for (let seat = 0; seat < 4; seat++) {
const o = claimOptionsFor(st, seat);
if (o) { const cl = chooseClaim(st, seat, o, 3); if (cl) intents.push({ seat, claim: cl }); }
}
resolveClaims(st, intents);
}
}
console.log(` ${failures === 0 ? `ok (${checked} positions)` : 'see failures above'}`);
}
// ── 7. Layout ────────────────────────────────────────────────────────────────
console.log('Layout:');
{
const inTable = (p) => {
const q = Lay.unproject(p.x, p.y);
return Math.abs(q.x) <= 1.0 && Math.abs(q.z) <= 1.0;
};
const boxes = [];
for (let seat = 0; seat < 4; seat++) {
for (let i = 0; i < 24; i++) {
const p = Lay.riverPose(seat, i);
check(inTable(p), `river ${seat}/${i} off the table`);
// footprint in table space (screen boxes would be inflated by perspective)
const row = Math.min(3, Math.floor(i / Lay.RIVER_COLS)), col = row === 3 ? i - 18 : i % Lay.RIVER_COLS;
const w = Lay.world(seat, (col - (Lay.RIVER_COLS - 1) / 2) * (Lay.TW + Lay.GAP), Lay.RIVER_D0 + Lay.TD / 2 + row * (Lay.TD + Lay.GAP));
const hx = (seat % 2 ? Lay.TD : Lay.TW) / 2, hz = (seat % 2 ? Lay.TW : Lay.TD) / 2;
boxes.push({ seat, x0: w.x - hx, x1: w.x + hx, y0: w.z - hz, y1: w.z + hz });
}
for (let j = 0; j < 18; j++) check(inTable(Lay.wallTilePose(seat, j, 18, 0)), `wall ${seat}/${j} off the table`);
for (let i = 0; i < 14; i++) check(inTable(Lay.revealPose(seat, i, 14)), `reveal ${seat}/${i} off the table`);
}
// rivers of different seats never overlap (first 24 tiles each)
let overlaps = 0;
for (const a of boxes) for (const b2 of boxes) {
if (a.seat >= b2.seat) continue;
if (a.x0 < b2.x1 && b2.x0 < a.x1 && a.y0 < b2.y1 && b2.y0 < a.y1) overlaps++;
}
check(overlaps === 0, `${overlaps} river tiles overlap another seat's river`);
// your rack fits between the side panels
const rack = Lay.humanRack(Array.from({ length: 13 }, (_, i) => i), 13);
const xs = [...rack.values()].map((p) => p.x);
check(Math.min(...xs) - Lay.HAND.w / 2 > Lay.SEAT_PANELS[0].x + Lay.SEAT_PANELS[0].w, 'rack runs under your seat panel');
check(Math.max(...xs) + Lay.HAND.w / 2 < Lay.DOCK.x, 'rack runs under the dock');
}
console.log(` ${failures === 0 ? 'ok' : 'see failures above'}`);
// ── 8. AI self-play + ledger ─────────────────────────────────────────────────
function tileConservation(state) {
let total = state.wallEnd - state.wallPos + 1;
for (const p of state.players) {
total += p.hand.length + p.bonus.length;
for (const m of p.melds) total += m.kinds.length;
}
for (const river of state.discards) total += river.length;
return total;
}
function checkInvariants(state, tag) {
if (state.phase === 'handOver' || state.phase === 'gameOver') return;
const total = tileConservation(state);
check(total === state.wall.length, `${tag}: ${total} tiles accounted for, expected ${state.wall.length}`);
for (const p of state.players) {
const drawing = state.phase === 'awaitDiscard' && state.turn === p.seat;
const expected = (drawing ? 14 : 13) - 3 * p.melds.length;
check(p.hand.length === expected,
`${tag}: seat ${p.seat} hand ${p.hand.length}, expected ${expected} (${state.phase})`);
}
}
const sortedJoin = (a) => a.slice().sort((x, y) => x - y).join();
function checkLedger(state, led, tag) {
for (let s = 0; s < 4; s++) {
const p = state.players[s];
if (sortedJoin(led.hand[s].map((id) => led.kindOf(id))) !== sortedJoin(p.hand)) { check(false, `${tag}: ledger hand ${s} differs`); return; }
if (led.river[s].map((id) => led.kindOf(id)).join() !== state.discards[s].join()) { check(false, `${tag}: ledger river ${s} differs`); return; }
if (sortedJoin(led.bonus[s].map((id) => led.kindOf(id))) !== sortedJoin(p.bonus)) { check(false, `${tag}: ledger bonus ${s} differs`); return; }
if (led.melds[s].length !== p.melds.length) { check(false, `${tag}: ledger melds ${s} differ`); return; }
led.melds[s].forEach((m, i) => {
check(sortedJoin(m.ids.map((id) => led.kindOf(id))) === sortedJoin(p.melds[i].kinds), `${tag}: meld ${s}/${i} kinds differ`);
});
}
if (state.phase !== 'handOver' && state.phase !== 'gameOver') {
check(led.wall.size === wallRemaining(state), `${tag}: ledger wall ${led.wall.size} vs ${wallRemaining(state)}`);
for (const id of led.wall) check(id >= state.wallPos && id <= state.wallEnd, `${tag}: id ${id} outside the live wall`);
}
}
function playSession(seed, opts, skillsIn) {
const skills = skillsIn ?? { 0: 1 + (seed % 5), 1: 1 + ((seed >> 2) % 5), 2: 3, 3: 5 };
const state = createInitialState({ names: ['A', 'B', 'C', 'D'], skills, seed, opts });
const led = new Ledger();
let li = 0;
const sync = (tag) => { while (li < state.log.length) led.apply(state.log[li++]); checkLedger(state, led, tag); };
const dealersSeen = new Set();
let hands = 0, wins = 0, draws = 0, claims = 0, kongs = 0, robs = 0;
let guard = 100000;
sync(`seed ${seed} start`);
while (!isGameOver(state) && guard-- > 0) {
const tag = `seed ${seed} hand ${state.handNumber}`;
checkInvariants(state, tag);
if (state.phase === 'handOver') {
dealersSeen.add(`${state.roundWind}:${state.dealer}`);
hands++;
const r = state.result;
if (r.type === 'win') {
wins++;
if (r.rob) robs++;
check(r.faan >= state.opts.minFaan, `seed ${seed}: win below minimum faan (${r.faan})`);
check(r.faan <= state.opts.faanCap, `seed ${seed}: win above the cap (${r.faan})`);
check(r.payments.reduce((a, x) => a + x, 0) === 0, `seed ${seed}: payments not zero-sum`);
check(led.winId != null && led.hand[r.winner].includes(led.winId), `seed ${seed}: ledger lost the winning tile`);
} else {
draws++;
}
const sum = state.players.reduce((a, p) => a + p.score, 0);
check(sum === 4 * state.opts.stake, `seed ${seed}: cumulative scores sum to ${sum}, expected ${4 * state.opts.stake}`);
startNextHand(state);
sync(`${tag} next`);
continue;
}
if (state.phase === 'awaitDiscard') {
const seat = state.turn;
const p = state.players[seat];
const acts = selfActions(state);
const sa = chooseSelfAction(state, seat, acts, p.skill);
if (sa?.type === 'win') {
check(acts.canWin, `seed ${seed}: AI declared an unoffered win`);
declareWin(state, seat, { byDiscard: false });
sync(`${tag} self-win`);
continue;
}
if (sa?.type === 'kong') {
kongs++;
check(declareKong(state, sa.spec), `seed ${seed}: illegal kong ${JSON.stringify(sa.spec)}`);
sync(`${tag} kong`);
continue;
}
const d = chooseDiscard(state, seat, p.skill);
check(p.hand.includes(d), `seed ${seed}: AI discarded unheld kind ${d}`);
discardTile(state, d);
sync(`${tag} discard`);
continue;
}
if (state.phase === 'awaitClaims' || state.phase === 'awaitRob') {
const from = state.lastDiscard.from;
const intents = [];
for (let seat = 0; seat < 4; seat++) {
const options = claimOptionsFor(state, seat);
if (!options) continue;
check(seat !== from, `seed ${seed}: discarder offered a claim`);
if (options.chows.length) {
check(state.phase === 'awaitClaims', `seed ${seed}: chow offered on a robbable kong`);
check(seat === (from + 1) % 4, `seed ${seed}: chow offered to non-left seat`);
}
const claim = chooseClaim(state, seat, options, state.players[seat].skill);
if (claim) intents.push({ seat, claim });
}
const { applied } = resolveClaims(state, intents);
if (applied && applied.claim.type !== 'win') claims++;
sync(`${tag} claims`);
continue;
}
check(false, `seed ${seed}: unknown phase ${state.phase}`);
break;
}
check(guard > 0, `seed ${seed}: session did not terminate`);
const rounds = state.opts.rounds;
check(dealersSeen.size >= 4 * rounds || guard <= 0, `seed ${seed}: only ${dealersSeen.size}/${4 * rounds} deals seen`);
check(getWinners(state).length >= 1, `seed ${seed}: no session winner`);
check(state.history.length === hands, `seed ${seed}: history has ${state.history.length} rows for ${hands} hands`);
return { hands, wins, draws, claims, kongs, robs };
}
const VARIANTS = [
['default rules', {}],
['minimum 3 faan, no flowers', { minFaan: 3, bonusTiles: false }],
['East + South, cap 10', { rounds: 2, faanCap: 10 }],
['no robbing, no stake, minimum 0', { robKong: false, stake: 0, minFaan: 0 }],
];
const PER = QUICK ? 4 : 12;
for (const [label, opts] of VARIANTS) {
console.log(`Self-play — ${label} (${PER} sessions, mixed skills):`);
let tHands = 0, tWins = 0, tDraws = 0, tClaims = 0, tKongs = 0, tRobs = 0;
const t0 = Date.now();
for (let g = 0; g < PER; g++) {
const r = playSession(1000 + g * 7919, opts);
tHands += r.hands; tWins += r.wins; tDraws += r.draws; tClaims += r.claims; tKongs += r.kongs; tRobs += r.robs;
}
const secs = ((Date.now() - t0) / 1000).toFixed(1);
console.log(` ${tHands} hands in ${secs}s — ${tWins} wins (${tRobs} robbed kongs), ${tDraws} drawn, ${tClaims} claims, ${tKongs} kongs`);
check(tWins > 0, `${label}: no hand was ever won`);
if (!opts.minFaan || opts.minFaan <= 1) check(tWins / Math.max(1, tHands) > 0.3, `${label}: only ${tWins}/${tHands} hands won`);
}
// ── 9. Skill ladder (optional, slow) ─────────────────────────────────────────
if (LADDER) {
console.log('Skill ladder (mirrored seats):');
const duel = (a, bSkill, sessions) => {
let delta = 0, hands = 0;
for (let g = 0; g < sessions; g++) {
for (let seat = 0; seat < 4; seat++) {
const skills = {};
for (let s2 = 0; s2 < 4; s2++) skills[s2] = s2 === seat ? a : bSkill;
const st = createInitialState({ names: ['A', 'B', 'C', 'D'], skills, seed: 77 + g * 104729 });
while (!isGameOver(st)) {
if (st.phase === 'handOver') { startNextHand(st); continue; }
if (st.phase === 'awaitDiscard') {
const sk = st.players[st.turn].skill;
const sa = chooseSelfAction(st, st.turn, selfActions(st), sk);
if (sa?.type === 'win') { declareWin(st, st.turn, { byDiscard: false }); continue; }
if (sa?.type === 'kong') { declareKong(st, sa.spec); continue; }
discardTile(st, chooseDiscard(st, st.turn, sk)); continue;
}
const ints = [];
for (let s2 = 0; s2 < 4; s2++) { const o = claimOptionsFor(st, s2); if (o) { const cl = chooseClaim(st, s2, o, st.players[s2].skill); if (cl) ints.push({ seat: s2, claim: cl }); } }
resolveClaims(st, ints);
}
delta += st.players[seat].score - st.opts.stake;
hands += st.history.length;
}
}
return delta / hands;
};
for (const [a, b2] of [[2, 1], [3, 2]]) {
const d = duel(a, b2, 10);
console.log(` skill ${a} vs three skill ${b2}: ${d >= 0 ? '+' : ''}${d.toFixed(2)} points per hand`);
check(d > 0, `skill ${a} should beat skill ${b2}`);
}
}
if (failures) {
console.error(`\nFAILED: ${failures} check(s).`);
process.exit(1);
}
console.log('\nAll Mahjong checks passed.');