Files
wikideck/scripts/sim/match.ts

54 lines
2.4 KiB
TypeScript

import { makeBot, mulberry32 } from '../../shared/bots/index.ts';
import type { BotFn, DeckSpec, EngineAdapter, MatchRecord, Seat } from '../../shared/bots/types.ts';
export const MAX_ACTIONS = 2000;
export function playMatch<S, A>(
engine: EngineAdapter<S, A>, ruleset: string, decks: [DeckSpec, DeckSpec], botNames: [string, string], seed: number,
): MatchRecord {
const t0 = performance.now();
const bots: [BotFn<unknown, A>, BotFn<unknown, A>] = [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);
const evalTrace: number[] = [];
const cardsPlayed: [string[], string[]] = [[], []];
const actionKinds: Record<string, number> = {};
let actions = 0, lastTurn = -1;
while (!engine.isOver(s) && actions < MAX_ACTIONS) {
const turn = engine.turn(s);
if (turn !== lastTurn) { evalTrace.push(engine.evaluate(s, 0)); lastTurn = turn; }
const seat = engine.toAct(s);
// 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;
s = engine.applyAction(s, a);
actions++;
}
const truncated = !engine.isOver(s);
const { winner, reason } = truncated ? { winner: null, reason: 'action-cap' } : engine.result(s);
return {
ruleset, seed,
decks: [decks[0].id, decks[1].id],
deckTags: [decks[0].tags, decks[1].tags],
bots: [botNames[0], botNames[1]],
firstSeat, winner, reason,
turns: engine.turn(s), actions, truncated,
evalTrace, decidedTurn: decidedTurn(evalTrace, winner),
cardsPlayed, actionKinds,
keywordValues: !truncated && engine.keywordValues ? engine.keywordValues(s, decks) : undefined,
ms: performance.now() - t0,
};
}
/** First turn (1-based) from which the eventual winner stayed ahead on eval through the end. */
export function decidedTurn(trace: number[], winner: Seat | null): number | null {
if (winner === null || !trace.length) return null;
const sign = winner === 0 ? 1 : -1;
let t = trace.length;
while (t > 0 && trace[t - 1] * sign > 0.05) t--;
return Math.min(t + 1, trace.length);
}