294 lines
16 KiB
TypeScript
294 lines
16 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, 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);
|
|
|
|
/**
|
|
* 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.queue.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.queue) {
|
|
const card = me.hand.find(c => c.cardId === play.cardId);
|
|
if (card) lanes[play.lane].cards[seat].push({ card, owner: seat, lane: play.lane, turn: state.turn, bonus: 0, seq: 1e9 + lanes[play.lane].cards[seat].length });
|
|
}
|
|
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]]);
|
|
|
|
/**
|
|
* Lanes after hypothetically resolving this turn with `seat`'s queue and an opponent who passes
|
|
* (its hidden queue is dropped), so on-reveal and end-of-turn keywords and reveal order count.
|
|
* Falls back to projectedLanes if the engine refuses.
|
|
*/
|
|
export function resolvedLanes(state: MatchState, seat: Seat): [number, number][] | MatchState {
|
|
try {
|
|
let s = { ...state, players: state.players.map(p => ({ ...p })) as MatchState['players'] };
|
|
const o = other(seat);
|
|
s.players[o].queue = [];
|
|
s.players[o].committed = false;
|
|
if (!s.players[seat].committed) s = applyAction(s, { type: 'commit', player: seat });
|
|
s = applyAction(s, { type: 'commit', player: o });
|
|
if (s.result) return s;
|
|
return s.lanes.map((_, i) => orient(lanePower(s, i), seat));
|
|
} catch {
|
|
return projectedLanes(state, seat);
|
|
}
|
|
}
|
|
|
|
/** Heuristic for `seat` in [-1, 1]: soft lane wins plus total power, from the hypothetically resolved turn. */
|
|
export function evaluateFor(state: MatchState, seat: Seat): number {
|
|
if (state.result) return state.result.winner === null ? 0 : state.result.winner === seat ? 1 : -1;
|
|
const r = state.players[seat].queue.length ? resolvedLanes(state, seat) : projectedLanes(state, seat);
|
|
if (!Array.isArray(r)) return r.result!.winner === null ? 0 : r.result!.winner === seat ? 0.95 : -0.95;
|
|
const lanes = r;
|
|
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)];
|
|
// Hand sizes include queued cards on both sides: the opponent's queue size is hidden information.
|
|
const handEdge = (me.hand.length - them.hand.length) * 0.02;
|
|
const unspent = energyLeft(me) * -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));
|
|
}
|
|
|
|
/**
|
|
* 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 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 };
|
|
// Before #38 handCount excludes queued cards and queuedCount exists; after #38 handCount is the full hand.
|
|
const o = view.opponent as { handCount: number; deckCount: number; queuedCount?: number };
|
|
players[them] = { deck: draw(o.deckCount), hand: draw(o.handCount + (o.queuedCount ?? 0)), 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). */
|
|
export function energyLeft(p: PlayerState): number {
|
|
return p.energy - p.queue.reduce((t, q) => t + (p.hand.find(c => c.cardId === q.cardId)?.cost ?? 0), 0);
|
|
}
|
|
|
|
// ---------- decks ----------
|
|
|
|
/** DESIGN §10.1: cost-1 cards have no keyword and get +vanillaBonus (if the ruleset has that key). */
|
|
function vanillaBonus(rules: Ruleset, c: GameCard): number {
|
|
const v = (rules as unknown as Record<string, unknown>).vanillaBonus;
|
|
return typeof v === 'number' && c.cost === 1 ? v : 0;
|
|
}
|
|
|
|
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.faction, (cats.get(c.faction) ?? 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 / 2) 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.5 ? 'curve:low' : avg >= 4.25 ? 'curve:high' : 'curve:mid');
|
|
return [...tags];
|
|
}
|
|
|
|
/** Base (one copy) cards of the default sim pool: the engine's preview pool. */
|
|
export function starterPoolCards(): GameCard[] {
|
|
return previewPool().map(c => ({ ...c, cardId: baseId(c.cardId) }));
|
|
}
|
|
|
|
/** Card id without its copy suffix (`loaner:123:1` -> `loaner:123`). */
|
|
export const baseId = (id: string) => id.replace(/:\d+$/, '');
|
|
const copyOf = (c: GameCard, copy: number): GameCard => ({ ...c, cardId: `${c.cardId}:${copy}` });
|
|
const pageKey = (c: GameCard): string | number => c.pageId ?? baseId(c.cardId);
|
|
|
|
/**
|
|
* Fill a deck of `size` from `pool`, best `score` first (score <= 0 = excluded, ties: higher power),
|
|
* up to `copies` per page. Returns null if the pool can't fill it.
|
|
*/
|
|
export function buildDeck(pool: GameCard[], score: (c: GameCard) => number, size: number, copies: number): GameCard[] | null {
|
|
const ranked = pool.map(c => ({ c, v: score(c) })).filter(x => x.v > 0).sort((a, b) => b.v - a.v || b.c.power - a.c.power);
|
|
const out: GameCard[] = [];
|
|
const used = new Map<string | number, number>();
|
|
for (let copy = 0; copy < copies && out.length < size; copy++)
|
|
for (const { c } of ranked) {
|
|
if (out.length >= size) break;
|
|
const k = pageKey(c), n = used.get(k) ?? 0;
|
|
if (n > copy) continue;
|
|
used.set(k, n + 1);
|
|
out.push(copyOf(c, copy));
|
|
}
|
|
return out.length === size ? out : null;
|
|
}
|
|
|
|
/** Deck that follows a target cost curve (counts per cost 1..6), using `filter`ed cards first. */
|
|
function curveDeck(pool: GameCard[], size: number, copies: number, filter: (c: GameCard) => boolean = () => true, curve = [0, 2, 3, 3, 2, 1, 1]): GameCard[] | null {
|
|
const target = curve.map(n => Math.round((n * size) / 12));
|
|
const out: GameCard[] = [];
|
|
const used = new Map<string | number, number>();
|
|
const take = (c: GameCard) => { const k = pageKey(c), n = used.get(k) ?? 0; if (n >= copies) return false; used.set(k, n + 1); out.push(copyOf(c, n)); return true; };
|
|
for (let cost = 1; cost <= 6; cost++) {
|
|
const cands = pool.filter(c => c.cost === cost).sort((a, b) => Number(filter(b)) - Number(filter(a)) || b.power - a.power);
|
|
let need = target[cost];
|
|
for (let pass = 0; pass < copies && need > 0; pass++) for (const c of cands) { if (need <= 0) break; if (take(c)) need--; }
|
|
}
|
|
const rest = [...pool].sort((a, b) => Number(filter(b)) - Number(filter(a)) || Math.abs(a.cost - 3) - Math.abs(b.cost - 3));
|
|
for (let pass = 0; pass < copies && out.length < size; pass++) for (const c of rest) { if (out.length >= size) break; take(c); }
|
|
return out.length === size ? out.slice(0, size) : null;
|
|
}
|
|
|
|
/**
|
|
* Sim decks: seeded starter decks (if the engine provides them) plus archetypes built from `pool`:
|
|
* curve, heavy (cost >= 5 first), swarm (cost <= 2), mono-faction and keyword-focused curve decks.
|
|
*/
|
|
export function defaultDecks(rules: Ruleset, extra: DeckSpec[] = [], pool: GameCard[] = starterPoolCards(), seededStarters = true): DeckSpec[] {
|
|
const size = rules.deckSize, copies = rules.maxCopiesPerPage;
|
|
const decks: DeckSpec[] = [];
|
|
// DESIGN §1.3: power depends only on cost, so loaners follow the ruleset's powerByCost.
|
|
// §10.1 powerDelta (applied at derivation, not by the engine).
|
|
const delta = (c: GameCard) => (c.keyword ? (rules.keywordParams?.[c.keyword]?.powerDelta ?? 0) : 0);
|
|
const repower = (c: GameCard): GameCard => (c.source === 'loaner' && rules.powerByCost[c.cost] !== undefined ? { ...c, power: Math.max(0, rules.powerByCost[c.cost] + (c.keyword ? 0 : vanillaBonus(rules, c)) + delta(c)) } : c);
|
|
pool = pool.map(repower);
|
|
const add = (id: string, cards: GameCard[] | null, tags: string[]) => {
|
|
if (cards) cards = cards.map(repower);
|
|
if (cards && !validateDeck(rules, cards).length) decks.push({ id, tags: tagDeck(cards, tags), payload: cards });
|
|
};
|
|
// 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']);
|
|
add('swarm', buildDeck(pool, c => (c.cost <= 2 ? 10 - c.cost : c.cost === 3 ? 1 : 0), size, copies), ['arch:swarm']);
|
|
const cats = [...new Set(pool.map(c => c.faction))].sort();
|
|
for (const cat of cats) if (pool.filter(c => c.faction === cat).length >= 6)
|
|
add(`mono-${cat}`, curveDeck(pool, size, copies, c => c.faction === cat), ['arch:mono-faction']);
|
|
const kws = [...new Set(pool.map(c => c.keyword).filter((k): k is string => !!k))].sort();
|
|
for (const kw of kws) if (pool.filter(c => c.keyword === kw).length >= 3)
|
|
add(`kw-${kw}`, curveDeck(pool, size, copies, c => c.keyword === kw), ['arch:keyword']);
|
|
for (const d of extra) add(d.id, d.payload as GameCard[], d.tags);
|
|
return decks;
|
|
}
|
|
|
|
// ---------- adapter ----------
|
|
|
|
export interface GameEngineOptions {
|
|
rulesets?: Record<string, Ruleset>;
|
|
extraDecks?: DeckSpec[];
|
|
/** Card pool for archetype decks (one copy per page). Default: the engine's starter pool. */
|
|
pool?: GameCard[];
|
|
/** Also include the engine's seeded placeholder decks `starterDeck(seed)` (default false). */
|
|
seededStarters?: boolean;
|
|
}
|
|
|
|
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>();
|
|
// Filler for hidden cards: the sim's card pool, powered by the view's ruleset.
|
|
const fillerCache = new Map<Ruleset, GameCard[]>();
|
|
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}`);
|
|
return r;
|
|
};
|
|
return {
|
|
name: 'shared/game',
|
|
rulesets: () => Object.keys(rulesets),
|
|
decks(id) {
|
|
if (!deckCache.has(id)) {
|
|
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);
|
|
}
|
|
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 queues first, then seat 1. Bots never read the other side's queued plays
|
|
// (evaluateFor hides them; lookahead determinizes), so the order leaks nothing.
|
|
toAct: s => (s.players[0].committed ? 1 : 0),
|
|
// Undo/timeout/concede are excluded: they never help a bot and let random bots loop.
|
|
legalActions: (s, seat) => legalActions(s, seat).filter(a => a.type === 'play' || a.type === 'commit'),
|
|
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' ? [baseId(a.cardId)] : []),
|
|
actionKind: a => a.type,
|
|
cardMeta(id) {
|
|
const c = meta.get(id);
|
|
if (!c) return undefined;
|
|
return { label: c.title, cost: c.cost, power: c.power, powerPerCost: c.power / Math.max(1, c.cost), keyword: c.keyword ?? 'vanilla', faction: c.faction, home: c.home };
|
|
},
|
|
firstSeat: s => 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;
|
|
if (!r0) return out;
|
|
const payload = [decks[0].payload as GameCard[], decks[1].payload as GameCard[]] as const;
|
|
const score = (w: PlayerId | null, seat: Seat) => (w === null ? 0 : w === seat ? 1 : -1);
|
|
for (const seat of [0, 1] as Seat[]) {
|
|
const played = new Set(final.actions.filter(a => a.type === 'play' && a.player === seat).map(a => (a as { cardId: string }).cardId));
|
|
const byKw = new Map<string, number>();
|
|
for (const c of payload[seat]) if (c.keyword && played.has(c.cardId)) byKw.set(c.keyword, (byKw.get(c.keyword) ?? 0) + 1);
|
|
for (const [kw, cards] of byKw) {
|
|
const stripped = payload[seat].map(c => (c.keyword === kw ? { ...c, keyword: null } : c));
|
|
const decks2 = (seat === 0 ? [stripped, payload[1]] : [payload[0], stripped]) as [GameCard[], GameCard[]];
|
|
try {
|
|
const r1 = replay(final.ruleset, decks2, final.seed, final.actions).result;
|
|
if (!r1) continue;
|
|
out.push({ seat, keyword: kw, cards, power: r0.totalPower[seat] - r1.totalPower[seat], flip: score(r0.winner, seat) > score(r1.winner, seat) ? 1 : 0 });
|
|
} catch { /* replay diverged (e.g. a keyword changed legality); skip */ }
|
|
}
|
|
}
|
|
return out;
|
|
},
|
|
actionPower: (s, a) => (a.type === 'play' ? s.players[a.player].hand.find(c => c.cardId === a.cardId)?.power ?? 0 : -1),
|
|
};
|
|
}
|
|
|
|
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<MatchState, Action> = gameEngine): (view: PlayerView, rng: Rng) => Action {
|
|
const bot = makeBot(name, engine);
|
|
return (view, rng) => bot(view, view.you, rng);
|
|
}
|