sim-balance: DESIGN 2.1 starter decks, owned-random decks, turn-resolving evaluator, powerDelta, v1.1 variants

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 23:51:32 -05:00
co-authored by Claude Opus 5.5
parent b4f06001cd
commit 4d0ffd8d73
5 changed files with 103 additions and 12 deletions
+38 -2
View File
@@ -2,7 +2,9 @@
// derived per DESIGN §1 (percentile -> fame -> cost, home stat) and §10.1 (faction keyword).
// Percentile cut points come from the file itself. Power is (re)set from the ruleset by the adapter.
import { readFileSync } from 'node:fs';
import { KEYWORDS, type GameCard, type Stat } from '../../shared/game/index.ts';
import { KEYWORD_IDS, type GameCard, type Stat } from '../../shared/game/index.ts';
import { mulberry32 } from '../../shared/bots/index.ts';
import type { DeckSpec } from '../../shared/bots/types.ts';
const STATS: Stat[] = ['attention', 'depth', 'reach'];
const HOME_TIE: Stat[] = ['depth', 'reach', 'attention'];
@@ -39,10 +41,44 @@ export function loadPool(file: string, opts: PoolOptions = {}): GameCard[] {
for (const s of HOME_TIE) { const v = pct[s], cur = pct[home]; if (v !== null && (cur === null || v > cur)) home = s; }
const faction = (c.category ?? c.legacyCategory ?? 'Culture') as GameCard['faction'];
const kw = FACTION_KEYWORD[faction];
const keyword = cost === 1 || opts.keywords === 'none' || !kw || !Object.hasOwn(KEYWORDS, kw) ? null : kw;
const keyword = cost === 1 || opts.keywords === 'none' || !kw || !(KEYWORD_IDS as readonly string[]).includes(kw) ? null : kw;
return {
cardId: `loaner:${c.pageId}`, pageId: c.pageId, title: c.title, faction, rarity: 'Common', cost, power: 0,
home, trend: 0, keyword, source: 'loaner',
} satisfies GameCard;
});
}
const kebab = (t: string) => t.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
/** The DESIGN §2.1 starter decks: "**A. Name: ...**" headings followed by | Cost | Card | Faction | Home | tables. */
export function loadStarterDecks(designMd: string): DeckSpec[] {
const text = readFileSync(designMd, 'utf8');
const sec = text.slice(text.indexOf('### 2.1'), text.indexOf('## 3.'));
const decks: DeckSpec[] = [];
let cur: { id: string; cards: GameCard[] } | null = null;
for (const line of sec.split('\n')) {
const h = line.match(/^\*\*([A-Z])\. ([^:*]+)/);
if (h) { cur = { id: `starter-${h[1]}-${kebab(h[2])}`, cards: [] }; decks.push({ id: cur.id, tags: ['arch:starter-v1'], payload: cur.cards }); continue; }
const r = line.match(/^\| (\d) \| ([^|]+) \| (\w+) \| (\w+) \|$/);
if (r && cur) {
const [, cost, title, faction, home] = r;
const c = Number(cost), kw = FACTION_KEYWORD[faction];
cur.cards.push({
cardId: `loaner:${kebab(title.trim())}`, pageId: null, title: title.trim(), faction: faction as GameCard['faction'], rarity: 'Common',
cost: c, power: 0, home: home as Stat, trend: 0, keyword: c === 1 || !(KEYWORD_IDS as readonly string[]).includes(kw) ? null : kw, source: 'loaner',
});
}
}
return decks.filter(d => (d.payload as GameCard[]).length === 12);
}
/** "Realistic owned" decks (DESIGN §2.1 v1.1 note): `n` seeded draws of 12 distinct cards from the pool, real category mix. */
export function ownedDecks(pool: GameCard[], n: number, size = 12, seed = 7): DeckSpec[] {
const rng = mulberry32(seed);
return Array.from({ length: n }, (_, i) => {
const p = [...pool];
for (let k = p.length - 1; k > 0; k--) { const j = Math.floor(rng() * (k + 1)); [p[k], p[j]] = [p[j], p[k]]; }
return { id: `owned-${i}`, tags: ['arch:owned-random'], payload: p.slice(0, size).map(c => ({ ...c, cardId: `${c.cardId}:0` })) };
});
}
+14 -4
View File
@@ -29,11 +29,15 @@ export async function loadEngine(name: string): Promise<EngineAdapter<any, any>>
}
}
let pool;
const extraDecks = [];
const cp = await import('./card-pool.ts');
if (process.env.SIM_STARTERS) extraDecks.push(...cp.loadStarterDecks(process.env.SIM_STARTERS));
if (process.env.SIM_POOL) {
const { loadPool } = await import('./card-pool.ts');
const { loadPool } = cp;
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 });
}
return makeGameEngine({ rulesets, pool });
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 });
}
throw new Error(`unknown engine ${name}`);
}
@@ -71,6 +75,12 @@ export function schedule(n: number, nDecks: number, baseSeed: number, mix = DEFA
return jobs;
}
/** Decks for a ruleset, filtered by the SIM_DECKS regex (inherited by child processes). */
export function decksFor(engine: EngineAdapter<any, any>, ruleset: string): DeckSpec[] {
const re = process.env.SIM_DECKS ? new RegExp(process.env.SIM_DECKS) : null;
return engine.decks(ruleset).filter(d => !re || re.test(d.id));
}
function runJobs(engine: EngineAdapter<any, any>, ruleset: string, decks: DeckSpec[], jobs: Job[], onRecord: (r: MatchRecord | { error: string; job: Job }) => void) {
for (const j of jobs) {
try { onRecord(playMatch(engine, ruleset, [decks[j.decks[0]], decks[j.decks[1]]], j.bots, j.seed)); }
@@ -94,7 +104,7 @@ async function main() {
mkdirSync(out, { recursive: true });
const sections: string[] = [];
for (const ruleset of rulesets) {
const decks = engine.decks(ruleset);
const decks = decksFor(engine, ruleset);
const jobs = schedule(n, decks.length, seed, MIXES[arg('mix', 'default')!]);
const records: MatchRecord[] = [];
const errors: string[] = [];
@@ -135,7 +145,7 @@ if (isEntry && process.argv.includes('--child')) {
process.once('message', async (msg: any) => {
const { engineName, ruleset, jobs } = msg as { engineName: string; ruleset: string; jobs: Job[] };
const engine = await loadEngine(engineName);
runJobs(engine, ruleset, engine.decks(ruleset), jobs, r => process.send!(r));
runJobs(engine, ruleset, decksFor(engine, ruleset), jobs, r => process.send!(r));
process.send!('done');
});
} else if (isEntry) main().catch(e => { console.error(e); process.exit(1); });
+13
View File
@@ -0,0 +1,13 @@
{
"k1-nerf3": { "keywordParams": {
"rising": { "amount": 1, "cap": 2, "powerDelta": -1 }, "nostalgic": { "amount": 2, "powerDelta": -1 }, "translated": { "amount": 1, "powerDelta": -1 } } },
"k2-nerf3-viral": { "keywordParams": {
"rising": { "amount": 1, "cap": 2, "powerDelta": -1 }, "nostalgic": { "amount": 2, "powerDelta": -1 }, "translated": { "amount": 1, "powerDelta": -1 },
"viral": { "amount": 2, "cap": 3, "powerDelta": 0 } } },
"k3-plus-ency": { "keywordParams": {
"rising": { "amount": 1, "cap": 2, "powerDelta": -1 }, "nostalgic": { "amount": 2, "powerDelta": -1 }, "translated": { "amount": 1, "powerDelta": -1 },
"viral": { "amount": 2, "cap": 3, "powerDelta": 0 }, "encyclopedic": { "amount": 3, "powerDelta": 0 } } },
"k4-soft": { "keywordParams": {
"rising": { "amount": 1, "cap": 1, "powerDelta": 0 }, "nostalgic": { "amount": 1, "powerDelta": 0 }, "translated": { "amount": 1, "powerDelta": -1 },
"viral": { "amount": 2, "cap": 3, "powerDelta": 0 }, "encyclopedic": { "amount": 3, "powerDelta": 0 } } }
}
+6
View File
@@ -0,0 +1,6 @@
{
"v1.1-candidate": { "keywordParams": {
"rising": { "amount": 1, "cap": 2, "powerDelta": -1 }, "nostalgic": { "amount": 2, "powerDelta": -1 }, "translated": { "amount": 1, "powerDelta": -1 },
"viral": { "amount": 2, "cap": 3, "powerDelta": 0 }, "encyclopedic": { "amount": 3, "powerDelta": 0 },
"local": { "amount": 1, "powerDelta": 0 } } }
}
+32 -6
View File
@@ -25,10 +25,32 @@ export function projectedLanes(state: MatchState, seat: Seat): [number, number][
}
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. */
/**
* 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 lanes = projectedLanes(state, seat);
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; }
@@ -135,17 +157,19 @@ function curveDeck(pool: GameCard[], size: number, copies: number, filter: (c: G
* 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()): DeckSpec[] {
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.
const repower = (c: GameCard): GameCard => (c.source === 'loaner' && rules.powerByCost[c.cost] !== undefined ? { ...c, power: rules.powerByCost[c.cost] + (c.keyword ? 0 : vanillaBonus(rules, c)) } : c);
// §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 });
};
for (let i = 0; i < 6; i++) add(`starter-${i}`, starterDeck(`sim-${i}`), ['arch:starter']);
if (seededStarters) for (let i = 0; i < 6; i++) add(`starter-${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']);
@@ -167,6 +191,8 @@ 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). */
seededStarters?: boolean;
}
export function makeGameEngine(opts: GameEngineOptions = {}): EngineAdapter<MatchState, Action> {
@@ -183,7 +209,7 @@ export function makeGameEngine(opts: GameEngineOptions = {}): EngineAdapter<Matc
rulesets: () => Object.keys(rulesets),
decks(id) {
if (!deckCache.has(id)) {
const d = defaultDecks(rules(id), opts.extraDecks, opts.pool);
const d = defaultDecks(rules(id), opts.extraDecks, opts.pool, opts.seededStarters ?? true);
for (const deck of d) for (const c of deck.payload as GameCard[]) meta.set(baseId(c.cardId), c);
deckCache.set(id, d);
}