From 003c8f2315a287db99c5be83920bb4f200b8bfbf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:57:31 -0500 Subject: [PATCH] sim-balance: bots see only viewFor(state, seat); stateFromView determinization; makeViewBot for ui-b; engine 2.1 starter decks Co-Authored-By: Claude Opus 5.5 --- scripts/sim/match.ts | 5 +-- scripts/sim/run.ts | 2 +- shared/bots/game-adapter.ts | 66 ++++++++++++++++++++++++++----------- shared/bots/index.ts | 30 +++++++++++------ shared/bots/types.ts | 10 +++--- tests/bots-sim.test.ts | 2 +- 6 files changed, 77 insertions(+), 38 deletions(-) diff --git a/scripts/sim/match.ts b/scripts/sim/match.ts index ffca574..c5cda21 100644 --- a/scripts/sim/match.ts +++ b/scripts/sim/match.ts @@ -7,7 +7,7 @@ export function playMatch( engine: EngineAdapter, ruleset: string, decks: [DeckSpec, DeckSpec], botNames: [string, string], seed: number, ): MatchRecord { const t0 = performance.now(); - const bots: [BotFn, BotFn] = [makeBot(botNames[0], engine), makeBot(botNames[1], engine)]; + const bots: [BotFn, BotFn] = [makeBot(botNames[0], engine), makeBot(botNames[1], engine)]; const rng = [mulberry32(seed ^ 0x9e3779b9), mulberry32(seed ^ 0x85ebca6b)]; let s = engine.createMatch(ruleset, decks, seed); const firstSeat = engine.firstSeat ? engine.firstSeat(s) : engine.toAct(s); @@ -19,7 +19,8 @@ export function playMatch( const turn = engine.turn(s); if (turn !== lastTurn) { evalTrace.push(engine.evaluate(s, 0)); lastTurn = turn; } const seat = engine.toAct(s); - const a = bots[seat](s, seat, rng[seat]); + // Bots see only their seat's observation (shared/game: viewFor), never the full state. + const a = bots[seat](engine.observe ? engine.observe(s, seat) : s, seat, rng[seat]); for (const c of engine.cardsOf(s, a)) cardsPlayed[seat].push(c); const k = engine.actionKind(a); actionKinds[k] = (actionKinds[k] ?? 0) + 1; diff --git a/scripts/sim/run.ts b/scripts/sim/run.ts index 5df0fb0..4e2798a 100644 --- a/scripts/sim/run.ts +++ b/scripts/sim/run.ts @@ -37,7 +37,7 @@ export async function loadEngine(name: string): Promise> pool = loadPool(process.env.SIM_POOL, { keywords: process.env.SIM_KEYWORDS === 'none' ? 'none' : 'faction', costThresholds: process.env.SIM_COST_THRESHOLDS ? JSON.parse(process.env.SIM_COST_THRESHOLDS) : undefined }); } if (pool && process.env.SIM_OWNED) extraDecks.push(...cp.ownedDecks(pool, Number(process.env.SIM_OWNED))); - return makeGameEngine({ rulesets, pool, extraDecks, seededStarters: !process.env.SIM_STARTERS }); + return makeGameEngine({ rulesets, pool, extraDecks }); } throw new Error(`unknown engine ${name}`); } diff --git a/shared/bots/game-adapter.ts b/shared/bots/game-adapter.ts index 09be81a..20329bc 100644 --- a/shared/bots/game-adapter.ts +++ b/shared/bots/game-adapter.ts @@ -1,10 +1,12 @@ // EngineAdapter over the public shared/game API, plus the starter/archetype decks used // by the balance simulation. Pure: rulesets and extra decks are passed in, no I/O. import { - DEFAULT_RULESET, applyAction, createMatch, isOver, lanePower, legalActions, previewPool, replay, result, starterDeck, validateDeck, - type Action, type CardInPlay, type GameCard, type MatchState, type PlayerId, type PlayerState, type Ruleset, + DEFAULT_RULESET, applyAction, createMatch, isOver, lanePower, legalActions, previewPool, replay, result, starterDeck, starterDeckById, STARTER_DECKS, validateDeck, viewFor, Rng as EngineRng, + type DerivationRules, + type Action, type CardInPlay, type GameCard, type MatchState, type PlayerId, type PlayerState, type PlayerView, type Ruleset, } from '../game/index.ts'; import type { DeckSpec, EngineAdapter, Rng, Seat } from './types.ts'; +import { makeBot } from './index.ts'; const other = (p: PlayerId): PlayerId => (p === 0 ? 1 : 0); @@ -62,21 +64,30 @@ export function evaluateFor(state: MatchState, seat: Seat): number { } /** - * Determinize hidden information before a lookahead for `seat`: the opponent's queued plays - * are taken back (it re-decides in the rollouts) and its hand and deck are reshuffled together. + * Rebuild a full MatchState from what `view.you` can see (viewFor), for bots to search on. + * Hidden parts are sampled from `filler`: the opponent's hand and deck, and our own deck order and contents + * (the view gives counts only). The opponent's queue is empty and uncommitted: it re-decides in rollouts. */ -export function determinize(state: MatchState, seat: Seat, rng: Rng): MatchState { - const s = structuredClone(state); - const o = other(seat), opp = s.players[o]; - opp.queue = []; - opp.committed = false; - const pool = [...opp.hand, ...opp.deck]; - for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; } - opp.hand = pool.slice(0, opp.hand.length); - opp.deck = pool.slice(opp.hand.length); - const mine = s.players[seat].deck; - for (let i = mine.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [mine[i], mine[j]] = [mine[j], mine[i]]; } - return s; +export function stateFromView(view: PlayerView, rng: Rng, filler: readonly GameCard[]): MatchState { + let k = 0; + const draw = (n: number) => Array.from({ length: n }, () => ({ ...filler[Math.floor(rng() * filler.length)], cardId: `hidden:${k++}` })); + const me = view.you, them = other(me); + const players = [] as unknown as [PlayerState, PlayerState]; + players[me] = { deck: draw(view.deckCount), hand: view.hand, energy: view.energy, queue: view.queue, committed: view.committed, afk: 0, carry: 0 }; + players[them] = { deck: draw(view.opponent.deckCount), hand: draw(view.opponent.handCount), energy: view.energy, queue: [], committed: false, afk: 0, carry: 0 }; + let seq = 0; + const lanes = view.lanes.map(l => { + const cards = [] as unknown as [CardInPlay[], CardInPlay[]]; + cards[me] = l.cards[0]; cards[them] = l.cards[1]; + for (const side of l.cards) for (const c of side) seq = Math.max(seq, c.seq); + return { topic: l.topic, portalRevealed: l.portalRevealed, cards }; + }); + return { + schema: 'wikideck-match/1', engineVersion: 1, ruleset: view.ruleset, seed: 0, + rng: new EngineRng(Math.floor(rng() * 4294967296)).state, + turn: view.turn, phase: view.phase, initiative: view.initiative, revealSeq: seq, + players, lanes, log: [], actions: [], result: view.result, + }; } /** Energy left after queued plays (the engine deducts queued costs at reveal). */ @@ -169,7 +180,9 @@ export function defaultDecks(rules: Ruleset, extra: DeckSpec[] = [], pool: GameC if (cards) cards = cards.map(repower); if (cards && !validateDeck(rules, cards).length) decks.push({ id, tags: tagDeck(cards, tags), payload: cards }); }; - if (seededStarters) for (let i = 0; i < 6; i++) add(`starter-${i}`, starterDeck(`sim-${i}`), ['arch:starter']); + // DESIGN §2.1 starter decks (engine-pinned loaners). + for (const def of STARTER_DECKS) add(`starter-${def.id}`, starterDeckById(def.id, rules as unknown as DerivationRules), ['arch:starter-v1']); + if (seededStarters) for (let i = 0; i < 6; i++) add(`seeded-${i}`, starterDeck(`sim-${i}`), ['arch:starter']); add('curve', curveDeck(pool, size, copies), ['arch:curve']); add('heavy', buildDeck(pool, c => (c.cost >= 5 ? 10 + c.cost : c.cost >= 4 ? 5 : 0), size, copies), ['arch:heavy']); add('top-heavy', curveDeck(pool, size, copies, undefined, [0, 1, 1, 2, 2, 3, 3]), ['arch:top-heavy']); @@ -191,7 +204,7 @@ export interface GameEngineOptions { extraDecks?: DeckSpec[]; /** Card pool for archetype decks (one copy per page). Default: the engine's starter pool. */ pool?: GameCard[]; - /** Include the engine's seeded placeholder starter decks (default true). */ + /** Also include the engine's seeded placeholder decks `starterDeck(seed)` (default false). */ seededStarters?: boolean; } @@ -199,6 +212,12 @@ export function makeGameEngine(opts: GameEngineOptions = {}): EngineAdapter(); const meta = new Map(); + // Filler for hidden cards: the sim's card pool, powered by the view's ruleset. + const fillerCache = new Map(); + const fillerFor = (r: Ruleset) => { + if (!fillerCache.has(r)) fillerCache.set(r, (opts.pool ?? starterPoolCards()).map(c => ({ ...c, power: r.powerByCost[c.cost] ?? c.power }))); + return fillerCache.get(r)!; + }; const rules = (id: string) => { const r = rulesets[id]; if (!r) throw new Error(`unknown ruleset ${id}`); @@ -209,7 +228,7 @@ export function makeGameEngine(opts: GameEngineOptions = {}): EngineAdapter Object.keys(rulesets), decks(id) { if (!deckCache.has(id)) { - const d = defaultDecks(rules(id), opts.extraDecks, opts.pool, opts.seededStarters ?? true); + const d = defaultDecks(rules(id), opts.extraDecks, opts.pool, opts.seededStarters ?? false); for (const deck of d) for (const c of deck.payload as GameCard[]) meta.set(baseId(c.cardId), c); deckCache.set(id, d); } @@ -234,6 +253,8 @@ export function makeGameEngine(opts: GameEngineOptions = {}): EngineAdapter s.initiative, + observe: (s, seat) => viewFor(s, seat), + assume: (view, _seat, rng) => stateFromView(view as PlayerView, rng, fillerFor((view as PlayerView).ruleset)), keywordValues(final, decks) { const out: { seat: Seat; keyword: string; power: number; flip: number; cards: number }[] = []; const r0 = final.result; @@ -257,8 +278,13 @@ export function makeGameEngine(opts: GameEngineOptions = {}): EngineAdapter (a.type === 'play' ? s.players[a.player].hand.find(c => c.cardId === a.cardId)?.power ?? 0 : -1), - determinize, }; } export const gameEngine = makeGameEngine(); + +/** For the browser AI (ui-b): a bot that takes only the engine PlayerView. */ +export function makeViewBot(name: string, engine: EngineAdapter = gameEngine): (view: PlayerView, rng: Rng) => Action { + const bot = makeBot(name, engine); + return (view, rng) => bot(view, view.you, rng); +} diff --git a/shared/bots/index.ts b/shared/bots/index.ts index c56d5ec..3e2dc28 100644 --- a/shared/bots/index.ts +++ b/shared/bots/index.ts @@ -17,6 +17,11 @@ export function mulberry32(seed: number): Rng { const pick = (xs: T[], rng: Rng): T => xs[Math.floor(rng() * xs.length)]; +/** The state a bot reasons about: a determinization of its observation (or the state itself if the engine has no views). */ +function see(engine: EngineAdapter, obs: unknown, seat: Seat, rng: Rng): S { + return engine.assume ? engine.assume(obs, seat, rng) : (obs as S); +} + function terminalValue(engine: EngineAdapter, s: S, seat: Seat): number { const { winner } = engine.result(s); return winner === null ? 0 : winner === seat ? 1 : -1; @@ -27,8 +32,8 @@ function value(engine: EngineAdapter, s: S, seat: Seat): number { } /** Uniformly random legal action. */ -export function randomBot(engine: EngineAdapter): BotFn { - return (state, player, rng) => pick(engine.legalActions(state, player), rng); +export function randomBot(engine: EngineAdapter): BotFn { + return (obs, player, rng) => pick(engine.legalActions(see(engine, obs, player, rng), player), rng); } function greedyChoice(engine: EngineAdapter, state: S, seat: Seat, actions: A[], rng: Rng): A { @@ -44,16 +49,20 @@ function greedyChoice(engine: EngineAdapter, state: S, seat: Seat, a } /** One-ply: take the action whose resulting state evaluates best for us. Ties broken randomly. */ -export function greedyBot(engine: EngineAdapter): BotFn { - return (state, player, rng) => greedyChoice(engine, state, player, engine.legalActions(state, player), rng); +export function greedyBot(engine: EngineAdapter): BotFn { + return (obs, player, rng) => { + const state = see(engine, obs, player, rng); + return greedyChoice(engine, state, player, engine.legalActions(state, player), rng); + }; } /** * Naive "always play the highest-power card" player (DESIGN §8 target: < 55% vs a smart bot). * Plays the highest printed-power affordable card into a random legal lane; ends the turn when nothing fits. */ -export function maxPowerBot(engine: EngineAdapter): BotFn { - return (state, player, rng) => { +export function maxPowerBot(engine: EngineAdapter): BotFn { + return (obs, player, rng) => { + const state = see(engine, obs, player, rng); const actions = engine.legalActions(state, player); if (!engine.actionPower) return greedyChoice(engine, state, player, actions, rng); let best: A[] = [], bestP = -Infinity; @@ -74,9 +83,10 @@ export interface LookaheadOptions { k?: number; rollouts?: number; horizon?: num * Rollouts run on the true state, so the bot is clairvoyant about hidden info and seeded * draws: an upper bound on skill, not a fair human-like player. */ -export function lookaheadBot(engine: EngineAdapter, opts: LookaheadOptions = {}): BotFn { +export function lookaheadBot(engine: EngineAdapter, opts: LookaheadOptions = {}): BotFn { const k = opts.k ?? 4, rollouts = opts.rollouts ?? 8, horizon = opts.horizon ?? 40, eps = opts.epsilon ?? 0.25; - return (state, seat, rng) => { + return (obs, seat, rng) => { + const state = see(engine, obs, seat, rng); const actions = engine.legalActions(state, seat); if (actions.length === 1) return actions[0]; const shortlist = actions.map(a => { @@ -87,7 +97,7 @@ export function lookaheadBot(engine: EngineAdapter, opts: LookaheadO for (const c of shortlist) { let total = 0; for (let r = 0; r < rollouts; r++) { - let s = engine.determinize ? engine.applyAction(engine.determinize(state, seat, rng), c.a) : c.next, steps = 0; + let s = engine.assume ? engine.applyAction(engine.assume(obs, seat, rng), c.a) : c.next, steps = 0; // fresh hidden sample per rollout while (!engine.isOver(s) && steps < horizon) { const who = engine.toAct(s); const legal = engine.legalActions(s, who); @@ -108,7 +118,7 @@ export function lookaheadBot(engine: EngineAdapter, opts: LookaheadO export const BOT_NAMES = ['random', 'maxpower', 'greedy', 'lookahead-lite', 'lookahead'] as const; export type BotName = typeof BOT_NAMES[number]; -export function makeBot(name: string, engine: EngineAdapter): BotFn { +export function makeBot(name: string, engine: EngineAdapter): BotFn { switch (name) { case 'random': return randomBot(engine); case 'maxpower': return maxPowerBot(engine); diff --git a/shared/bots/types.ts b/shared/bots/types.ts index f22a980..3d0b32f 100644 --- a/shared/bots/types.ts +++ b/shared/bots/types.ts @@ -52,12 +52,14 @@ export interface EngineAdapter { keywordValues?(final: S, decks: [DeckSpec, DeckSpec]): { seat: Seat; keyword: string; power: number; flip: number; cards: number }[]; /** Seat with the first-player advantage (defaults to toAct at match start). */ firstSeat?(state: S): Seat; - /** Resample information hidden from `seat` (opponent hand/staged plays, deck order) before searching. */ - determinize?(state: S, seat: Seat, rng: Rng): S; + /** What `seat` may see (e.g. shared/game viewFor). Bots receive only this. Default: the state itself. */ + observe?(state: S, seat: Seat): unknown; + /** A full state consistent with an observation, hidden parts sampled with `rng` (determinization). */ + assume?(observation: unknown, seat: Seat, rng: Rng): S; } -/** A bot is a pure function of the state it sees. ui-b can reuse it as the browser AI. */ -export type BotFn = (state: S, player: Seat, rng: Rng) => A; +/** A bot is a pure function of what its seat can see (EngineAdapter.observe). ui-b reuses it as the browser AI. */ +export type BotFn = (observation: O, player: Seat, rng: Rng) => A; export interface MatchRecord { ruleset: string; diff --git a/tests/bots-sim.test.ts b/tests/bots-sim.test.ts index 9df3e4d..7f4bfc3 100644 --- a/tests/bots-sim.test.ts +++ b/tests/bots-sim.test.ts @@ -41,7 +41,7 @@ test('bots only return legal actions on shared/game', { skip: !existsSync(new UR let steps = 0; while (!engine.isOver(s) && steps++ < 500) { const seat = engine.toAct(s); - const a = bot(s, seat, rng); + const a = bot(engine.observe ? engine.observe(s, seat) : s, seat, rng); assert.ok(engine.legalActions(s, seat).some(x => JSON.stringify(x) === JSON.stringify(a)), `${name} chose illegal ${JSON.stringify(a)}`); s = engine.applyAction(s, a); }