Files
wikideck/shared/bots/game-adapter.ts
T
claudeandClaude Opus 5.5 9841622ac7 sim-balance: bots (random/greedy/lookahead), sim runner and stats
Bots are pure (state, player, rng) => action over an EngineAdapter;
shared/bots/game-adapter.ts adapts the shared/game API (hidden staged
plays, determinized lookahead). scripts/sim/run.ts runs N matches per
ruleset across child processes and writes per-ruleset markdown/JSON.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:54:53 -05:00

168 lines
7.8 KiB
TypeScript

// 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, STARTER_POOL, applyAction, createMatch, isOver, lanePower,
legalActions, result, starterCard, starterDeck, validateDeck,
type Action, type CardInPlay, type GameCard, type MatchState, type PlayerId, type Ruleset,
} from '../game/index.ts';
import type { DeckSpec, EngineAdapter, Rng, Seat } from './types.ts';
const other = (p: PlayerId): PlayerId => (p === 0 ? 1 : 0);
/**
* Lane outcome as `seat` sees it: its own revealed and staged cards against the opponent's
* revealed cards only (staged opponent plays are hidden). Ongoing effects included, onReveal not.
*/
export function projectedLanes(state: MatchState, seat: Seat): [number, number][] {
const me = state.players[seat];
if (!me.staged.length) return state.lanes.map((_, i) => orient(lanePower(state, i), seat));
const lanes = state.lanes.map(l => ({ ...l, cards: [[...l.cards[0]], [...l.cards[1]]] as [CardInPlay[], CardInPlay[]] }));
for (const play of me.staged) {
const card = me.hand.find(c => c.id === play.cardId);
if (card) lanes[play.lane].cards[seat].push({ card, owner: seat, lane: play.lane, turn: state.turn, bonus: 0 });
}
const view = { ...state, lanes } as MatchState;
return lanes.map((_, i) => orient(lanePower(view, i), seat));
}
const orient = (p: [number, number], seat: Seat): [number, number] => (seat === 0 ? p : [p[1], p[0]]);
/** Heuristic for `seat` in [-1, 1]: soft lane wins, weighted up as the match nears its end. */
export function evaluateFor(state: MatchState, seat: Seat): number {
if (state.result) return state.result.winner === null ? 0 : state.result.winner === seat ? 1 : -1;
const lanes = projectedLanes(state, seat);
const scale = 4;
let lane = 0, total = 0;
for (const [a, b] of lanes) { lane += Math.tanh((a - b) / scale); total += a - b; }
const me = state.players[seat], them = state.players[other(seat)];
const handEdge = (me.hand.length - me.staged.length - (them.hand.length - them.staged.length)) * 0.02;
const unspent = me.energy * -0.01; // nudge greedy to use its energy
const v = (lane + Math.tanh(total / 20) * 0.3) / (state.lanes.length + 0.3) + handEdge + unspent;
return Math.max(-1, Math.min(1, v));
}
/**
* Determinize hidden information before a lookahead for `seat`: the opponent's staged plays
* are taken back (it re-decides in the rollouts) and its hand and deck are reshuffled together.
*/
export function determinize(state: MatchState, seat: Seat, rng: Rng): MatchState {
const s = structuredClone(state);
const o = other(seat), opp = s.players[o];
if (opp.staged.length || opp.ended) {
const refund = opp.staged.reduce((t, p) => t + (opp.hand.find(c => c.id === p.cardId)?.cost ?? 0), 0);
opp.energy += refund;
opp.staged = [];
opp.ended = 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;
}
// ---------- decks ----------
type Spec = (typeof STARTER_POOL)[number];
function tagDeck(cards: GameCard[], base: string[]): string[] {
const tags = new Set(base);
const cats = new Map<string, number>();
const kws = new Map<string, number>();
for (const c of cards) {
cats.set(c.category, (cats.get(c.category) ?? 0) + 1);
kws.set(c.keyword ?? 'vanilla', (kws.get(c.keyword ?? 'vanilla') ?? 0) + 1);
}
const [topCat, nCat] = [...cats].sort((a, b) => b[1] - a[1])[0];
if (nCat >= cards.length / 3) tags.add(`cat:${topCat}`);
for (const [k, n] of kws) if (n >= cards.length / 2) tags.add(`kw:${k}-heavy`);
const avg = cards.reduce((t, c) => t + c.cost, 0) / cards.length;
tags.add(avg <= 2.75 ? 'curve:low' : avg >= 4 ? 'curve:high' : 'curve:mid');
return [...tags];
}
/** Build a deck of `size` from specs ranked by `score`, up to `copies` per page. */
function themed(score: (s: Spec) => number, size: number, copies: number): GameCard[] {
const ranked = [...STARTER_POOL].map(s => ({ s, v: score(s) })).filter(x => x.v > 0).sort((a, b) => b.v - a.v || a.s[3] - b.s[3]);
const out: GameCard[] = [];
for (let copy = 0; copy < copies && out.length < size; copy++)
for (const { s } of ranked) { if (out.length >= size) break; out.push(starterCard(s, copy)); }
return out;
}
export function defaultDecks(rules: Ruleset, extra: DeckSpec[] = []): DeckSpec[] {
const size = rules.deck.min, copies = rules.deck.maxCopiesPerPage;
const decks: DeckSpec[] = [];
for (let i = 0; i < 8; i++) {
const cards = starterDeck(`sim-${i}`, rules);
decks.push({ id: `starter-${i}`, tags: tagDeck(cards, ['arch:starter']), payload: cards });
}
const arche: [string, (s: Spec) => number][] = [
['rally', s => (s[5] === 'rally' ? 10 - s[3] : s[3] <= 2 ? 1 : 0)],
['anchor', s => (s[5] === 'anchor' ? 10 - s[3] : s[3] <= 2 ? 1 : 0)],
['vanilla', s => (s[5] === null ? 10 - Math.abs(3.5 - s[3]) : 0)],
['low-curve', s => (s[3] <= 3 ? 10 + s[4] - s[3] : 0)],
['high-curve', s => (s[3] >= 3 ? s[3] : 0)],
];
for (const [name, score] of arche) {
const cards = themed(score, size, copies);
if (!validateDeck(rules, cards).length) decks.push({ id: name, tags: tagDeck(cards, [`arch:${name}`]), payload: cards });
}
for (const d of extra) if (!validateDeck(rules, d.payload as GameCard[]).length)
decks.push({ ...d, tags: tagDeck(d.payload as GameCard[], d.tags) });
return decks;
}
// ---------- adapter ----------
export interface GameEngineOptions {
rulesets?: Record<string, Ruleset>;
extraDecks?: DeckSpec[];
}
export function makeGameEngine(opts: GameEngineOptions = {}): EngineAdapter<MatchState, Action> {
const rulesets = opts.rulesets ?? { base: DEFAULT_RULESET };
const deckCache = new Map<string, DeckSpec[]>();
const meta = new Map<string, GameCard>();
const rules = (id: string) => {
const r = rulesets[id];
if (!r) throw new Error(`unknown ruleset ${id}`);
return r;
};
return {
name: 'shared/game',
rulesets: () => Object.keys(rulesets),
decks(id) {
if (!deckCache.has(id)) {
const d = defaultDecks(rules(id), opts.extraDecks);
for (const deck of d) for (const c of deck.payload as GameCard[]) meta.set(c.id, c);
deckCache.set(id, d);
}
return deckCache.get(id)!;
},
createMatch: (id, decks, seed) => createMatch(rules(id), [decks[0].payload as GameCard[], decks[1].payload as GameCard[]], `sim-${seed}`),
// Simultaneous turns: seat 0 stages first, then seat 1. Bots never read the other side's staged plays
// (evaluateFor hides them; lookahead determinizes), so the order leaks nothing.
toAct: s => (s.players[0].ended ? 1 : 0),
// Unstage is excluded: it never helps a bot and lets random bots loop.
legalActions: (s, seat) => legalActions(s, seat).filter(a => a.type !== 'unstage'),
applyAction,
isOver,
result: s => { const r = result(s); return { winner: r?.winner ?? null, reason: r?.reason }; },
turn: s => s.turn,
evaluate: evaluateFor,
cardsOf: (_s, a) => (a.type === 'play' ? [a.cardId.replace(/:\d+$/, '')] : []),
actionKind: a => a.type,
cardMeta(id) {
const c = meta.get(id) ?? meta.get(`${id}:0`);
if (!c) return undefined;
return { label: c.name, cost: c.cost, power: c.power, powerPerCost: c.power / Math.max(1, c.cost), keyword: c.keyword ?? 'vanilla', category: c.category };
},
firstSeat: s => s.firstToReveal,
determinize,
};
}
export const gameEngine = makeGameEngine();