/** * 平衡報告(docs/13 M1):node src/balance.ts [--scenario taoyuan-2022-mayor] [--seeds 30] * * 每位候選人輪流當「玩家」,分別用不同打法打完整場,其他陣營都是一般 AI。 * 看策略能移動多少得票率、勝率多少,用來決定劇本難度與行動效果是否夠有感。 */ import { mkdir, writeFile } from "node:fs/promises"; import { parseArgs } from "node:util"; import { aiOrders, createMatch, makeRng, planOrders, playWeek, viewFor, type ScenarioCandidate, type World } from "@election2026/engine"; import type { Order } from "@election2026/protocol"; import { loadWorld } from "./world.ts"; type Strategy = "idle" | "smart" | ScenarioCandidate["aiStyle"]; const STRATEGIES: { id: Strategy; label: string }[] = [ { id: "idle", label: "什麼都不做" }, { id: "balanced", label: "均衡" }, { id: "ground", label: "地面戰" }, { id: "air", label: "空戰" }, { id: "dirty", label: "奧步(買票、網軍)" }, { id: "smart", label: "懂戰術(組合拳+打對台)" }, ]; interface Outcome { share: number; won: boolean; scandal: boolean; } function play(world: World, playerId: string, strategy: Strategy, seed: number): Outcome { let state = createMatch(world, `balance-${seed}`, seed, playerId); while (state.phase !== "finished") { let orders: Order[]; if (strategy === "idle") orders = []; else if (strategy === "smart") orders = planOrders(viewFor(state, world, playerId), "balanced", makeRng(seed, "player", state.week), { tactics: true }); else orders = planOrders(viewFor(state, world, playerId), strategy, makeRng(seed, "player", state.week)); state = playWeek(state, world, { [playerId]: orders }).state; } const r = state.result!; const total = Object.values(r.votes).reduce((a, b) => a + b, 0) || 1; const ci = world.scenario.candidates.findIndex((c) => c.id === playerId); return { share: r.votes[playerId] / total, won: r.winnerId === playerId && !r.voided, scandal: state.candidates[ci].tags.includes("檢調約談") || state.candidates[ci].tags.includes("奧步"), }; } const pct = (x: number, d = 1) => `${(x * 100).toFixed(d)}%`; const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / (xs.length || 1); async function main(): Promise { const { values } = parseArgs({ options: { scenario: { type: "string", default: "taoyuan-2022-mayor" }, seeds: { type: "string", default: "30" } }, }); const started = Date.now(); const world = await loadWorld(values.scenario); const seeds = Array.from({ length: Number(values.seeds) }, (_, i) => 5_000 + i); const rows: { candidate: string; strategy: string; share: number; delta: number; winRate: number; scandalRate: number }[] = []; for (const cand of world.scenario.candidates) { // 對照組:玩家也交給劇本設定的 AI 性格 const baseline = mean( seeds.map((seed) => { let state = createMatch(world, `balance-${seed}`, seed, cand.id); while (state.phase !== "finished") state = playWeek(state, world, { [cand.id]: aiOrders(state, world, cand.id) }).state; const r = state.result!; return r.votes[cand.id] / (Object.values(r.votes).reduce((a, b) => a + b, 0) || 1); }), ); for (const s of STRATEGIES) { const outcomes = seeds.map((seed) => play(world, cand.id, s.id, seed)); const share = mean(outcomes.map((o) => o.share)); rows.push({ candidate: cand.name, strategy: s.label, share, delta: share - baseline, winRate: mean(outcomes.map((o) => (o.won ? 1 : 0))), scandalRate: mean(outcomes.map((o) => (o.scandal ? 1 : 0))), }); } console.log(`${cand.name} 完成`); } const lines = [ `# 平衡報告:${world.scenario.name}`, "", `每種打法 ${seeds.length} 場,共 ${seeds.length * STRATEGIES.length * world.scenario.candidates.length} 場;其他陣營都是一般 AI。「比照 AI」是和玩家交給劇本預設 AI 時相比。`, "", "| 候選人 | 打法 | 平均得票率 | 比照 AI | 勝率 | 出包率 |", "|---|---|---:|---:|---:|---:|", ...rows.map( (r) => `| ${r.candidate} | ${r.strategy} | ${pct(r.share, 2)} | ${r.delta >= 0 ? "+" : ""}${(r.delta * 100).toFixed(2)} | ${pct(r.winRate, 0)} | ${pct(r.scandalRate, 0)} |`, ), "", `耗時 ${((Date.now() - started) / 1000).toFixed(1)} 秒。`, ]; const outDir = new URL("../out/", import.meta.url); await mkdir(outDir, { recursive: true }); await writeFile(new URL(`balance-${world.scenario.id}.md`, outDir), lines.join("\n") + "\n"); await writeFile(new URL(`balance-${world.scenario.id}.json`, outDir), JSON.stringify(rows, null, 2)); console.log(lines.join("\n")); } await main();