From 132def8e550459406778b868e8a1f2abc0aa19f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:02:28 -0500 Subject: [PATCH] [sim-balance] Duel adapter onto shared/duel (DuelEngineApi), real-engine sim binding Not a PR yet: needs #72 (contracts) and the engine alpha to merge first. Co-Authored-By: Claude Opus 5.5 --- scripts/sim/duel-core-sim.ts | 52 ++++++++ scripts/sim/duel-run.ts | 1 + shared/bots/duel-adapter.ts | 176 +++++++++++++++++++++++++ tests/sim-balance-duel-adapter.test.ts | 51 +++++++ 4 files changed, 280 insertions(+) create mode 100644 scripts/sim/duel-core-sim.ts create mode 100644 shared/bots/duel-adapter.ts create mode 100644 tests/sim-balance-duel-adapter.test.ts diff --git a/scripts/sim/duel-core-sim.ts b/scripts/sim/duel-core-sim.ts new file mode 100644 index 0000000..346a3ae --- /dev/null +++ b/scripts/sim/duel-core-sim.ts @@ -0,0 +1,52 @@ +// DuelSim binding for duel-core's shared/duel engine, with the 236 sample cards derived by duel-cards. +import { readFileSync, existsSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import type { DuelCard, DuelEngineApi, DuelRuleset } from '../../shared/duel/index.ts'; +import { connectedTierOf, duelMetrics, makeDuelAdapter } from '../../shared/bots/duel-adapter.ts'; +import type { DuelSim } from './duel-sim-types.ts'; +import type { PoolCard } from './duel-decks.ts'; + +export interface DuelPoolCard extends PoolCard { title: string; card: DuelCard } + +const FIXTURE = fileURLToPath(new URL('../../docs/game/duel-card-sample.json', import.meta.url)); + +/** The duel engine's functions, whether engine.ts exports them one by one or as an object. */ +async function loadApi(): Promise { + const mod = '../../shared/duel/engine.ts'; + const m = await import(mod) as Record; + const obj = Object.values(m).find(v => v && typeof v === 'object' && typeof v.createDuel === 'function' && typeof v.statsOf === 'function'); + return (obj ?? m) as DuelEngineApi; +} + +async function loadCards(sampleFile: string): Promise { + try { + const mod = '../../shared/duel/sample.ts'; + const { deriveSample } = await import(mod) as { deriveSample: (c: unknown[], r?: unknown) => DuelCard[] }; + const raw = JSON.parse(readFileSync(sampleFile, 'utf8')).cards; + // SIM_DERIVE: JSON patch over duel-cards' DERIVE_RULES (data-only derivation tuning). + if (!process.env.SIM_DERIVE) return deriveSample(raw); + const d = await import('../../shared/duel/derive.ts' as string) as { DERIVE_RULES: Record }; + return deriveSample(raw, { ...d.DERIVE_RULES, ...JSON.parse(process.env.SIM_DERIVE) }); + } catch (e) { + if (process.env.SIM_DERIVE || !existsSync(FIXTURE)) throw e; + return JSON.parse(readFileSync(FIXTURE, 'utf8')).cards as DuelCard[]; + } +} + +export async function makeDuelSim(sampleFile: string, overrides: Record = {}): Promise> { + const api = await loadApi(); + const rs = await import('../../shared/duel/ruleset.ts') as { mergeDuelRuleset: (o: unknown) => DuelRuleset }; + const rules = rs.mergeDuelRuleset(overrides); + const cards = await loadCards(sampleFile); + const pool: DuelPoolCard[] = cards.map(c => ({ + id: c.cardId, title: c.title, type: c.type, portal: c.portal, cost: c.cost, keywords: [...c.keywords], + fame: (c as any).basis?.fame, card: c, + })); + const engine = makeDuelAdapter(api, { rules, pool: cards }); + return { + name: 'duel', engine, lens: engine.lens, pool, + deckPayload: cs => cs.map(c => c.card), + metrics: duelMetrics, + connected: (a, b) => connectedTierOf(a.card, b.card, rules.connectedTiers), + }; +} diff --git a/scripts/sim/duel-run.ts b/scripts/sim/duel-run.ts index 8d1f8a2..5fc9e00 100644 --- a/scripts/sim/duel-run.ts +++ b/scripts/sim/duel-run.ts @@ -55,6 +55,7 @@ export function playDuel(sim: DuelSim, decks: [SimDeck, SimDeck], bo export const DUEL_MIXES: Record = { 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]], + mirror: [['mc-lite', 'mc-lite', 1]], skill: [['heuristic', 'mc', 0.4], ['random', 'heuristic', 0.2], ['greedy', 'heuristic', 0.2], ['heuristic', 'mc-lite', 0.2]], }; diff --git a/shared/bots/duel-adapter.ts b/shared/bots/duel-adapter.ts new file mode 100644 index 0000000..b89d718 --- /dev/null +++ b/shared/bots/duel-adapter.ts @@ -0,0 +1,176 @@ +// EngineAdapter + DuelLens over duel-core's shared/duel engine (DuelEngineApi, docs/game/DUEL_API.md), +// for the duel bots (shared/bots/duel-bots.ts) and the balance sim (scripts/sim/duel-run.ts). Pure, no I/O: +// the engine module and the card pool are passed in. +import type { + CardInstance, ConnectedTier, DuelAction, DuelCard, DuelEngineApi, DuelRuleset, DuelState, Permanent, PlayerView, Seat, +} from '../duel/index.ts'; +import type { EngineAdapter, Rng } from './types.ts'; +import { duelEvaluate, type DuelLens, type LensAction, type LensCreature } from './duel-bots.ts'; + +/** What a duel bot sees: its seat's view, its own decklist (players know their deck) and its legal actions. */ +export interface DuelObservation { view: PlayerView; deck: DuelCard[]; legal: DuelAction[] } + +const KW_VALUE: Record = { Featured: 1, Protected: 0.4, 'Well-sourced': 0.5, Legacy: 0.5, Stub: 0.5, Multilingual: 0.4, Translated: 0.2, Local: 0.2, Trending: 0.3 }; + +/** Connected test between two cards (DUEL_API "Connected"), for the pairwise pool rate. */ +export function connectedTierOf(a: DuelCard, b: DuelCard, tiers: readonly ConnectedTier[]): ConnectedTier | null { + if (a.cardId === b.cardId || !a.connect || !b.connect) return null; + const meets = (x: readonly T[], y: readonly T[]) => x.some(v => y.includes(v)); + for (const t of tiers) { + if (t === 'Linked' && ((b.pageId !== null && a.connect.links.includes(b.pageId)) || (a.pageId !== null && b.connect.links.includes(a.pageId)))) return t; + if (t === 'Compatriot' && meets(a.connect.countries, b.connect.countries)) return t; + if (t === 'Contemporary' && a.type !== b.type && meets(a.connect.centuries, b.connect.centuries)) return t; + if (t === 'Kin' && meets(a.connect.p31.filter(q => q !== 'Q5' && q !== 'Q16521'), b.connect.p31)) return t; + } + return null; +} + +export function makeDuelLens(api: DuelEngineApi): DuelLens { + const stats = (s: DuelState, p: Permanent) => { try { return api.statsOf(s, p.uid); } catch { return { power: p.card.power ?? 0, toughness: p.card.toughness ?? 0 }; } }; + const blocker = (p: Permanent) => p.card.type === 'Figure' || (p.card.type === 'Location' && (p.card.toughness ?? 0) > 0); + return { + phase: s => (s.phase === 'over' ? 'other' : s.phase), + life: (s, seat) => s.players[seat].life, + handSize: (s, seat) => s.players[seat].hand.length, + creatures: (s, seat): LensCreature[] => s.battlefield.filter(p => p.controller === seat && blocker(p)).map(p => { + const { power, toughness } = stats(s, p); + const left = Math.max(0, toughness - p.damage); + const kw = (p.card.keywords ?? []).reduce((t, k) => t + (KW_VALUE[k] ?? 0), 0); + const fig = p.card.type === 'Figure'; + return { uid: p.uid, power, toughness: left, tapped: p.tapped, canAttack: fig && !p.tapped && !p.sick, canBlock: !p.tapped, value: fig ? power + left * 0.8 + 0.5 + kw : left * 0.5 }; + }), + attackers: s => s.combat.attackers, + blocks: s => Object.entries(s.combat.blocks) as [string, string][], + decode: (s, a): LensAction => { + switch (a.type) { + case 'play': { + const c = s.players[s.active].hand.find(h => h.uid === a.uid)?.card; + return { kind: 'play', cost: c?.cost ?? 0, cardType: c?.type ?? '?' }; + } + case 'toggleAttacker': return { kind: 'attack', uid: a.uid, on: true }; + case 'confirmAttack': return { kind: 'confirmAttack' }; + case 'block': return { kind: 'block', blocker: a.blocker, attacker: a.attacker }; + case 'confirmBlocks': return { kind: 'confirmBlocks' }; + case 'endPhase': return { kind: 'endMain' }; + case 'keep': return { kind: 'keep' }; + case 'mulligan': return { kind: 'mulligan' }; + default: return { kind: 'other' }; + } + }, + }; +} + +function shuffled(xs: T[], rng: Rng): T[] { + const a = [...xs]; + for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } + return a; +} + +/** + * Rebuild a full DuelState from a seat's observation (a determinization). Hidden zones are sampled: + * our library from our decklist minus every card we can see, the opponent's hand and library from `pool` + * minus everything visible. Permanent modifiers are recovered exactly from the view's current + * power/toughness (whatever statsOf doesn't recompute goes into permPower/permToughness). + */ +export function stateFromObservation(api: DuelEngineApi, obs: DuelObservation, seat: Seat, rng: Rng, pool: readonly DuelCard[]): DuelState { + const v = obs.view, o = (1 - seat) as Seat; + const seen = new Set(); + const mark = (c: DuelCard) => seen.add(c.cardId); + v.you.hand.forEach(h => mark(h.card)); + v.you.graveyard.forEach(g => mark(g.card)); + v.opponent.graveyard.forEach(g => mark(g.card)); + v.battlefield.forEach(p => mark(p.card)); + const ownLeft = shuffled(obs.deck.filter(c => !seen.has(c.cardId) && !v.battlefield.some(p => p.card.cardId === c.cardId && p.owner === seat)), rng); + const oppPool = shuffled(pool.filter(c => !seen.has(c.cardId) && !obs.deck.some(d => d.cardId === c.cardId)), rng); + let k = 0; + const hidden = (owner: Seat, card: DuelCard): CardInstance => ({ uid: `${owner}:h${k++}`, owner, card }); + const take = (n: number) => Array.from({ length: n }, (_, i) => hidden(o, oppPool[i % Math.max(1, oppPool.length)] ?? obs.deck[0])); + const oppHand = take(v.opponent.handSize); + const oppLib = Array.from({ length: v.opponent.librarySize }, (_, i) => hidden(o, oppPool[(v.opponent.handSize + i) % Math.max(1, oppPool.length)] ?? obs.deck[0])); + const myLib = Array.from({ length: v.you.librarySize }, (_, i) => hidden(seat, ownLeft[i % Math.max(1, ownLeft.length)] ?? obs.deck[0])); + const side = (sv: PlayerView['opponent'], hand: CardInstance[], library: CardInstance[]) => { + const territory = Math.min(v.rules.territoryCap, v.battlefield.filter(p => p.controller === sv.seat && p.card.type === 'Location').reduce((t, p) => t + (p.card.territory ?? 0), 0)); + return { + life: sv.life, citations: sv.citations, baseCitations: Math.max(0, sv.maxCitations - territory), library, hand, graveyard: sv.graveyard, + mulligansTaken: sv.mulligansTaken, ready: sv.ready, locationsThisTurn: 0, bankSeconds: sv.bankSeconds, timeouts: 0, fatigue: 0, + }; + }; + const players = [] as unknown as DuelState['players']; + players[seat] = side(v.you, v.you.hand, myLib); + players[o] = side(v.opponent, oppHand, oppLib); + // Locations played this turn aren't in the view: if we hold an affordable Location that isn't legal to play, assume one was played. + if (v.active === seat && v.phase === 'main') { + const legalUids = new Set(obs.legal.flatMap(a => (a.type === 'play' ? [a.uid] : []))); + players[seat].locationsThisTurn = v.you.hand.some(h => h.card.type === 'Location' && h.card.cost <= v.you.citations && !legalUids.has(h.uid)) ? 1 : 0; + } + const battlefield: Permanent[] = v.battlefield.map((p, i) => ({ + uid: p.uid, owner: p.owner, controller: p.controller, card: p.card, tapped: p.tapped, sick: p.sick, damage: p.damage, counters: p.counters, + permPower: 0, permToughness: 0, tempPower: 0, tempToughness: 0, tempKeywords: [], permKeywords: [], attachedTo: p.attachedTo, + shielded: false, entered: i, connectedLogged: true, + })); + const s: DuelState = { + engine: 'duel', rules: v.rules, seed: 'assumed', rng: Math.floor(rng() * 2 ** 32) >>> 0, turn: v.turn, active: v.active, + firstSeat: v.active, phase: v.phase, players, battlefield, combat: structuredClone(v.combat), log: [], result: v.result, + version: v.version, nextToken: 100000 + v.version, nextEntry: battlefield.length, + }; + for (const p of battlefield) { + const want = v.battlefield.find(x => x.uid === p.uid)!; + try { + const got = api.statsOf(s, p.uid); + p.permPower = want.power - got.power; + p.permToughness = want.toughness - got.toughness; + } catch { /* keep zero */ } + const extra = want.keywords.filter(kw => !(p.card.keywords ?? []).includes(kw)); + if (extra.length) p.permKeywords = extra; + } + return s; +} + +export interface DuelAdapterOptions { rules: DuelRuleset; pool: readonly DuelCard[] } + +export function makeDuelAdapter(api: DuelEngineApi, opts: DuelAdapterOptions): EngineAdapter & { lens: DuelLens } { + const lens = makeDuelLens(api); + const decks = new WeakMap(); + const deckOf = new Map(); + const adapter: EngineAdapter & { lens: typeof lens } = { + name: 'duel', + lens, + rulesets: () => [opts.rules.version], + decks: () => [], + createMatch: (_r, specs, seed) => { + const d: [DuelCard[], DuelCard[]] = [specs[0].payload as DuelCard[], specs[1].payload as DuelCard[]]; + const s = api.createDuel(opts.rules, d, String(seed)); + decks.set(s, d); deckOf.set(s.seed, d); + return s; + }, + toAct: s => api.toAct(s) ?? s.active, + legalActions: (s, seat) => api.legalActions(s, seat), + applyAction: (s, a) => api.applyAction(s, api.toAct(s) ?? s.active, a), + isOver: s => api.isOver(s), + result: s => { const r = api.result(s); return { winner: r?.winner ?? null, reason: r?.reason }; }, + turn: s => s.turn, + evaluate: (s, seat) => duelEvaluate(lens, s, seat), + cardsOf: (s, a) => (a.type === 'play' ? [s.players[api.toAct(s) ?? s.active].hand.find(h => h.uid === a.uid)?.card.cardId ?? a.uid] : []), + actionKind: a => a.type, + firstSeat: s => s.firstSeat, + observe: (s, seat): DuelObservation => ({ view: api.viewFor(s, seat), deck: (deckOf.get(s.seed) ?? decks.get(s) ?? [[], []])[seat], legal: api.legalActions(s, seat) }), + assume: (obs, seat, rng) => stateFromObservation(api, obs as DuelObservation, seat, rng, opts.pool), + }; + return adapter; +} + +/** Per-match numbers from the omniscient log, for DUEL_BALANCE.md. */ +export function duelMetrics(s: DuelState): Record { + const m: Record = { connectedFires: 0, plays: 0, rivalries: 0, destroyed: 0, mulligans: 0, tokens: 0, discards: 0 }; + for (const e of s.log) { + if (e.kind === 'connected') m.connectedFires++; + else if (e.kind === 'deploy' || e.kind === 'cast' || e.kind === 'adopt') m.plays++; + else if (e.kind === 'rivalry') m.rivalries++; + else if (e.kind === 'destroyed') m.destroyed++; + else if (e.kind === 'mulligan') m.mulligans++; + else if (e.kind === 'tokenCreated') m.tokens++; + else if (e.kind === 'discard') m.discards++; + } + m.lifeLeft = s.result?.winner != null ? s.players[s.result.winner].life : 0; + return m; +} diff --git a/tests/sim-balance-duel-adapter.test.ts b/tests/sim-balance-duel-adapter.test.ts new file mode 100644 index 0000000..257aa09 --- /dev/null +++ b/tests/sim-balance-duel-adapter.test.ts @@ -0,0 +1,51 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { mulberry32 } from '../shared/bots/index.ts'; +import { makeDuelBot, DUEL_BOT_NAMES } from '../shared/bots/duel-bots.ts'; +import { deckSet } from '../scripts/sim/duel-decks.ts'; +import { playDuel } from '../scripts/sim/duel-run.ts'; + +const hasEngine = existsSync(new URL('../shared/duel/engine.ts', import.meta.url)); +const SAMPLE = fileURLToPath(new URL('../docs/game/card-sample.json', import.meta.url)); + +test('duel adapter: bots play legal actions on shared/duel and matches end', { skip: !hasEngine && 'shared/duel/engine.ts not merged yet' }, async () => { + const { makeDuelSim } = await import('../scripts/sim/duel-core-sim.ts'); + const sim = await makeDuelSim(SAMPLE); + const decks = deckSet(sim.pool, 4, 3); + assert.equal(decks[0].cards.length, 40); + for (const name of DUEL_BOT_NAMES) { + const bot = makeDuelBot(name, sim.engine, sim.lens); + let s = sim.engine.createMatch('duel', [{ id: 'a', tags: [], payload: sim.deckPayload(decks[0].cards) }, { id: 'b', tags: [], payload: sim.deckPayload(decks[1].cards) }], 9); + const rng = mulberry32(4); + for (let i = 0; i < (name.startsWith('mc') ? 150 : 1500) && !sim.engine.isOver(s); i++) { + const seat = sim.engine.toAct(s); + const legal = sim.engine.legalActions(s, seat); + const a = bot(sim.engine.observe!(s, seat), seat, rng); + assert.ok(legal.some(x => JSON.stringify(x) === JSON.stringify(a)), `${name} chose an illegal action`); + s = sim.engine.applyAction(s, a); + } + } + const r1 = playDuel(sim, [decks[2], decks[3]], ['heuristic', 'heuristic'], 21); + const r2 = playDuel(sim, [decks[2], decks[3]], ['heuristic', 'heuristic'], 21); + assert.equal(r1.truncated, false); + assert.deepEqual({ ...r1, ms: 0 }, { ...r2, ms: 0 }); +}); + +test('duel adapter: determinization keeps the visible state and the view', { skip: !hasEngine && 'shared/duel/engine.ts not merged yet' }, async () => { + const { makeDuelSim } = await import('../scripts/sim/duel-core-sim.ts'); + const sim = await makeDuelSim(SAMPLE); + const decks = deckSet(sim.pool, 2, 8); + let s = sim.engine.createMatch('duel', [{ id: 'a', tags: [], payload: sim.deckPayload(decks[0].cards) }, { id: 'b', tags: [], payload: sim.deckPayload(decks[1].cards) }], 5); + const bot = makeDuelBot('heuristic', sim.engine, sim.lens); + const rng = mulberry32(1); + for (let i = 0; i < 120 && !sim.engine.isOver(s); i++) { const seat = sim.engine.toAct(s); s = sim.engine.applyAction(s, bot(sim.engine.observe!(s, seat), seat, rng)); } + const seat = sim.engine.toAct(s); + const obs = sim.engine.observe!(s, seat) as any; + const guess = sim.engine.assume!(obs, seat, rng) as any; + assert.equal(guess.players[seat].hand.length, s.players[seat].hand.length); + assert.equal(guess.players[1 - seat].hand.length, s.players[1 - seat].hand.length); + assert.equal(guess.players[seat].library.length, s.players[seat].library.length); + assert.equal(sim.engine.evaluate(guess, seat).toFixed(6), sim.engine.evaluate(s, seat).toFixed(6), 'material eval sees only public info'); +});