Merge pull request '[sim-balance] Duel bots (heuristic, MC) and duel simulation harness' (#71) from night2/sim-balance/duel-harness into night/2026-11-17

This commit is contained in:
2026-11-18 16:13:50 +00:00
8 changed files with 968 additions and 0 deletions
+49
View File
@@ -0,0 +1,49 @@
// 40-card sim decks drawn from a card pool (the 236 real sample cards). Every card is unique (one NFT each),
// so decks sample without replacement. Archetypes skew the type or cost mix. Pure, seeded.
import { mulberry32 } from '../../shared/bots/index.ts';
export interface PoolCard { id: string; type: string; portal: string; cost: number; keywords: string[]; fame?: number }
export interface SimDeck<C extends PoolCard = PoolCard> { id: string; tags: string[]; cards: C[] }
export const ARCHETYPES = ['random', 'figure-heavy', 'doctrine-heavy', 'event-heavy', 'location-heavy', 'institution-heavy', 'low-curve', 'high-curve'] as const;
export type Archetype = typeof ARCHETYPES[number];
function weight(c: PoolCard, arch: Archetype): number {
switch (arch) {
case 'figure-heavy': return c.type === 'Figure' ? 8 : 1;
case 'doctrine-heavy': return c.type === 'Doctrine' ? 8 : 1;
case 'event-heavy': return c.type === 'Event' ? 12 : 1;
case 'location-heavy': return c.type === 'Location' ? 8 : 1;
case 'institution-heavy': return c.type === 'Institution' ? 10 : 1;
case 'low-curve': return c.cost <= 2 ? 8 : c.cost === 3 ? 3 : 0.3;
case 'high-curve': return c.cost >= 5 ? 8 : c.cost === 4 ? 3 : 0.5;
default: return 1;
}
}
/** Weighted sampling without replacement (Efraimidis–Spirakis keys). */
export function buildDeck<C extends PoolCard>(pool: C[], arch: Archetype, seed: number, size = 40): SimDeck<C> {
const rng = mulberry32(seed);
const keyed = pool.map(c => ({ c, k: Math.pow(rng(), 1 / Math.max(1e-6, weight(c, arch))) }));
keyed.sort((a, b) => b.k - a.k);
const cards = keyed.slice(0, Math.min(size, pool.length)).map(x => x.c);
return { id: `${arch}#${seed}`, tags: deckTags(cards, arch), cards };
}
export function deckTags(cards: PoolCard[], arch: string): string[] {
const count = (f: (c: PoolCard) => string) => { const m: Record<string, number> = {}; for (const c of cards) m[f(c)] = (m[f(c)] ?? 0) + 1; return m; };
const top = (m: Record<string, number>) => Object.entries(m).sort((a, b) => b[1] - a[1])[0]?.[0] ?? '?';
const avg = cards.reduce((t, c) => t + c.cost, 0) / (cards.length || 1);
const curve = avg < 2.6 ? 'low' : avg < 3.4 ? 'mid' : 'high';
return [`arch:${arch}`, `portal:${top(count(c => c.portal))}`, `curve:${curve}`, `mainType:${top(count(c => c.type))}`];
}
/** n decks: half random, the rest cycling through the skewed archetypes. */
export function deckSet<C extends PoolCard>(pool: C[], n: number, seed: number, size = 40): SimDeck<C>[] {
const out: SimDeck<C>[] = [];
for (let i = 0; i < n; i++) {
const arch: Archetype = i % 2 === 0 ? 'random' : ARCHETYPES[1 + ((i >> 1) % (ARCHETYPES.length - 1))];
out.push(buildDeck(pool, arch, (seed * 7919 + i * 104729) >>> 0, size));
}
return out;
}
+137
View File
@@ -0,0 +1,137 @@
// Duel balance simulation.
// npx tsx scripts/sim/duel-run.ts --engine duel --matches 2000 --workers 4 --out sim-out/duel [--rules '{"startingLife":18}']
// Writes <out>/<label>.jsonl, <out>/<label>.stats.json and <out>/<label>.md. Workers are capped at 4 (r350 memory).
import { fork } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { createWriteStream, mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { mulberry32 } from '../../shared/bots/index.ts';
import { makeDuelBot } from '../../shared/bots/duel-bots.ts';
import type { BotFn, DeckSpec, Seat } from '../../shared/bots/types.ts';
import { deckSet, type SimDeck } from './duel-decks.ts';
import type { DuelSim } from './duel-sim-types.ts';
import { aggregateDuel, duelMarkdown, type DuelRecord } from './duel-stats.ts';
export const MAX_WORKERS = 4;
export const MAX_ACTIONS = 3000;
const SAMPLE = fileURLToPath(new URL('../../docs/game/card-sample.json', import.meta.url));
export async function loadDuelSim(name: string, rules: Record<string, unknown> = {}): Promise<DuelSim<any, any>> {
if (name === 'standin') return (await import('./duel-standin-adapter.ts')).makeStandinSim(SAMPLE, rules as any);
if (name === 'duel') { const mod = './duel-core-sim.ts'; return (await import(mod)).makeDuelSim(SAMPLE, rules); }
throw new Error(`unknown duel engine ${name}`);
}
export function playDuel<S, A>(sim: DuelSim<S, A>, decks: [SimDeck, SimDeck], botNames: [string, string], seed: number, bots?: [BotFn<unknown, A>, BotFn<unknown, A>]): DuelRecord {
const t0 = performance.now();
const { engine } = sim;
const b = bots ?? [makeDuelBot(botNames[0], engine, sim.lens), makeDuelBot(botNames[1], engine, sim.lens)];
const rng = [mulberry32(seed ^ 0x9e3779b9), mulberry32(seed ^ 0x85ebca6b)];
const specs: [DeckSpec, DeckSpec] = [0, 1].map(i => ({ id: decks[i].id, tags: decks[i].tags, payload: sim.deckPayload(decks[i].cards) })) as [DeckSpec, DeckSpec];
let s = engine.createMatch('duel', specs, seed);
const first = (engine.firstSeat ? engine.firstSeat(s) : engine.toAct(s)) as Seat;
const played: [string[], string[]] = [[], []];
let actions = 0;
while (!engine.isOver(s) && actions < MAX_ACTIONS) {
const seat = engine.toAct(s);
const a = b[seat](engine.observe ? engine.observe(s, seat) : s, seat, rng[seat]);
for (const c of engine.cardsOf(s, a)) played[seat].push(c);
s = engine.applyAction(s, a);
actions++;
}
const truncated = !engine.isOver(s);
const res = truncated ? { winner: null, reason: 'action-cap' } : engine.result(s);
const turns = engine.turn(s);
return {
seed, bots: botNames, decks: [decks[0].id, decks[1].id], tags: [decks[0].tags, decks[1].tags],
first, winner: res.winner, reason: res.reason ?? 'none', turns, turnsEach: Math.ceil(turns / 2), actions, truncated,
// Clock model: 10 s of overhead per turn plus 4 s per atomic action (taps, plays, blocks).
minutes: (turns * 10 + actions * 4) / 60,
played, metrics: sim.metrics ? sim.metrics(s) : {}, ms: performance.now() - t0,
};
}
/** Bot pairings and their share of the schedule. Symmetric pairs carry the balance stats. */
export const DUEL_MIXES: Record<string, [string, string, number][]> = {
default: [['heuristic', 'heuristic', 0.7], ['mc-lite', 'mc-lite', 0.06], ['heuristic', 'mc-lite', 0.08], ['random', 'heuristic', 0.06], ['greedy', 'heuristic', 0.05], ['random', 'random', 0.05]],
fast: [['heuristic', 'heuristic', 0.9], ['random', 'heuristic', 0.05], ['greedy', 'heuristic', 0.05]],
skill: [['heuristic', 'mc', 0.4], ['random', 'heuristic', 0.2], ['greedy', 'heuristic', 0.2], ['heuristic', 'mc-lite', 0.2]],
};
interface Job { i: number; seed: number; decks: [number, number]; bots: [string, string] }
export function schedule(n: number, nDecks: number, baseSeed: number, mix: [string, string, number][]): Job[] {
const rng = mulberry32(baseSeed);
const total = mix.reduce((t, m) => t + m[2], 0);
return Array.from({ length: n }, (_, i) => {
let r = rng() * total, k = 0;
while (r > mix[k][2] && k < mix.length - 1) { r -= mix[k][2]; k++; }
const flip = rng() < 0.5;
let d0 = Math.floor(rng() * nDecks), d1 = Math.floor(rng() * nDecks);
if (d1 === d0) d1 = (d1 + 1) % nDecks;
return { i, seed: (baseSeed * 1000003 + i * 7919) >>> 0, decks: [d0, d1], bots: flip ? [mix[k][1], mix[k][0]] : [mix[k][0], mix[k][1]] };
});
}
function arg(name: string, def?: string): string | undefined { const i = process.argv.indexOf(`--${name}`); return i >= 0 ? process.argv[i + 1] : def; }
interface Ctx { engineName: string; rules: Record<string, unknown>; nDecks: number; deckSeed: number }
async function setup(ctx: Ctx) {
const sim = await loadDuelSim(ctx.engineName, ctx.rules);
const decks = deckSet(sim.pool, ctx.nDecks, ctx.deckSeed, Number(ctx.rules.deckSize ?? 40));
return { sim, decks };
}
function runJobs(sim: DuelSim<any, any>, decks: SimDeck[], jobs: Job[], on: (r: DuelRecord | { error: string }) => void) {
for (const j of jobs) {
try { on(playDuel(sim, [decks[j.decks[0]], decks[j.decks[1]]], j.bots, j.seed)); }
catch (e) { on({ error: String((e as Error)?.stack ?? e).slice(0, 800) }); }
}
}
async function main() {
const ctx: Ctx = { engineName: arg('engine', 'standin')!, rules: JSON.parse(arg('rules', '{}')!), nDecks: Number(arg('decks', '120')), deckSeed: Number(arg('deck-seed', '7')) };
const n = Number(arg('matches', '1000'));
const workers = Math.max(1, Math.min(MAX_WORKERS, Number(arg('workers', '4'))));
const seed = Number(arg('seed', '1'));
const out = arg('out', 'sim-out/duel')!;
const label = arg('label', ctx.engineName)!;
mkdirSync(out, { recursive: true });
const { sim, decks } = await setup(ctx);
const jobs = schedule(n, decks.length, seed, DUEL_MIXES[arg('mix', 'default')!]);
const records: DuelRecord[] = [], errors: string[] = [];
const file = createWriteStream(join(out, `${label}.jsonl`));
const t0 = Date.now();
const handle = (r: any) => {
if (r.error) { errors.push(r.error); return; }
records.push(r); file.write(JSON.stringify(r) + '\n');
if ((records.length + errors.length) % 250 === 0) process.stderr.write(`[${label}] ${records.length + errors.length}/${n} ${((Date.now() - t0) / 1000).toFixed(0)}s\n`);
};
if (workers === 1) runJobs(sim, decks, jobs, handle);
else {
const chunks: Job[][] = Array.from({ length: workers }, () => []);
jobs.forEach((j, i) => chunks[i % workers].push(j));
await Promise.all(chunks.map(chunk => new Promise<void>((resolve, reject) => {
const w = fork(fileURLToPath(import.meta.url), ['--child'], { execArgv: ['--import', 'tsx', '--max-old-space-size=384'], serialization: 'advanced' });
w.on('message', (m: any) => (m === 'done' ? w.kill() : handle(m)));
w.on('error', reject);
w.on('exit', () => resolve());
w.send({ ctx, jobs: chunk });
})));
}
file.end();
const stats = aggregateDuel(records, sim, decks, errors.length, { engine: ctx.engineName, rules: ctx.rules, label, sha: arg('sha') });
writeFileSync(join(out, `${label}.stats.json`), JSON.stringify(stats, null, 1));
if (errors.length) writeFileSync(join(out, `${label}.errors.txt`), errors.slice(0, 30).join('\n----\n'));
const md = duelMarkdown(stats);
writeFileSync(join(out, `${label}.md`), md);
process.stderr.write(`[${label}] done: ${records.length} matches, ${errors.length} errors, ${((Date.now() - t0) / 1000).toFixed(1)}s\n`);
process.stdout.write(md);
}
const isEntry = !!process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];
if (isEntry && process.argv.includes('--child')) {
process.once('message', async (msg: any) => {
const { sim, decks } = await setup(msg.ctx);
runJobs(sim, decks, msg.jobs, r => process.send!(r));
process.send!('done');
});
} else if (isEntry) main().catch(e => { console.error(e); process.exit(1); });
+18
View File
@@ -0,0 +1,18 @@
// What the duel simulation needs from an engine binding (stand-in or shared/duel).
import type { EngineAdapter } from '../../shared/bots/types.ts';
import type { DuelLens } from '../../shared/bots/duel-bots.ts';
import type { PoolCard } from './duel-decks.ts';
export interface DuelSim<S, A, C extends PoolCard = any> {
name: string;
engine: EngineAdapter<S, A>;
lens: DuelLens<S, A>;
/** The card pool decks are drawn from (the 236 sample cards, derived). */
pool: C[];
/** DeckSpec.payload for a list of pool cards. */
deckPayload(cards: C[]): unknown;
/** Extra per-match numbers from the final state (connected fires, plays, ...). */
metrics?(final: S): Record<string, number>;
/** Static Connected test for a pair of pool cards (for the pairwise fire rate). */
connected?(a: C, b: C): boolean | string | null;
}
+76
View File
@@ -0,0 +1,76 @@
// EngineAdapter + DuelLens over the sim stand-in duel engine (scripts/sim/duel-standin.ts).
import type { DeckSpec, EngineAdapter, Seat } from '../../shared/bots/types.ts';
import { duelEvaluate, type DuelLens, type LensAction } from '../../shared/bots/duel-bots.ts';
import { existsSync } from 'node:fs';
import { applyAction, createDuel, fromDuelCards, isCreature, legalActions, pow, tough, viewFor, deriveSample, STANDIN_RULES, type SAction, type SCard, type SRules, type SState } from './duel-standin.ts';
import { mulberry32 } from '../../shared/bots/index.ts';
import type { DuelSim } from './duel-sim-types.ts';
export const standinLens: DuelLens<SState, SAction> = {
phase: s => s.phase,
life: (s, p) => s.players[p].life,
handSize: (s, p) => (s as any).view && (s as any).view.seat !== p ? (s as any).view.oppHand : s.players[p].hand.length,
creatures: (s, p) => s.players[p].board.filter(isCreature).map(b => ({
uid: String(b.uid), power: pow(b), toughness: Math.max(0, tough(b) - b.damage), tapped: b.tapped,
canAttack: b.card.type === 'Figure' && !b.tapped && !b.sick, canBlock: !b.tapped,
value: pow(b) + tough(b) * 0.8 + (b.card.type === 'Figure' ? 0.5 : 0),
})),
attackers: s => s.attackers.map(String),
blocks: s => s.blocks.map(([b, a]) => [String(b), String(a)]),
decode: (s, a): LensAction => {
switch (a.type) {
case 'play': { const c = s.players[a.seat].hand.find(h => h.id === a.card); return { kind: 'play', cost: c?.cost ?? 0, cardType: c?.type ?? '?' }; }
case 'toggleAttacker': return { kind: 'attack', uid: String(a.uid), on: !s.attackers.includes(a.uid) };
case 'confirmAttack': return { kind: 'confirmAttack' };
case 'block': return { kind: 'block', blocker: String(a.blocker), attacker: String(a.attacker) };
case 'confirmBlocks': return { kind: 'confirmBlocks' };
case 'endPhase': return { kind: 'endMain' };
}
},
};
export function makeStandinSim(poolFile: string, rules: Partial<SRules> = {}): DuelSim<SState, SAction, SCard> {
const fixture = poolFile.replace(/card-sample\.json$/, 'duel-card-sample.json');
const pool = process.env.SIM_STANDIN_POOL !== 'own' && existsSync(fixture) ? fromDuelCards(fixture) : deriveSample(poolFile);
const R = { ...STANDIN_RULES, ...rules };
const engine: EngineAdapter<SState, SAction> = {
name: 'duel-standin',
rulesets: () => ['standin'],
decks: () => [],
createMatch: (_r, decks, seed) => createDuel([decks[0].payload as SCard[], decks[1].payload as SCard[]], seed, R),
toAct: s => (s.phase === 'block' ? (1 - s.active) : s.active) as Seat,
legalActions: (s, seat) => legalActions(s, seat),
applyAction: (s, a) => applyAction(s, a),
isOver: s => s.over,
result: s => ({ winner: s.winner, reason: s.reason }),
turn: s => s.turn,
evaluate: (s, seat) => duelEvaluate(standinLens, s, seat),
cardsOf: (s, a) => (a.type === 'play' ? [a.card] : []),
actionKind: a => a.type,
firstSeat: s => s.first,
observe: (s, seat) => viewFor(s, seat),
assume: (obs, seat, rng) => {
// Refill hidden zones from the unseen part of the pool (a determinization).
const v = structuredClone(obs) as SState & { view: { oppHand: number; oppLib: number; myLib: number } };
const seen = new Set<string>();
for (const p of v.players) for (const z of [p.hand, p.grave, p.board.map(b => b.card)]) for (const c of z) seen.add(c.id);
const unseen = pool.filter(c => !seen.has(c.id));
const r = mulberry32(Math.floor(rng() * 2 ** 31));
for (let i = unseen.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [unseen[i], unseen[j]] = [unseen[j], unseen[i]]; }
let k = 0;
const take = (n: number) => { const out: SCard[] = []; for (let i = 0; i < n; i++) out.push(unseen[k++ % Math.max(1, unseen.length)]); return out; };
const o = 1 - seat;
v.players[o].hand = take(v.view.oppHand);
v.players[o].library = take(v.view.oppLib);
v.players[seat].library = take(v.view.myLib);
delete (v as any).view;
return v;
},
};
return {
name: 'standin', engine, lens: standinLens, pool,
deckPayload: cards => cards,
metrics: s => ({ connectedFires: s.stats.connectedFires, plays: s.stats.plays, lifeLeft: s.winner === null ? 0 : s.players[s.winner].life }),
connected: (a, b) => a.connect.some((k: string) => b.connect.includes(k)),
};
}
+229
View File
@@ -0,0 +1,229 @@
// Stand-in duel engine for sim-balance, used only until (and as a test double alongside) duel-core's
// shared/duel engine. Implements the BRIEF "Game rules core" in miniature: 40-card decks, 20 Notability,
// Citations +1/turn to 10, no stack, sorcery-speed Events, single blocks, simultaneous damage,
// summoning sickness, empty-library loss. Card derivation is a rough copy of duel-cards' plan
// (fame percentile -> cost 1..6, P+T budget per cost). Pure and deterministic.
import { readFileSync } from 'node:fs';
import { mulberry32 } from '../../shared/bots/index.ts';
export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
export interface SCard {
id: string; pageId: number; title: string; type: CardType; portal: string;
cost: number; power: number; toughness: number; keywords: string[];
fame: number; connect: string[];
}
export interface SPerm { card: SCard; uid: number; damage: number; tapped: boolean; sick: boolean; buff: [number, number]; attachedTo?: number }
export interface SPlayer { life: number; library: SCard[]; hand: SCard[]; grave: SCard[]; board: SPerm[]; citations: number; maxCitations: number; ramp: number }
export type Phase = 'main' | 'attack' | 'block';
export interface SState {
rules: SRules; seed: number; rngState: number; turn: number; active: 0 | 1; phase: Phase;
players: [SPlayer, SPlayer]; attackers: number[]; blocks: [number, number][]; uid: number;
winner: 0 | 1 | null; over: boolean; reason?: string; first: 0 | 1;
stats: { connectedFires: number; plays: number };
}
export interface SRules { deckSize: number; startingLife: number; maxCitations: number; handSize: number; openingHand: number; turnCap?: number; connectedBonus: number }
export const STANDIN_RULES: SRules = { deckSize: 40, startingLife: 20, maxCitations: 10, handSize: 7, openingHand: 7, connectedBonus: 1 };
export type SAction =
| { type: 'play'; seat: 0 | 1; card: string; target?: number | 'face' }
| { type: 'toggleAttacker'; seat: 0 | 1; uid: number }
| { type: 'confirmAttack'; seat: 0 | 1 }
| { type: 'block'; seat: 0 | 1; blocker: number; attacker: number }
| { type: 'confirmBlocks'; seat: 0 | 1 }
| { type: 'endPhase'; seat: 0 | 1 };
// ---------- card derivation (sample JSON -> SCard) ----------
const COST_T = [26, 39, 51, 63, 78];
const BUDGET = [3, 4, 6, 8, 10, 12];
function classify(c: any): CardType {
const p31 = (c.instanceOf ?? []).map((x: any) => String(x.label ?? ''));
const ids = (c.instanceOf ?? []).map((x: any) => x.id);
if (ids.some((i: string) => ['Q5', 'Q16521', 'Q95074'].includes(i))) return 'Figure';
if (p31.some((l: string) => /settlement|commune|village|town|city|municipality|river|island|castle|building|township|mountain|lake/i.test(l))) return 'Location';
if (p31.some((l: string) => /election|storm|protest|battle|season|events|war|nor'easter|tournament|final/i.test(l))) return 'Event';
if (p31.some((l: string) => /group|company|film|album|band|team|organi[sz]ation|club|school|novel|song|series/i.test(l))) return 'Institution';
const cats = (c.categories ?? []).join('|');
if (/\d+ births|\d+ deaths|Living people/.test(cats)) return 'Figure';
if (/Communes of|Villages in|Populated places/.test(cats)) return 'Location';
return 'Doctrine';
}
function pctTable(cards: any[], key: string): number[] { return cards.map(c => c.stats?.[key]).filter((v: any) => typeof v === 'number').sort((a: number, b: number) => a - b); }
function pct(v: number | null | undefined, t: number[]): number | null { if (typeof v !== 'number') return null; let b = 0; for (const x of t) if (x < v) b++; return Math.round(100 * b / t.length); }
const COUNTRY = /\b(American|United States|English|British|France|French|German|Japan|Japanese|Chin(a|ese)|India|Brazil|Pol(and|ish)|Ital(y|ian)|Spa(in|nish)|Austria|Canad|Australia|Russia|Mexic|Iran|Pakistan|Swed|Norw|Estonia|Ukrain|Croatia|Philippin|Indonesia|Korea)/g;
export function deriveSample(file: string): SCard[] {
const raw = JSON.parse(readFileSync(file, 'utf8')).cards as any[];
const tA = pctTable(raw, 'attention'), tD = pctTable(raw, 'depth'), tR = pctTable(raw, 'reach');
return raw.map(c => {
const ps = [pct(c.stats?.attention, tA), pct(c.stats?.depth, tD), pct(c.stats?.reach, tR)].filter((x): x is number => x !== null);
const fame = ps.length ? Math.round(ps.reduce((a, b) => a + b, 0) / ps.length) : 0;
const cost = 1 + COST_T.filter(t => t <= fame).length;
const budget = BUDGET[cost - 1];
const a = pct(c.stats?.attention, tA) ?? 50, d = pct(c.stats?.depth, tD) ?? 50;
const share = Math.min(0.7, Math.max(0.3, a / Math.max(1, a + d)));
const power = Math.max(1, Math.round(budget * share)), toughness = Math.max(1, budget - power);
const txt = `${c.description ?? ''} ${(c.categories ?? []).join(' ')}`;
const countries = [...new Set([...txt.matchAll(COUNTRY)].map(m => m[1].slice(0, 5)))].map(x => `c:${x}`);
const cents = [...new Set([...`${c.title} ${txt}`.matchAll(/\b(1[0-9]{3}|20[0-2][0-9])\b/g)].map(m => `t:${Math.floor(Number(m[1]) / 100)}`))];
const type = classify(c);
if (type === 'Location') return { id: `p${c.pageId}`, pageId: c.pageId, title: c.title, type, portal: c.faction ?? 'Other', cost: Math.ceil(cost / 2), power: 0, toughness: Math.max(1, Math.ceil(toughness / 2)), keywords: [], fame, connect: [...countries, ...cents] };
const kw: string[] = [];
if (c.languageCount >= 20) kw.push('Multilingual');
if (c.pageBytes < 3000) kw.push('Stub');
return { id: `p${c.pageId}`, pageId: c.pageId, title: c.title, type, portal: c.faction ?? 'Other', cost, power, toughness, keywords: kw.slice(0, 2), fame, connect: [...countries, ...cents] };
});
}
// ---------- engine ----------
const clone = <T>(x: T): T => structuredClone(x);
function rng(s: SState) { const r = mulberry32(s.rngState); return () => { const v = r(); s.rngState = (s.rngState + 0x6d2b79f5) >>> 0; return v; }; }
function shuffle<T>(xs: T[], r: () => number) { for (let i = xs.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [xs[i], xs[j]] = [xs[j], xs[i]]; } }
const opp = (p: 0 | 1): 0 | 1 => (p === 0 ? 1 : 0);
export const pow = (p: SPerm) => p.card.power + p.buff[0];
export const tough = (p: SPerm) => p.card.toughness + p.buff[1];
export const isCreature = (p: SPerm) => p.card.type === 'Figure' || (p.card.type === 'Location' && p.attachedTo === undefined);
export function createDuel(decks: [SCard[], SCard[]], seed: number, rules: SRules = STANDIN_RULES): SState {
const s: SState = { rules, seed, rngState: seed >>> 0, turn: 1, active: 0, phase: 'main', players: [null, null] as any, attackers: [], blocks: [], uid: 1, winner: null, over: false, first: 0, stats: { connectedFires: 0, plays: 0 } };
const r = rng(s);
s.first = r() < 0.5 ? 0 : 1; s.active = s.first;
for (const p of [0, 1] as const) {
const lib = decks[p].slice(0, rules.deckSize).map(c => ({ ...c }));
shuffle(lib, r);
s.players[p] = { life: rules.startingLife, library: lib, hand: lib.splice(0, rules.openingHand), grave: [], board: [], citations: 0, maxCitations: 0, ramp: 0 };
}
refresh(s, false);
return s;
}
function lose(s: SState, p: 0 | 1, reason: string) { if (!s.over) { s.over = true; s.winner = opp(p); s.reason = reason; } }
function draw(s: SState, p: 0 | 1) { const pl = s.players[p]; const c = pl.library.shift(); if (!c) return lose(s, p, 'library-empty'); pl.hand.push(c); }
function refresh(s: SState, doDraw: boolean) {
const pl = s.players[s.active];
pl.maxCitations = Math.min(s.rules.maxCitations, pl.maxCitations + 1);
pl.citations = pl.maxCitations + pl.ramp;
for (const b of pl.board) { b.tapped = false; b.sick = false; }
if (doDraw) draw(s, s.active);
s.phase = 'main'; s.attackers = []; s.blocks = [];
}
function endTurn(s: SState) {
for (const pl of s.players) for (const b of pl.board) b.damage = 0;
const pl = s.players[s.active];
while (pl.hand.length > s.rules.handSize) pl.grave.push(pl.hand.pop()!);
if (s.rules.turnCap && s.turn >= s.rules.turnCap * 2) {
const [a, b] = s.players; s.over = true; s.reason = 'turn-cap';
s.winner = a.life === b.life ? null : a.life > b.life ? 0 : 1; return;
}
s.turn++; s.active = opp(s.active); refresh(s, true);
}
function connectedWith(card: SCard, board: SPerm[]): boolean { return board.some(b => b.card.connect.some(k => card.connect.includes(k))); }
export function legalActions(s: SState, seat: 0 | 1): SAction[] {
if (s.over) return [];
const pl = s.players[seat], foe = s.players[opp(seat)];
if (s.phase === 'block') {
if (seat !== opp(s.active)) return [];
const out: SAction[] = [{ type: 'confirmBlocks', seat }];
const used = new Set(s.blocks.map(b => b[0])), blocked = new Set(s.blocks.map(b => b[1]));
for (const bl of pl.board) if (isCreature(bl) && !bl.tapped && !used.has(bl.uid) && (bl.card.type === 'Figure' || tough(bl) > 0))
for (const a of s.attackers) if (!blocked.has(a)) out.push({ type: 'block', seat, blocker: bl.uid, attacker: a });
return out;
}
if (seat !== s.active) return [];
if (s.phase === 'attack') {
const out: SAction[] = [{ type: 'confirmAttack', seat }];
for (const b of pl.board) if (b.card.type === 'Figure' && !b.tapped && !b.sick) out.push({ type: 'toggleAttacker', seat, uid: b.uid });
return out;
}
const out: SAction[] = [{ type: 'endPhase', seat }];
const seen = new Set<string>();
for (const c of pl.hand) {
if (c.cost > pl.citations || seen.has(c.id)) continue; seen.add(c.id);
if (c.type === 'Event') {
out.push({ type: 'play', seat, card: c.id, target: 'face' });
for (const b of foe.board) if (b.card.type === 'Figure' && !b.card.keywords.includes('Protected')) out.push({ type: 'play', seat, card: c.id, target: b.uid });
} else if (c.type === 'Doctrine') {
for (const b of pl.board) if (b.card.type === 'Figure') out.push({ type: 'play', seat, card: c.id, target: b.uid });
} else out.push({ type: 'play', seat, card: c.id });
}
return out;
}
function kill(s: SState) {
for (const p of [0, 1] as const) {
const pl = s.players[p];
const dead = pl.board.filter(b => isCreature(b) && b.damage >= tough(b) && tough(b) > 0);
if (!dead.length) continue;
const ids = new Set(dead.map(d => d.uid));
for (const d of dead) pl.grave.push(d.card);
pl.board = pl.board.filter(b => !ids.has(b.uid) && !(b.attachedTo !== undefined && ids.has(b.attachedTo)));
}
}
export function applyAction(s0: SState, a: SAction): SState {
const s = clone(s0);
const pl = s.players[a.seat], foe = s.players[opp(a.seat)];
switch (a.type) {
case 'play': {
const i = pl.hand.findIndex(c => c.id === a.card); const c = pl.hand[i];
pl.hand.splice(i, 1); pl.citations -= c.cost; s.stats.plays++;
const conn = connectedWith(c, pl.board); if (conn) s.stats.connectedFires++;
const bonus = conn ? s.rules.connectedBonus : 0;
if (c.type === 'Event') {
const dmg = c.cost + 1 + bonus;
if (a.target === 'face') foe.life -= Math.ceil(dmg / 2);
else { const t = foe.board.find(b => b.uid === a.target); if (t) t.damage += dmg; kill(s); }
pl.grave.push(c);
} else if (c.type === 'Doctrine') {
const t = pl.board.find(b => b.uid === a.target)!;
t.buff = [t.buff[0] + Math.ceil(c.power / 2) + bonus, t.buff[1] + Math.ceil(c.toughness / 2) + bonus];
pl.board.push({ card: c, uid: s.uid++, damage: 0, tapped: false, sick: false, buff: [0, 0], attachedTo: t.uid });
} else if (c.type === 'Institution') {
pl.board.push({ card: c, uid: s.uid++, damage: 0, tapped: false, sick: false, buff: [0, 0], attachedTo: -1 });
draw(s, a.seat); if (c.cost >= 4) draw(s, a.seat);
} else if (c.type === 'Location') {
if (pl.ramp < 2) pl.ramp++;
pl.board.push({ card: { ...c, power: 0 }, uid: s.uid++, damage: 0, tapped: false, sick: false, buff: [0, bonus] });
} else pl.board.push({ card: c, uid: s.uid++, damage: 0, tapped: false, sick: true, buff: [bonus, bonus] });
if (foe.life <= 0) lose(s, opp(a.seat), 'notability');
return s;
}
case 'endPhase': s.phase = 'attack'; return s;
case 'toggleAttacker': { const k = s.attackers.indexOf(a.uid); if (k >= 0) s.attackers.splice(k, 1); else s.attackers.push(a.uid); return s; }
case 'confirmAttack':
if (!s.attackers.length) { endTurn(s); return s; }
for (const u of s.attackers) pl.board.find(b => b.uid === u)!.tapped = true;
s.phase = 'block'; return s;
case 'block': s.blocks.push([a.blocker, a.attacker]); return s;
case 'confirmBlocks': {
const att = s.players[s.active], def = s.players[a.seat];
for (const u of s.attackers) {
const A = att.board.find(b => b.uid === u); if (!A) continue;
const bl = s.blocks.find(b => b[1] === u);
const B = bl && def.board.find(b => b.uid === bl[0]);
if (B) { B.damage += pow(A); A.damage += pow(B); } else def.life -= pow(A);
}
kill(s);
if (def.life <= 0) { lose(s, a.seat, 'notability'); return s; }
endTurn(s); return s;
}
}
}
/** Seat-local copy: opponent hand and both libraries' contents are hidden (replaced by counts). */
export function viewFor(s: SState, seat: 0 | 1) {
const v = clone(s) as any;
const o = v.players[opp(seat)];
v.view = { seat, oppHand: o.hand.length, oppLib: o.library.length, myLib: v.players[seat].library.length };
o.hand = []; o.library = []; v.players[seat].library = [];
return v as SState & { view: { seat: 0 | 1; oppHand: number; oppLib: number; myLib: number } };
}
/** duel-cards' derived DuelCards (docs/game/duel-card-sample.json) mapped onto the stand-in's card shape. */
export function fromDuelCards(file: string): SCard[] {
const cards = JSON.parse(readFileSync(file, 'utf8')).cards as any[];
return cards.map(c => ({
id: c.cardId, pageId: c.pageId, title: c.title, type: c.type, portal: c.portal, cost: c.cost,
power: c.type === 'Location' ? 0 : (c.power ?? c.basis?.magnitude ?? 1), toughness: c.type === 'Location' ? Math.max(1, c.toughness ?? 1) : (c.toughness ?? c.basis?.magnitude ?? 1),
keywords: c.keywords ?? [], fame: c.basis?.fame ?? 0,
connect: [...(c.connect?.countries ?? []).map((x: string) => `c:${x}`), ...(c.connect?.centuries ?? []).map((x: number) => `t:${x}`)],
}));
}
+156
View File
@@ -0,0 +1,156 @@
// Aggregate duel match records into the DUEL_BALANCE.md metrics.
import type { Seat } from '../../shared/bots/types.ts';
import { rate, type Rate } from './stats.ts';
import type { SimDeck, PoolCard } from './duel-decks.ts';
import type { DuelSim } from './duel-sim-types.ts';
export interface DuelRecord {
seed: number; bots: [string, string]; decks: [string, string]; tags: [string[], string[]];
first: Seat; winner: Seat | null; reason: string; turns: number; turnsEach: number; actions: number; truncated: boolean;
minutes: number; played: [string[], string[]]; metrics: Record<string, number>; ms: number;
}
const quant = (xs: number[], q: number) => { if (!xs.length) return NaN; const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.floor(q * s.length))]; };
const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / (xs.length || 1);
function pearson(xs: number[], ys: number[]) {
const mx = mean(xs), my = mean(ys); let sxy = 0, sxx = 0, syy = 0;
for (let i = 0; i < xs.length; i++) { const dx = xs[i] - mx, dy = ys[i] - my; sxy += dx * dy; sxx += dx * dx; syy += dy * dy; }
return sxx && syy ? sxy / Math.sqrt(sxx * syy) : NaN;
}
export interface DuelStats {
meta: Record<string, unknown>;
matches: number; errors: number; draws: number; truncated: number; reasons: Record<string, number>;
firstPlayer: Rate; firstPlayerAll: Rate;
turnsEach: { p10: number; p50: number; p90: number; mean: number };
minutes: { p10: number; p50: number; p90: number };
stalls: { actionCap: number; turnCap: number; over20Each: number; rate: number };
skill: Record<string, Rate>;
byTag: Record<string, Rate>;
byType: Record<string, Rate & { plays: number }>;
byPortal: Record<string, Rate & { plays: number }>;
byKeyword: Record<string, Rate & { plays: number }>;
byCost: Record<string, Rate & { plays: number }>;
fame: { rCardWr: number; rWithinCost: Record<string, number>; topDecile: Rate; bottomDecile: Rate; cards: number };
connected: { pairRate: number; pairs: number; firesPerPlay: number; firesPerGame: number };
cards: { id: string; title?: string; type: string; cost: number; fame?: number; games: number; wr: Rate }[];
}
const sym = (m: DuelRecord) => m.bots[0] === m.bots[1];
export function aggregateDuel(records: DuelRecord[], sim: DuelSim<any, any>, decks: SimDeck[], errors: number, meta: Record<string, unknown>): DuelStats {
const byId = new Map<string, PoolCard & { title?: string }>(sim.pool.map((c: any) => [c.id, c]));
const decisive = records.filter(m => m.winner !== null);
const symDec = decisive.filter(sym);
const reasons: Record<string, number> = {};
for (const m of records) reasons[m.reason] = (reasons[m.reason] ?? 0) + 1;
const skill: Record<string, Rate> = {};
const pairs: Record<string, [number, number]> = {};
for (const m of decisive) {
if (sym(m)) continue;
const key = [...m.bots].sort().join('>');
const [a] = key.split('>');
const aSeat = m.bots[0] === a ? 0 : 1;
const p = pairs[key] ?? (pairs[key] = [0, 0]); p[0]++; if (m.winner === aSeat) p[1]++;
}
for (const [k, [n, w]] of Object.entries(pairs)) {
// Report as "stronger>weaker" with the stronger side's rate.
const [a, b] = k.split('>'); const r = rate(w, n);
if (r.rate >= 0.5) skill[`${a}>${b}`] = r; else skill[`${b}>${a}`] = rate(n - w, n);
}
// Tags: exclude games where both decks share the tag.
const tagAcc: Record<string, [number, number]> = {};
for (const m of symDec) for (const s of [0, 1] as Seat[]) for (const t of m.tags[s]) {
if (m.tags[1 - s].includes(t)) continue;
const a = tagAcc[t] ?? (tagAcc[t] = [0, 0]); a[0]++; if (m.winner === s) a[1]++;
}
const byTag = Object.fromEntries(Object.entries(tagAcc).sort().map(([k, [n, w]]) => [k, rate(w, n)]));
// Card-level: a card "appears" in a game if its seat played it. WR of the seat that played it.
const cardAcc = new Map<string, [number, number]>();
for (const m of symDec) for (const s of [0, 1] as Seat[]) for (const id of new Set(m.played[s])) {
if (new Set(m.played[1 - s]).has(id)) continue;
const a = cardAcc.get(id) ?? [0, 0]; a[0]++; if (m.winner === s) a[1]++; cardAcc.set(id, a);
}
const group = (f: (c: PoolCard) => string[]) => {
const acc: Record<string, [number, number]> = {};
for (const [id, [n, w]] of cardAcc) { const c = byId.get(id); if (!c) continue; for (const k of f(c)) { const a = acc[k] ?? (acc[k] = [0, 0]); a[0] += n; a[1] += w; } }
return Object.fromEntries(Object.entries(acc).sort().map(([k, [n, w]]) => [k, { ...rate(w, n), plays: n }]));
};
const cards = [...cardAcc].map(([id, [n, w]]) => { const c = byId.get(id) as any; return { id, title: c?.title, type: c?.type ?? '?', cost: c?.cost ?? 0, fame: c?.fame, games: n, wr: rate(w, n) }; })
.sort((a, b) => b.games - a.games);
const solid = cards.filter(c => c.games >= 20 && typeof c.fame === 'number');
const rWithinCost: Record<string, number> = {};
for (const cost of [1, 2, 3, 4, 5, 6]) { const xs = solid.filter(c => c.cost === cost); if (xs.length >= 5) rWithinCost[cost] = pearson(xs.map(c => c.fame!), xs.map(c => c.wr.rate)); }
const byFame = [...solid].sort((a, b) => a.fame! - b.fame!);
const dec = Math.max(1, Math.floor(byFame.length / 10));
const pool = (xs: typeof solid) => rate(xs.reduce((t, c) => t + c.wr.wins, 0), xs.reduce((t, c) => t + c.games, 0));
// Connected: static pair rate over the pool, and in-game fires.
let pairsN = 0, hits = 0;
if (sim.connected) for (let i = 0; i < sim.pool.length; i++) for (let j = i + 1; j < sim.pool.length; j++) { pairsN++; if (sim.connected(sim.pool[i], sim.pool[j])) hits++; }
const fires = records.map(m => m.metrics.connectedFires ?? 0), plays = records.map(m => m.metrics.plays ?? 0);
const turns = records.filter(m => !m.truncated).map(m => m.turnsEach);
const fp = (xs: DuelRecord[]) => rate(xs.filter(m => m.winner === m.first).length, xs.length);
const actionCap = records.filter(m => m.truncated).length, turnCap = reasons['turn-cap'] ?? 0, over20 = records.filter(m => m.turnsEach > 20).length;
return {
meta: { ...meta, decks: decks.length, when: new Date().toISOString() },
matches: records.length, errors, draws: records.length - decisive.length, truncated: actionCap, reasons,
firstPlayer: fp(symDec), firstPlayerAll: fp(decisive),
turnsEach: { p10: quant(turns, 0.1), p50: quant(turns, 0.5), p90: quant(turns, 0.9), mean: mean(turns) },
minutes: { p10: quant(records.map(m => m.minutes), 0.1), p50: quant(records.map(m => m.minutes), 0.5), p90: quant(records.map(m => m.minutes), 0.9) },
stalls: { actionCap, turnCap, over20Each: over20, rate: (actionCap + turnCap + over20) / (records.length || 1) },
skill, byTag,
byType: group(c => [c.type]), byPortal: group(c => [c.portal]), byKeyword: group(c => (c.keywords.length ? c.keywords : ['(none)'])), byCost: group(c => [String(c.cost)]),
fame: { rCardWr: pearson(solid.map(c => c.fame!), solid.map(c => c.wr.rate)), rWithinCost, topDecile: pool(byFame.slice(-dec)), bottomDecile: pool(byFame.slice(0, dec)), cards: solid.length },
connected: { pairRate: pairsN ? hits / pairsN : NaN, pairs: pairsN, firesPerPlay: mean(plays) ? mean(fires) / mean(plays) : NaN, firesPerGame: mean(fires) },
cards,
};
}
const pc = (r: Rate) => (Number.isNaN(r.rate) ? '—' : `${(100 * r.rate).toFixed(1)}% [${(100 * r.lo).toFixed(0)}–${(100 * r.hi).toFixed(0)}] n=${r.n}`);
const table = (title: string, m: Record<string, Rate & { plays?: number }>) =>
`| ${title} | Win rate (95% CI) |\n|---|---|\n` + Object.entries(m).map(([k, r]) => `| ${k} | ${pc(r)} |`).join('\n') + '\n';
export function duelMarkdown(s: DuelStats): string {
const f = (x: number, d = 1) => (Number.isNaN(x) ? '—' : x.toFixed(d));
const top = s.cards.filter(c => c.games >= 20).sort((a, b) => b.wr.rate - a.wr.rate);
const line = (c: DuelStats['cards'][number]) => `| ${c.title ?? c.id} | ${c.type} | ${c.cost} | ${f(c.fame ?? NaN, 0)} | ${pc(c.wr)} |`;
return `### Run \`${s.meta.label}\` (engine \`${s.meta.engine}\`${s.meta.sha ? `, SHA \`${s.meta.sha}\`` : ''})
Rules overrides: \`${JSON.stringify(s.meta.rules)}\`. ${s.matches} matches, ${s.meta.decks} decks, ${s.errors} errors, ${s.draws} draws.
| Metric | Value | Target |
|---|---|---|
| First-player win rate (symmetric bots) | ${pc(s.firstPlayer)} | 48–52% |
| First-player win rate (all decisive) | ${pc(s.firstPlayerAll)} | |
| Turns each p10 / median / p90 | ${f(s.turnsEach.p10, 0)} / **${f(s.turnsEach.p50, 0)}** / ${f(s.turnsEach.p90, 0)} | median 8–12 |
| Est. minutes p10 / median / p90 | ${f(s.minutes.p10)} / **${f(s.minutes.p50)}** / ${f(s.minutes.p90)} | 8–15 |
| Stalls (action cap + turn cap + >20 turns each) | ${s.stalls.actionCap} + ${s.stalls.turnCap} + ${s.stalls.over20Each} (${f(100 * s.stalls.rate)}%) | ~0 |
| Connected: static pair rate over the pool | ${f(100 * s.connected.pairRate)}% of ${s.connected.pairs} pairs | 15–30% |
| Connected: fires per play / per game | ${f(100 * s.connected.firesPerPlay)}% / ${f(s.connected.firesPerGame, 2)} | |
| Fame vs card win rate (Pearson r, cards with ≥20 games) | ${f(s.fame.rCardWr, 2)} (n=${s.fame.cards}) | ≈0 (not strictly better) |
| Top vs bottom fame decile | ${pc(s.fame.topDecile)} vs ${pc(s.fame.bottomDecile)} | close |
End reasons: ${Object.entries(s.reasons).map(([k, v]) => `${k} ${v}`).join(', ')}.
Skill (stronger bot's win rate): ${Object.entries(s.skill).map(([k, r]) => `${k} ${pc(r)}`).join('; ') || '—'}.
Fame vs win rate within each cost: ${Object.entries(s.fame.rWithinCost).map(([k, r]) => `cost ${k}: r=${f(r, 2)}`).join(', ') || '—'}.
${table('Card type (seat that played it)', s.byType)}
${table('Portal', s.byPortal)}
${table('Keyword', s.byKeyword)}
${table('Cost', s.byCost)}
${table('Deck tag (vs decks without it)', s.byTag)}
Top cards by win rate when played (≥20 games):
| Card | Type | Cost | Fame | WR |
|---|---|---|---|---|
${top.slice(0, 8).map(line).join('\n')}
Bottom cards:
| Card | Type | Cost | Fame | WR |
|---|---|---|---|---|
${top.slice(-8).reverse().map(line).join('\n')}
`;
}