[sim-balance] Duel bots choose from the observation's legal list; stand-in can use duel-cards' fixture
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -18,7 +18,7 @@ const SAMPLE = fileURLToPath(new URL('../../docs/game/card-sample.json', import.
|
||||
|
||||
export async function loadDuelSim(name: string, rules: Record<string, unknown> = {}): Promise<DuelSim<any, any>> {
|
||||
if (name === 'standin') return (await import('./duel-standin-adapter.ts')).makeStandinSim(SAMPLE, rules as any);
|
||||
if (name === 'duel') { const mod = '../../shared/bots/duel-adapter.ts'; return (await import(mod)).makeDuelSim(SAMPLE, rules); }
|
||||
if (name === 'duel') { const mod = './duel-core-sim.ts'; return (await import(mod)).makeDuelSim(SAMPLE, rules); }
|
||||
throw new Error(`unknown duel engine ${name}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// EngineAdapter + DuelLens over the sim stand-in duel engine (scripts/sim/duel-standin.ts).
|
||||
import type { DeckSpec, EngineAdapter, Seat } from '../../shared/bots/types.ts';
|
||||
import { duelEvaluate, type DuelLens, type LensAction } from '../../shared/bots/duel-bots.ts';
|
||||
import { applyAction, createDuel, isCreature, legalActions, pow, tough, viewFor, deriveSample, STANDIN_RULES, type SAction, type SCard, type SRules, type SState } from './duel-standin.ts';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { applyAction, createDuel, fromDuelCards, isCreature, legalActions, pow, tough, viewFor, deriveSample, STANDIN_RULES, type SAction, type SCard, type SRules, type SState } from './duel-standin.ts';
|
||||
import { mulberry32 } from '../../shared/bots/index.ts';
|
||||
import type { DuelSim } from './duel-sim-types.ts';
|
||||
|
||||
@@ -29,7 +30,8 @@ export const standinLens: DuelLens<SState, SAction> = {
|
||||
};
|
||||
|
||||
export function makeStandinSim(poolFile: string, rules: Partial<SRules> = {}): DuelSim<SState, SAction, SCard> {
|
||||
const pool = deriveSample(poolFile);
|
||||
const fixture = poolFile.replace(/card-sample\.json$/, 'duel-card-sample.json');
|
||||
const pool = process.env.SIM_STANDIN_POOL !== 'own' && existsSync(fixture) ? fromDuelCards(fixture) : deriveSample(poolFile);
|
||||
const R = { ...STANDIN_RULES, ...rules };
|
||||
const engine: EngineAdapter<SState, SAction> = {
|
||||
name: 'duel-standin',
|
||||
|
||||
@@ -64,10 +64,12 @@ export function deriveSample(file: string): SCard[] {
|
||||
const txt = `${c.description ?? ''} ${(c.categories ?? []).join(' ')}`;
|
||||
const countries = [...new Set([...txt.matchAll(COUNTRY)].map(m => m[1].slice(0, 5)))].map(x => `c:${x}`);
|
||||
const cents = [...new Set([...`${c.title} ${txt}`.matchAll(/\b(1[0-9]{3}|20[0-2][0-9])\b/g)].map(m => `t:${Math.floor(Number(m[1]) / 100)}`))];
|
||||
const type = classify(c);
|
||||
if (type === 'Location') return { id: `p${c.pageId}`, pageId: c.pageId, title: c.title, type, portal: c.faction ?? 'Other', cost: Math.ceil(cost / 2), power: 0, toughness: Math.max(1, Math.ceil(toughness / 2)), keywords: [], fame, connect: [...countries, ...cents] };
|
||||
const kw: string[] = [];
|
||||
if (c.languageCount >= 20) kw.push('Multilingual');
|
||||
if (c.pageBytes < 3000) kw.push('Stub');
|
||||
return { id: `p${c.pageId}`, pageId: c.pageId, title: c.title, type: classify(c), portal: c.faction ?? 'Other', cost, power, toughness, keywords: kw.slice(0, 2), fame, connect: [...countries, ...cents] };
|
||||
return { id: `p${c.pageId}`, pageId: c.pageId, title: c.title, type, portal: c.faction ?? 'Other', cost, power, toughness, keywords: kw.slice(0, 2), fame, connect: [...countries, ...cents] };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -179,7 +181,7 @@ export function applyAction(s0: SState, a: SAction): SState {
|
||||
draw(s, a.seat); if (c.cost >= 4) draw(s, a.seat);
|
||||
} else if (c.type === 'Location') {
|
||||
if (pl.ramp < 2) pl.ramp++;
|
||||
pl.board.push({ card: { ...c, power: 0, toughness: Math.max(1, Math.ceil(c.toughness / 2)) }, uid: s.uid++, damage: 0, tapped: false, sick: false, buff: [0, bonus] });
|
||||
pl.board.push({ card: { ...c, power: 0 }, uid: s.uid++, damage: 0, tapped: false, sick: false, buff: [0, bonus] });
|
||||
} else pl.board.push({ card: c, uid: s.uid++, damage: 0, tapped: false, sick: true, buff: [bonus, bonus] });
|
||||
if (foe.life <= 0) lose(s, opp(a.seat), 'notability');
|
||||
return s;
|
||||
@@ -214,3 +216,14 @@ export function viewFor(s: SState, seat: 0 | 1) {
|
||||
o.hand = []; o.library = []; v.players[seat].library = [];
|
||||
return v as SState & { view: { seat: 0 | 1; oppHand: number; oppLib: number; myLib: number } };
|
||||
}
|
||||
|
||||
/** duel-cards' derived DuelCards (docs/game/duel-card-sample.json) mapped onto the stand-in's card shape. */
|
||||
export function fromDuelCards(file: string): SCard[] {
|
||||
const cards = JSON.parse(readFileSync(file, 'utf8')).cards as any[];
|
||||
return cards.map(c => ({
|
||||
id: c.cardId, pageId: c.pageId, title: c.title, type: c.type, portal: c.portal, cost: c.cost,
|
||||
power: c.type === 'Location' ? 0 : (c.power ?? c.basis?.magnitude ?? 1), toughness: c.type === 'Location' ? Math.max(1, c.toughness ?? 1) : (c.toughness ?? c.basis?.magnitude ?? 1),
|
||||
keywords: c.keywords ?? [], fame: c.basis?.fame ?? 0,
|
||||
connect: [...(c.connect?.countries ?? []).map((x: string) => `c:${x}`), ...(c.connect?.centuries ?? []).map((x: number) => `t:${x}`)],
|
||||
}));
|
||||
}
|
||||
|
||||
+43
-11
@@ -2,7 +2,39 @@
|
||||
// Bots see the duel through a DuelLens (a few accessors over state and action), so the same bots run
|
||||
// on duel-core's shared/duel engine and on the sim stand-in. Pure: no I/O.
|
||||
import type { EngineAdapter, Rng, Seat, BotFn } from './types.ts';
|
||||
import { greedyBot, lookaheadBot, maxPowerBot, randomBot } from './index.ts';
|
||||
import { lookaheadBot } from './index.ts';
|
||||
|
||||
/**
|
||||
* Observations may carry the acting seat's legal actions (`legal`): the UI shows them anyway, and choosing
|
||||
* from them guarantees a bot never returns an action that is legal only in its determinized guess.
|
||||
*/
|
||||
function legalOf<S, A>(engine: EngineAdapter<S, A>, obs: unknown, s: S, seat: Seat): A[] {
|
||||
const l = (obs as { legal?: A[] } | null)?.legal;
|
||||
return Array.isArray(l) ? l : engine.legalActions(s, seat);
|
||||
}
|
||||
const seeState = <S, A>(engine: EngineAdapter<S, A>, obs: unknown, seat: Seat, rng: Rng): S => (engine.assume ? engine.assume(obs, seat, rng) : (obs as S));
|
||||
|
||||
/** Uniformly random legal action. */
|
||||
export function duelRandomBot<S, A>(engine: EngineAdapter<S, A>): BotFn<unknown, A> {
|
||||
return (obs, seat, rng) => { const l = (obs as { legal?: A[] })?.legal; const legal = Array.isArray(l) ? l : engine.legalActions(seeState(engine, obs, seat, rng), seat); return legal[Math.floor(rng() * legal.length)]; };
|
||||
}
|
||||
|
||||
/** One-ply greedy on the evaluation over every legal action (weak at combat: toggles have no immediate value). */
|
||||
export function duelGreedyBot<S, A>(engine: EngineAdapter<S, A>): BotFn<unknown, A> {
|
||||
return (obs, seat, rng) => {
|
||||
const s = seeState(engine, obs, seat, rng);
|
||||
const legal = legalOf(engine, obs, s, seat);
|
||||
let best = legal[0], bestV = -Infinity;
|
||||
for (const a of legal) { const v = safeEval(engine, s, a, seat) + rng() * 1e-6; if (v > bestV) { bestV = v; best = a; } }
|
||||
return best;
|
||||
};
|
||||
}
|
||||
|
||||
/** Evaluate `a` from `s`; an action the determinized state rejects scores -5 (it stays a candidate). */
|
||||
function safeEval<S, A>(engine: EngineAdapter<S, A>, s: S, a: A, seat: Seat): number {
|
||||
try { const n = engine.applyAction(s, a); return engine.isOver(n) ? (engine.result(n).winner === seat ? 10 : engine.result(n).winner === null ? 0 : -10) : engine.evaluate(n, seat); }
|
||||
catch { return -5; }
|
||||
}
|
||||
|
||||
export interface LensCreature { uid: string; power: number; toughness: number; tapped: boolean; canAttack: boolean; canBlock: boolean; value: number }
|
||||
export type LensAction =
|
||||
@@ -86,8 +118,8 @@ function chooseBlock<S, A>(lens: DuelLens<S, A>, s: S, seat: Seat, legal: { a: A
|
||||
*/
|
||||
export function heuristicBot<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>): BotFn<unknown, A> {
|
||||
return (obs, seat, rng) => {
|
||||
const s = engine.assume ? engine.assume(obs, seat, rng) : (obs as S);
|
||||
const legal = engine.legalActions(s, seat);
|
||||
const s = seeState(engine, obs, seat, rng);
|
||||
const legal = legalOf(engine, obs, s, seat);
|
||||
if (legal.length === 1) return legal[0];
|
||||
return heuristicChoice(engine, lens, s, seat, legal, rng);
|
||||
};
|
||||
@@ -103,7 +135,7 @@ export function heuristicChoice<S, A>(engine: EngineAdapter<S, A>, lens: DuelLen
|
||||
const base = engine.evaluate(s, seat);
|
||||
let best: A | undefined, bestV = -Infinity;
|
||||
for (const { a, d } of plays) {
|
||||
const v = engine.evaluate(engine.applyAction(s, a), seat) + 0.004 * (d as any).cost + rng() * 1e-6;
|
||||
const v = safeEval(engine, s, a, seat) + 0.004 * (d as any).cost + rng() * 1e-6;
|
||||
if (v > bestV) { bestV = v; best = a; }
|
||||
}
|
||||
if (best !== undefined && bestV > base - 0.02) return best;
|
||||
@@ -138,8 +170,8 @@ export interface DuelMCOptions { rollouts?: number; k?: number; horizon?: number
|
||||
export function duelMCBot<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>, opts: DuelMCOptions = {}): BotFn<unknown, A> {
|
||||
const rollouts = opts.rollouts ?? 6, k = opts.k ?? 4, horizon = opts.horizon ?? 120;
|
||||
return (obs, seat, rng) => {
|
||||
const s = engine.assume ? engine.assume(obs, seat, rng) : (obs as S);
|
||||
const legal = engine.legalActions(s, seat);
|
||||
const s = seeState(engine, obs, seat, rng);
|
||||
const legal = legalOf(engine, obs, s, seat);
|
||||
if (legal.length === 1) return legal[0];
|
||||
const ph = lens.phase(s);
|
||||
if (ph !== 'main' && ph !== 'attack') return heuristicChoice(engine, lens, s, seat, legal, rng);
|
||||
@@ -150,7 +182,7 @@ export function duelMCBot<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A
|
||||
const dec = legal.map(a => ({ a, d: lens.decode(s, a) }));
|
||||
cands = [h, ...dec.filter(x => x.d.kind === 'confirmAttack' || (x.d.kind === 'attack' && x.d.on)).map(x => x.a)];
|
||||
} else {
|
||||
cands = [h, ...legal.map(a => ({ a, v: engine.evaluate(engine.applyAction(s, a), seat) })).sort((x, y) => y.v - x.v).map(x => x.a)];
|
||||
cands = [h, ...legal.map(a => ({ a, v: safeEval(engine, s, a, seat) })).sort((x, y) => y.v - x.v).map(x => x.a)];
|
||||
}
|
||||
const uniq: A[] = [];
|
||||
for (const c of cands) if (!uniq.some(u => JSON.stringify(u) === JSON.stringify(c))) uniq.push(c);
|
||||
@@ -160,7 +192,8 @@ export function duelMCBot<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A
|
||||
for (const c of short) {
|
||||
let total = 0;
|
||||
for (let r = 0; r < rollouts; r++) {
|
||||
let st = engine.applyAction(engine.assume ? engine.assume(obs, seat, rng) : s, c), steps = 0;
|
||||
let st: S, steps = 0;
|
||||
try { st = engine.applyAction(seeState(engine, obs, seat, rng), c); } catch { total -= 1; continue; }
|
||||
while (!engine.isOver(st) && steps < horizon) {
|
||||
const who = engine.toAct(st);
|
||||
const lg = engine.legalActions(st, who);
|
||||
@@ -182,9 +215,8 @@ export const DUEL_BOT_NAMES = ['random', 'greedy', 'heuristic', 'mc', 'mc-lite']
|
||||
|
||||
export function makeDuelBot<S, A>(name: string, engine: EngineAdapter<S, A>, lens: DuelLens<S, A>): BotFn<unknown, A> {
|
||||
switch (name) {
|
||||
case 'random': return randomBot(engine);
|
||||
case 'greedy': return greedyBot(engine);
|
||||
case 'maxpower': return maxPowerBot(engine);
|
||||
case 'random': return duelRandomBot(engine);
|
||||
case 'greedy': return duelGreedyBot(engine);
|
||||
case 'heuristic': return heuristicBot(engine, lens);
|
||||
case 'mc': return duelMCBot(engine, lens);
|
||||
case 'mc-lite': return duelMCBot(engine, lens, { rollouts: 3, k: 3, horizon: 60 });
|
||||
|
||||
Reference in New Issue
Block a user