forked from WikiDeck/wikideck
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f494e399c |
@@ -16,7 +16,7 @@ A 3-node **testnet-only** fixture on poweredge-r350. It is reachable on the LAN
|
||||
- `compose.lan.yaml` also sets, per node:
|
||||
- `WIKIDECK_USER_AGENT`, a Wikimedia-policy UA with a project URL (#19). Without it, Wikipedia returned 429 to our egress and templates failed.
|
||||
- the game-mode env from #22: A = classic and trending, B = draft, C = all three.
|
||||
- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-16 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves.
|
||||
- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-17 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves.
|
||||
- `testnet.sh` has `up`, `mine N [workers]`, `status` and `down`. Run it from the repo root on a checkout of the integration branch. `up` rebuilds the image from that checkout; the ledgers persist in the named volumes.
|
||||
|
||||
Never point this at mainnet or the live `wikideck` namespace.
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
# because lobbies are in memory and a restart ends games in progress.
|
||||
# Head detection uses the public Gitea API, which also works where SSH auth isn't available.
|
||||
set -u
|
||||
BRANCH=${BRANCH:-night/2026-11-16}
|
||||
BRANCH=${BRANCH:-night/2026-11-17}
|
||||
API=${API:-https://gitea.eom.dev/api/v1/repos/claude/wikideck}
|
||||
INTERVAL=${INTERVAL:-180}
|
||||
LOG=${LOG:-/tmp/wikideck-night-autodeploy.log}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
// 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); });
|
||||
@@ -1,18 +0,0 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
// 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)),
|
||||
};
|
||||
}
|
||||
@@ -1,229 +0,0 @@
|
||||
// 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}`)],
|
||||
}));
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
// 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')}
|
||||
`;
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
// Duel bots: engine-agnostic heuristics for a Magic-style duel (attack/block/sorcery-speed plays).
|
||||
// Bots see the duel through a DuelLens (a few accessors over state and action), so the same bots run
|
||||
// on duel-core's shared/duel engine and on the sim stand-in. Pure: no I/O.
|
||||
import type { EngineAdapter, Rng, Seat, BotFn } from './types.ts';
|
||||
import { lookaheadBot } from './index.ts';
|
||||
|
||||
/**
|
||||
* Observations may carry the acting seat's legal actions (`legal`): the UI shows them anyway, and choosing
|
||||
* from them guarantees a bot never returns an action that is legal only in its determinized guess.
|
||||
*/
|
||||
function legalOf<S, A>(engine: EngineAdapter<S, A>, obs: unknown, s: S, seat: Seat): A[] {
|
||||
const l = (obs as { legal?: A[] } | null)?.legal;
|
||||
return Array.isArray(l) ? l : engine.legalActions(s, seat);
|
||||
}
|
||||
const seeState = <S, A>(engine: EngineAdapter<S, A>, obs: unknown, seat: Seat, rng: Rng): S => (engine.assume ? engine.assume(obs, seat, rng) : (obs as S));
|
||||
|
||||
/** Uniformly random legal action. */
|
||||
export function duelRandomBot<S, A>(engine: EngineAdapter<S, A>): BotFn<unknown, A> {
|
||||
return (obs, seat, rng) => { const l = (obs as { legal?: A[] })?.legal; const legal = Array.isArray(l) ? l : engine.legalActions(seeState(engine, obs, seat, rng), seat); return legal[Math.floor(rng() * legal.length)]; };
|
||||
}
|
||||
|
||||
/** One-ply greedy on the evaluation over every legal action (weak at combat: toggles have no immediate value). */
|
||||
export function duelGreedyBot<S, A>(engine: EngineAdapter<S, A>): BotFn<unknown, A> {
|
||||
return (obs, seat, rng) => {
|
||||
const s = seeState(engine, obs, seat, rng);
|
||||
const legal = legalOf(engine, obs, s, seat);
|
||||
let best = legal[0], bestV = -Infinity;
|
||||
for (const a of legal) { const v = safeEval(engine, s, a, seat) + rng() * 1e-6; if (v > bestV) { bestV = v; best = a; } }
|
||||
return best;
|
||||
};
|
||||
}
|
||||
|
||||
/** Evaluate `a` from `s`; an action the determinized state rejects scores -5 (it stays a candidate). */
|
||||
function safeEval<S, A>(engine: EngineAdapter<S, A>, s: S, a: A, seat: Seat): number {
|
||||
try { const n = engine.applyAction(s, a); return engine.isOver(n) ? (engine.result(n).winner === seat ? 10 : engine.result(n).winner === null ? 0 : -10) : engine.evaluate(n, seat); }
|
||||
catch { return -5; }
|
||||
}
|
||||
|
||||
export interface LensCreature { uid: string; power: number; toughness: number; tapped: boolean; canAttack: boolean; canBlock: boolean; value: number }
|
||||
export type LensAction =
|
||||
| { kind: 'play'; cost: number; cardType: string }
|
||||
| { kind: 'attack'; uid: string; on: boolean }
|
||||
| { kind: 'confirmAttack' }
|
||||
| { kind: 'block'; blocker: string; attacker: string }
|
||||
| { kind: 'confirmBlocks' }
|
||||
| { kind: 'endMain' }
|
||||
| { kind: 'mulligan' | 'keep' | 'other' };
|
||||
|
||||
export interface DuelLens<S, A> {
|
||||
phase(s: S): 'main' | 'attack' | 'block' | 'mulligan' | 'other';
|
||||
life(s: S, seat: Seat): number;
|
||||
creatures(s: S, seat: Seat): LensCreature[];
|
||||
handSize(s: S, seat: Seat): number;
|
||||
/** Attackers currently declared by the active player (uids). */
|
||||
attackers(s: S): string[];
|
||||
/** Blocks declared so far [blocker, attacker]. */
|
||||
blocks(s: S): [string, string][];
|
||||
decode(s: S, a: A): LensAction;
|
||||
}
|
||||
|
||||
/** Material evaluation in [-1, 1]: life, board (power+toughness) and cards in hand. */
|
||||
export function duelEvaluate<S, A>(lens: DuelLens<S, A>, s: S, seat: Seat): number {
|
||||
const o = (seat === 0 ? 1 : 0) as Seat;
|
||||
const board = (p: Seat) => lens.creatures(s, p).reduce((t, c) => t + c.value, 0);
|
||||
const myLife = lens.life(s, seat), oLife = lens.life(s, o);
|
||||
const lifeTerm = (Math.min(myLife, 20) - Math.min(oLife, 20)) / 20 + (oLife <= 0 ? 1 : 0) - (myLife <= 0 ? 1 : 0);
|
||||
const boardTerm = Math.tanh((board(seat) - board(o)) / 12);
|
||||
const handTerm = Math.tanh((lens.handSize(s, seat) - lens.handSize(s, o)) / 6);
|
||||
return Math.max(-1, Math.min(1, 0.4 * lifeTerm + 0.45 * boardTerm + 0.15 * handTerm));
|
||||
}
|
||||
|
||||
const pick = <T>(xs: T[], rng: Rng): T => xs[Math.floor(rng() * xs.length)];
|
||||
|
||||
/** Choose attackers: attack with a creature unless the foe has an untapped blocker that kills it and survives; all-in when lethal-ish. */
|
||||
function wantAttack<S, A>(lens: DuelLens<S, A>, s: S, seat: Seat, c: LensCreature): boolean {
|
||||
const o = (seat === 0 ? 1 : 0) as Seat;
|
||||
const blockers = lens.creatures(s, o).filter(b => b.canBlock);
|
||||
const mine = lens.creatures(s, seat).filter(x => x.canAttack);
|
||||
// Lethal check: assume the foe blocks our biggest attackers; the rest must cover its life.
|
||||
const unblocked = mine.map(x => x.power).sort((a, b) => b - a).slice(blockers.length).reduce((t, p) => t + p, 0);
|
||||
if (unblocked >= lens.life(s, o)) return true;
|
||||
if (c.power <= 0) return false;
|
||||
const badBlock = blockers.some(b => b.power >= c.toughness && b.toughness > c.power);
|
||||
if (badBlock) return false;
|
||||
const trade = blockers.some(b => b.power >= c.toughness);
|
||||
// Trading is fine if we are ahead on board or the foe is low.
|
||||
if (trade) return lens.life(s, o) <= 8 || mine.length > blockers.length;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Choose a block for an attacker: kill-and-survive > chump only when lethal > even trade if attacker is worth more. */
|
||||
function chooseBlock<S, A>(lens: DuelLens<S, A>, s: S, seat: Seat, legal: { a: A; d: LensAction & { kind: 'block' } }[]): A | null {
|
||||
if (!legal.length) return null;
|
||||
const o = (seat === 0 ? 1 : 0) as Seat;
|
||||
const att = new Map(lens.creatures(s, o).map(c => [c.uid, c]));
|
||||
const mine = new Map(lens.creatures(s, seat).map(c => [c.uid, c]));
|
||||
const blocked = new Set(lens.blocks(s).map(b => b[1]));
|
||||
const incoming = lens.attackers(s).filter(u => !blocked.has(u)).reduce((t, u) => t + (att.get(u)?.power ?? 0), 0);
|
||||
const lethal = incoming >= lens.life(s, seat);
|
||||
let best: A | null = null, bestScore = 0;
|
||||
for (const { a, d } of legal) {
|
||||
const A = att.get(d.attacker), B = mine.get(d.blocker);
|
||||
if (!A || !B) continue;
|
||||
const kills = B.power >= A.toughness, dies = A.power >= B.toughness;
|
||||
let score = 0;
|
||||
if (kills && !dies) score = 10 + A.value;
|
||||
else if (kills && dies) score = A.value > B.value ? 5 + A.value - B.value : lethal ? 3 : 0;
|
||||
else if (!dies) score = 2 + A.power * 0.5; // safe absorb
|
||||
else score = lethal ? 1 + A.power - B.value * 0.1 : 0;
|
||||
if (score > bestScore) { bestScore = score; best = a; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* Heuristic duel bot: main phase is one-ply greedy over plays (material eval), attacks and blocks follow
|
||||
* simple Magic heuristics. Strong enough to be the balance baseline; deterministic given rng.
|
||||
*/
|
||||
export function heuristicBot<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>): BotFn<unknown, A> {
|
||||
return (obs, seat, rng) => {
|
||||
const s = seeState(engine, obs, seat, rng);
|
||||
const legal = legalOf(engine, obs, s, seat);
|
||||
if (legal.length === 1) return legal[0];
|
||||
return heuristicChoice(engine, lens, s, seat, legal, rng);
|
||||
};
|
||||
}
|
||||
|
||||
export function heuristicChoice<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>, s: S, seat: Seat, legal: A[], rng: Rng): A {
|
||||
const dec = legal.map(a => ({ a, d: lens.decode(s, a) }));
|
||||
const find = (k: LensAction['kind']) => dec.find(x => x.d.kind === k)?.a;
|
||||
switch (lens.phase(s)) {
|
||||
case 'mulligan': return find('keep') ?? legal[0];
|
||||
case 'main': {
|
||||
const plays = dec.filter(x => x.d.kind === 'play');
|
||||
const base = engine.evaluate(s, seat);
|
||||
let best: A | undefined, bestV = -Infinity;
|
||||
for (const { a, d } of plays) {
|
||||
const v = safeEval(engine, s, a, seat) + 0.004 * (d as any).cost + rng() * 1e-6;
|
||||
if (v > bestV) { bestV = v; best = a; }
|
||||
}
|
||||
if (best !== undefined && bestV > base - 0.02) return best;
|
||||
return find('endMain') ?? find('other') ?? legal[0];
|
||||
}
|
||||
case 'attack': {
|
||||
const declared = new Set(lens.attackers(s));
|
||||
for (const { a, d } of dec) {
|
||||
if (d.kind !== 'attack') continue;
|
||||
const c = lens.creatures(s, seat).find(x => x.uid === d.uid);
|
||||
if (!c) continue;
|
||||
const want = wantAttack(lens, s, seat, c);
|
||||
if (want !== declared.has(d.uid) && d.on === want) return a;
|
||||
}
|
||||
return find('confirmAttack') ?? legal[0];
|
||||
}
|
||||
case 'block': {
|
||||
const b = chooseBlock(lens, s, seat, dec.filter((x): x is { a: A; d: LensAction & { kind: 'block' } } => x.d.kind === 'block'));
|
||||
return b ?? find('confirmBlocks') ?? legal[0];
|
||||
}
|
||||
default: return pick(legal, rng);
|
||||
}
|
||||
}
|
||||
|
||||
export interface DuelMCOptions { rollouts?: number; k?: number; horizon?: number }
|
||||
|
||||
/**
|
||||
* Shallow Monte Carlo over the heuristic: in the main and block phases, shortlist up to k candidate actions,
|
||||
* run `rollouts` heuristic playouts (fresh determinization each) for `horizon` actions and pick the best mean.
|
||||
* Attack declarations use the heuristic directly (toggles have no immediate value to rank).
|
||||
*/
|
||||
export function duelMCBot<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>, opts: DuelMCOptions = {}): BotFn<unknown, A> {
|
||||
const rollouts = opts.rollouts ?? 6, k = opts.k ?? 4, horizon = opts.horizon ?? 120;
|
||||
return (obs, seat, rng) => {
|
||||
const s = seeState(engine, obs, seat, rng);
|
||||
const legal = legalOf(engine, obs, s, seat);
|
||||
if (legal.length === 1) return legal[0];
|
||||
const ph = lens.phase(s);
|
||||
if (ph !== 'main' && ph !== 'attack') return heuristicChoice(engine, lens, s, seat, legal, rng);
|
||||
const h = heuristicChoice(engine, lens, s, seat, legal, rng);
|
||||
let cands: A[];
|
||||
if (ph === 'attack') {
|
||||
// Candidates: heuristic choice, confirm now, or all-in (toggle every not-yet-declared attacker).
|
||||
const dec = legal.map(a => ({ a, d: lens.decode(s, a) }));
|
||||
cands = [h, ...dec.filter(x => x.d.kind === 'confirmAttack' || (x.d.kind === 'attack' && x.d.on)).map(x => x.a)];
|
||||
} else {
|
||||
cands = [h, ...legal.map(a => ({ a, v: safeEval(engine, s, a, seat) })).sort((x, y) => y.v - x.v).map(x => x.a)];
|
||||
}
|
||||
const uniq: A[] = [];
|
||||
for (const c of cands) if (!uniq.some(u => JSON.stringify(u) === JSON.stringify(c))) uniq.push(c);
|
||||
const short = uniq.slice(0, k);
|
||||
if (short.length === 1) return short[0];
|
||||
let best = short[0], bestScore = -Infinity;
|
||||
for (const c of short) {
|
||||
let total = 0;
|
||||
for (let r = 0; r < rollouts; r++) {
|
||||
let st: S, steps = 0;
|
||||
try { st = engine.applyAction(seeState(engine, obs, seat, rng), c); } catch { total -= 1; continue; }
|
||||
while (!engine.isOver(st) && steps < horizon) {
|
||||
const who = engine.toAct(st);
|
||||
const lg = engine.legalActions(st, who);
|
||||
if (!lg.length) break;
|
||||
st = engine.applyAction(st, lg.length === 1 ? lg[0] : heuristicChoice(engine, lens, st, who, lg, rng));
|
||||
steps++;
|
||||
}
|
||||
if (engine.isOver(st)) { const w = engine.result(st).winner; total += w === null ? 0 : w === seat ? 1 : -1; }
|
||||
else total += engine.evaluate(st, seat);
|
||||
}
|
||||
const score = total / rollouts + (c === h ? 0.02 : 0);
|
||||
if (score > bestScore) { bestScore = score; best = c; }
|
||||
}
|
||||
return best;
|
||||
};
|
||||
}
|
||||
|
||||
/** Heuristic with blunders: with probability `rate` a uniformly random legal action instead (UI "Easy"). */
|
||||
export function blunderBot<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>, rate = 0.3): BotFn<unknown, A> {
|
||||
const h = heuristicBot(engine, lens), r = duelRandomBot(engine);
|
||||
return (obs, seat, rng) => (rng() < rate ? r(obs, seat, rng) : h(obs, seat, rng));
|
||||
}
|
||||
|
||||
export const DUEL_BOT_NAMES = ['random', 'greedy', 'easy', 'heuristic', 'mc', 'mc-lite'] as const;
|
||||
|
||||
export function makeDuelBot<S, A>(name: string, engine: EngineAdapter<S, A>, lens: DuelLens<S, A>): BotFn<unknown, A> {
|
||||
switch (name) {
|
||||
case 'random': return duelRandomBot(engine);
|
||||
case 'greedy': return duelGreedyBot(engine);
|
||||
case 'heuristic': return heuristicBot(engine, lens);
|
||||
case 'easy': return blunderBot(engine, lens);
|
||||
case 'mc': return duelMCBot(engine, lens);
|
||||
case 'mc-lite': return duelMCBot(engine, lens, { rollouts: 3, k: 3, horizon: 60 });
|
||||
case 'lookahead': return lookaheadBot(engine);
|
||||
default: throw new Error(`unknown duel bot ${name}`);
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { mulberry32 } from '../shared/bots/index.ts';
|
||||
import { makeDuelBot, DUEL_BOT_NAMES } from '../shared/bots/duel-bots.ts';
|
||||
import { makeStandinSim } from '../scripts/sim/duel-standin-adapter.ts';
|
||||
import { buildDeck, deckSet, ARCHETYPES } from '../scripts/sim/duel-decks.ts';
|
||||
import { playDuel, schedule, DUEL_MIXES, MAX_WORKERS } from '../scripts/sim/duel-run.ts';
|
||||
import { aggregateDuel, duelMarkdown } from '../scripts/sim/duel-stats.ts';
|
||||
|
||||
const SAMPLE = fileURLToPath(new URL('../docs/game/card-sample.json', import.meta.url));
|
||||
const sim = makeStandinSim(SAMPLE);
|
||||
|
||||
test('decks: 40 unique cards from the 236-card sample, archetypes skew types', () => {
|
||||
assert.equal(sim.pool.length, 236);
|
||||
for (const arch of ARCHETYPES) {
|
||||
const d = buildDeck(sim.pool, arch, 3);
|
||||
assert.equal(d.cards.length, 40);
|
||||
assert.equal(new Set(d.cards.map(c => c.id)).size, 40, 'each NFT appears once');
|
||||
assert.ok(d.tags.includes(`arch:${arch}`));
|
||||
}
|
||||
const figs = (arch: (typeof ARCHETYPES)[number]) => buildDeck(sim.pool, arch, 9).cards.filter(c => c.type === 'Figure').length;
|
||||
assert.ok(figs('figure-heavy') > figs('doctrine-heavy'));
|
||||
assert.deepEqual(deckSet(sim.pool, 6, 1).map(d => d.id), deckSet(sim.pool, 6, 1).map(d => d.id));
|
||||
});
|
||||
|
||||
test('duel matches terminate, are deterministic and bots only play legal actions', () => {
|
||||
const decks = deckSet(sim.pool, 4, 2);
|
||||
for (const bots of [['random', 'random'], ['heuristic', 'greedy'], ['mc-lite', 'heuristic']] as [string, string][]) {
|
||||
const a = playDuel(sim, [decks[0], decks[1]], bots, 11);
|
||||
const b = playDuel(sim, [decks[0], decks[1]], bots, 11);
|
||||
assert.equal(a.truncated, false, `${bots} truncated`);
|
||||
assert.deepEqual({ ...a, ms: 0 }, { ...b, ms: 0 });
|
||||
}
|
||||
const { engine, lens } = sim;
|
||||
for (const name of DUEL_BOT_NAMES) {
|
||||
const bot = makeDuelBot(name, engine, lens);
|
||||
let s = engine.createMatch('duel', [{ id: 'a', tags: [], payload: decks[2].cards }, { id: 'b', tags: [], payload: decks[3].cards }], 5);
|
||||
const rng = mulberry32(3);
|
||||
for (let i = 0; i < 400 && !engine.isOver(s); i++) {
|
||||
const seat = engine.toAct(s);
|
||||
const a = bot(engine.observe!(s, seat), seat, rng);
|
||||
assert.ok(engine.legalActions(s, seat).some(x => JSON.stringify(x) === JSON.stringify(a)), `${name} chose an illegal action`);
|
||||
s = engine.applyAction(s, a);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('observation hides the opponent hand and libraries', () => {
|
||||
const decks = deckSet(sim.pool, 2, 4);
|
||||
const s = sim.engine.createMatch('duel', [{ id: 'a', tags: [], payload: decks[0].cards }, { id: 'b', tags: [], payload: decks[1].cards }], 1);
|
||||
const v = sim.engine.observe!(s, 0) as any;
|
||||
assert.equal(v.players[1].hand.length, 0);
|
||||
assert.equal(v.players[1].library.length, 0);
|
||||
assert.equal(v.players[0].library.length, 0);
|
||||
assert.equal(v.view.oppHand, s.players[1].hand.length);
|
||||
});
|
||||
|
||||
test('heuristic beats random; stats and markdown cover the report metrics', () => {
|
||||
const decks = deckSet(sim.pool, 10, 5);
|
||||
const jobs = schedule(40, decks.length, 9, [['random', 'heuristic', 1]]);
|
||||
const recs = jobs.map(j => playDuel(sim, [decks[j.decks[0]], decks[j.decks[1]]], j.bots, j.seed));
|
||||
const stats = aggregateDuel(recs, sim, decks, 0, { label: 't', engine: 'standin', rules: {} });
|
||||
assert.ok(stats.skill['heuristic>random'].rate > 0.8, JSON.stringify(stats.skill));
|
||||
const md = duelMarkdown(stats);
|
||||
for (const k of ['First-player win rate', 'Turns each', 'Stalls', 'Connected', 'Fame vs card win rate', 'Card type', 'Portal', 'Keyword', 'Cost']) assert.match(md, new RegExp(k));
|
||||
assert.ok(stats.connected.pairRate > 0 && stats.connected.pairRate < 1);
|
||||
assert.equal(MAX_WORKERS, 4);
|
||||
assert.ok(Object.keys(DUEL_MIXES).includes('default'));
|
||||
});
|
||||
Reference in New Issue
Block a user