import { ADVISOR_BY_ID } from "./advisors.ts"; import { attackable, blockedReason, counterable, defOf, playCard } from "./cards.ts"; import { PRESS_BY_ID, STOP_EVENT_BY_ID, type Choice, type Outcome } from "./content.ts"; import { cardDef, findCard, upgradable } from "./data.ts"; import { encounterById } from "./route.ts"; import { choose, createRun, endWeek, ultimate, type CreateOptions } from "./rules.ts"; import { bestArg, choiceBlocked } from "./scenes.ts"; import { nextRandom, type RogueSetup, type RunState, type StopKind } from "./state.ts"; import { ultReady } from "./ultimate.ts"; import { previewsFor } from "./view.ts"; /** * 模擬玩家(平衡報告用,apps/sim rogue-balance): * - idle:什麼都不做;random:亂出牌、亂選;naive:牌都打在人最多的區、不理對手; * - casual:照手牌順序出,每張打在畫面推薦的第一名(隨手玩、但會看星號的玩家); * - greedy:每次挑「每點體力換最多票」的牌和區(看得懂預估數字的玩家),劇情和下一站也挑划算的; * - ground/air/attack:greedy 出牌,但獎勵只拿某一派的牌,檢查有沒有一招通吃。 */ export type BotName = "idle" | "random" | "naive" | "casual" | "greedy" | "ground" | "air" | "attack"; interface Dice { next: () => number; } function dice(seed: number): Dice { let state = (seed ^ 0x5bd1e995) >>> 0 || 1; return { next: () => { const [x, n] = nextRandom(state); state = n; return x; }, }; } function targetsOf(s: RunState, uid: string): (string | null)[] { const card = defOf(s.hand.find((c) => c.uid === uid)!); if (card.target === "town") return s.towns.map((t) => t.code); if (card.target === "intent") return counterable(s).map((i) => i.id); if (card.target === "attack") return attackable(s).map((i) => i.id); return [null]; } const playable = (s: RunState) => s.hand.filter((c) => !blockedReason(s, defOf(c))); function playRandom(s: RunState, d: Dice): RunState { for (let k = 0; k < 14; k++) { const cards = playable(s); if (cards.length === 0 || d.next() < 0.1) break; const card = cards[Math.floor(d.next() * cards.length)]!; const targets = targetsOf(s, card.uid); const r = playCard(s, card.uid, targets[Math.floor(d.next() * targets.length)] ?? null); if ("error" in r) break; s = r.state; } return s; } function playNaive(s: RunState): RunState { const biggest = [...s.towns].sort((a, b) => b.voters - a.voters)[0]!.code; for (let k = 0; k < 14; k++) { const card = playable(s).find((c) => { const t = defOf(c).target; return t !== "intent" && t !== "attack"; }); if (!card) break; const r = playCard(s, card.uid, defOf(card).target === "town" ? biggest : null); if ("error" in r) break; s = r.state; } return s; } const SPECIAL = new Set(["money", "probe", "draw", "rush", "power", "answer"]); /** 照手牌順序,每張打在預估最高的目標;預估是負的就跳過(募款、抽牌照打) */ function playCasual(s: RunState): RunState { for (let k = 0; k < 14; k++) { const previews = previewsFor(s); const next = s.hand .map((c) => ({ c, best: [...(previews[c.uid] ?? [])].sort((a, b) => b.votes - a.votes)[0] })) .find(({ c, best }) => best && (best.votes > 0 || SPECIAL.has(defOf(c).effect.kind))); if (!next?.best) break; const r = playCard(s, next.c.uid, next.best.target === "city" ? null : next.best.target); if ("error" in r) break; s = r.state; } return s; } /** 每點體力換多少票;錢不夠時募款牌加分,沒有把柄時打探加分 */ function playGreedy(s: RunState): RunState { for (let k = 0; k < 14; k++) { const previews = previewsFor(s); let best: { uid: string; target: string | null; value: number } | null = null; for (const c of s.hand) { const card = defOf(c); for (const p of previews[c.uid] ?? []) { let value = p.votes; const kind = card.effect.kind; if (kind === "money") value = s.money < 500 ? 4000 * s.scale : 300 * s.scale; if (kind === "probe") value = s.leverage === 0 ? 2500 * s.scale : 0; if (kind === "draw") value = 2600 * s.scale; if (kind === "rush") value = s.hand.length > 1 ? 3000 * s.scale : 0; if (kind === "power") value = (s.totalWeeks - s.week + 1) * 900 * s.scale; if (kind === "answer") value = 3000 * s.scale; const per = value / Math.max(0.5, card.cost); if (per > 0 && (!best || per > best.value)) best = { uid: c.uid, target: p.target === "city" ? null : p.target, value: per }; } } if (!best) break; const r = playCard(s, best.uid, best.target); if ("error" in r) break; s = r.state; } return s; } /** 拿牌的偏好:數字越大越想要 */ const CARD_TASTE: Record = { rally: 5, pilgrimage: 5, celebrity: 4.5, door: 4, tv: 4, counter: 4, office: 4, online: 3.5, oath: 3.5, kneel: 4, night: 3, calls: 3, clarify: 3, expose: 2.5, probe: 2.5, live: 3, talk: 2.5, walk: 2.5, small: 2, breakfast: 3.5, park: 3, campus: 3, hakka: 2.5, weddings: 3, truck: 4, banquet: 3.5, endorse: 3.5, billboard: 3, volunteers: 3.5, phonebank: 3.5, mobilize: 3, allnighter: 3, shorts: 3, line: 3.5, radio: 3, flyers: 3, policy: 3.5, whitepaper: 3, mediatraining: 3.5, fieldwork: 3.5, factcheck: 3, contrast: 3, selffund: 2.5, tycoon: 2, elder: 4, }; const ADVISOR_TASTE: Record = { chief: 5, youth_corps: 4.5, scheduler: 4, combo_coach: 4, rally_king: 3.5, temple_master: 3, market_auntie: 3.5, ad_planner: 3, tycoon: 3, old_stake: 2.5, spin_doctor: 3, social_editor: 2.5, muckraker: 2.5, opener: 4, night_owl: 3.5, truck_captain: 3.5, councilors: 3, iron_base: 3, party_org: 3.5, volunteer_lead: 3.5, mascot: 3, pollster: 3, fundraiser: 2.5, cfo: 2.5, lawyer: 2.5, crisis_team: 2.5, debate_coach: 3, influencer: 2.5, speechwriter: 3, hakka_director: 2, farm_ally: 2, student_leader: 2.5, }; const ARCHETYPE_TAGS: Partial> = { ground: ["ground", "rally", "org"], air: ["media", "online", "tv", "press"], attack: ["attack", "intel", "press", "defend"] }; const ARCHETYPE_SCHOOL: Partial> = { ground: ["ground", "org", "any"], air: ["air", "any", "money"], attack: ["defend", "any", "air"] }; const cardScore = (bot: BotName, id: string): number => { const card = findCard(id)!; const tags = ARCHETYPE_TAGS[bot]; if (tags && !card.tags.some((t) => tags.includes(t))) return 0; return CARD_TASTE[id] ?? 1; }; const advisorScore = (bot: BotName, id: string): number => { const schools = ARCHETYPE_SCHOOL[bot]; if (schools && !schools.includes(ADVISOR_BY_ID.get(id)?.school ?? "any")) return 0.5; return ADVISOR_TASTE[id] ?? 1; }; /** 劇情結果大概值多少票(greedy 挑選項用) */ function outcomeValue(s: RunState, o: Outcome): number { return ( (o.votes ?? 0) + (o.rivalVotes ?? 0) * 0.8 + (o.momentum ?? 0) * 1800 - (o.rivalMomentum ?? 0) * 1500 + (o.money ?? 0) * (s.money < 400 ? 8 : 3) + (o.energy ?? 0) * 1700 + (o.card ? 1800 : 0) + (o.upgrade ? 1500 : 0) + (o.advisor ? 2500 : 0) - (o.status ?? []).reduce((a, x) => a + (x === "favor" ? 2500 : x === "reporter" || x === "storm" ? 1200 : 600), 0) ); } const choiceValue = (s: RunState, c: Choice): number => (c.roll ? c.roll.chance * outcomeValue(s, c.outcome) + (1 - c.roll.chance) * outcomeValue(s, c.roll.fail) : outcomeValue(s, c.outcome)); function bestChoice(s: RunState, choices: readonly Choice[]): number { let best = 0; let value = -Infinity; choices.forEach((c, i) => { if (choiceBlocked(s, c)) return; const v = choiceValue(s, c); if (v > value) { value = v; best = i; } }); return best; } const smart = (bot: BotName) => bot === "greedy" || bot === "ground" || bot === "air" || bot === "attack"; function pickScene(s: RunState, bot: BotName, d: Dice): number { const scene = s.scene!; if (scene.kind === "poll") return 0; if (scene.kind === "debate") { if (scene.round >= scene.topics.length) return 0; if (!smart(bot) && bot !== "casual") return Math.floor(d.next() * scene.hand.length); // 看懂質疑:挑手上最好的論點;隨手玩的三成看錯 if (bot === "casual" && d.next() < 0.3) return Math.floor(d.next() * scene.hand.length); return bestArg(scene.hand, scene.needs[scene.round]!); } if (scene.kind === "crisis") { if (!smart(bot)) return 1; if (s.money >= 450) return 0; return s.hand.length > 0 ? 2 : 3; } const def = PRESS_BY_ID.get(scene.id)!; if (!smart(bot)) { const ok = def.choices.map((c, i) => (choiceBlocked(s, c) ? -1 : i)).filter((i) => i >= 0); return ok[Math.floor(d.next() * ok.length)] ?? 0; } return bestChoice(s, def.choices); } const deck = (s: RunState) => [...s.draw, ...s.discard, ...s.hand]; /** 下一站的偏好 */ function routeScore(s: RunState, bot: BotName, kind: StopKind): number { const basics = deck(s).filter((c) => ["canvass", "market", "temple", "dinner", "favor", "tired", "reporter", "storm"].includes(c.id)).length; const scores: Record = { card: 3, advisor: 4, upgrade: 2.6, remove: basics >= 4 ? 2.5 : 1, shop: s.money >= 500 ? 3.2 : 0.5, encounter: 2.4, event: 2.2, minigame: 2.3, }; if (bot === "attack" && kind === "encounter") return 1; return scores[kind]; } /** 要拿掉的牌:先人情包袱,再來是開局的弱牌 */ function removeTarget(s: RunState): string | null { const order = ["favor", "tired", "reporter", "storm", "temple", "dinner", "market", "canvass"]; for (const id of order) { const c = deck(s).find((x) => x.id === id && !x.up); if (c) return c.uid; } return null; } /** 要升級的牌:效果大、常打的 */ function upgradeTarget(s: RunState): string | null { const order = ["rally", "office", "counter", "pilgrimage", "celebrity", "volunteers", "door", "truck", "tv", "canvass", "market", "stake", "temple"]; for (const id of order) { const c = deck(s).find((x) => x.id === id && upgradable(x.id, x.up)); if (c) return c.uid; } const any = deck(s).find((x) => upgradable(x.id, x.up)); return any?.uid ?? null; } function pickRouteFor(s: RunState, bot: BotName, d: Dice): number | "skip" { const route = s.route!; if (bot === "idle") return "skip"; if (bot === "random" || bot === "naive") return Math.floor(d.next() * route.length); if (bot === "casual") return route.indexOf("card") >= 0 ? route.indexOf("card") : 0; const ranked = route.map((k, i) => ({ i, v: routeScore(s, bot, k) })).sort((a, b) => b.v - a.v); return ranked[0]!.i; } function pickStopFor(s: RunState, bot: BotName, d: Dice): { pick: number | "skip"; target: string | null } { const stop = s.stop!; const randomish = !smart(bot); switch (stop.kind) { case "card": { if (randomish) return { pick: Math.floor(d.next() * stop.options.length), target: null }; const ranked = stop.options.map((id, i) => ({ i, v: cardScore(bot, id) })).sort((a, b) => b.v - a.v); return ranked[0] && ranked[0].v > 0 ? { pick: ranked[0].i, target: null } : { pick: "skip", target: null }; } case "advisor": { if (randomish) return { pick: Math.floor(d.next() * stop.options.length), target: null }; const ranked = stop.options.map((id, i) => ({ i, v: advisorScore(bot, id) })).sort((a, b) => b.v - a.v); return { pick: ranked[0]!.i, target: null }; } case "upgrade": { const target = randomish ? (deck(s).find((c) => upgradable(c.id, c.up))?.uid ?? null) : upgradeTarget(s); return target ? { pick: 0, target } : { pick: "skip", target: null }; } case "remove": { const target = removeTarget(s); return target ? { pick: 0, target } : { pick: "skip", target: null }; } case "shop": { if (randomish) return { pick: "skip", target: null }; const reserve = 250; const favor = deck(s).some((c) => c.id === "favor"); const options = stop.items .map((item, i) => ({ item, i })) .filter(({ item }) => !item.sold && s.money - item.price >= reserve) .map(({ item, i }) => ({ i, item, v: item.kind === "card" ? cardScore(bot, item.id) : item.kind === "advisor" ? advisorScore(bot, item.id) + 1 : favor ? 5 : 2 })) .filter((x) => x.v >= 3) .sort((a, b) => b.v - a.v); const top = options[0]; if (!top) return { pick: "skip", target: null }; return { pick: top.i, target: top.item.kind === "remove" ? removeTarget(s) : null }; } case "encounter": { if (stop.step >= stop.encounters.length) return { pick: "skip", target: null }; const e = encounterById(stop.encounters[stop.step]!)!; if (randomish) return { pick: Math.floor(d.next() * e.options.length), target: null }; const value = (o: (typeof e.options)[number]) => (o.roll ? o.roll.chance * o.roll.success.score + (1 - o.roll.chance) * o.roll.failure.score : o.score); const ranked = e.options.map((o, i) => ({ i, v: value(o) })).sort((a, b) => b.v - a.v); return { pick: ranked[0]!.i, target: null }; } case "minigame": // 打得好的玩家大約 75 分、隨手玩 40–70 分 return { pick: Math.round(randomish ? 40 + d.next() * 30 : 65 + d.next() * 20), target: null }; case "event": { const def = STOP_EVENT_BY_ID.get(stop.id)!; if (randomish) { const ok = def.choices.map((c, i) => (choiceBlocked(s, c) ? -1 : i)).filter((i) => i >= 0); return { pick: ok[Math.floor(d.next() * ok.length)] ?? 0, target: null }; } return { pick: bestChoice(s, def.choices), target: null }; } } } /** 讓模擬玩家打完整場;watch 每做完一步呼叫一次(平衡分析用:看這一步的 log) */ export function runBot(setup: RogueSetup, seed: number, bot: BotName, opts: CreateOptions = {}, watch?: (s: RunState, step: "week" | "scene" | "stop") => void): RunState { let s = createRun(setup, `bot-${seed}`, seed, opts); const d = dice(seed); for (let guard = 0; s.phase !== "finished" && guard < 200; guard++) { let next: RunState | { error: string }; if (s.phase === "plan" && s.scene?.kind === "press") { // 記者堵麥:這週內要回答(先回答再出牌) next = choose(s, bot === "idle" ? 0 : pickScene(s, bot, d)); for (let k = 0; "error" in next && k < 4; k++) next = choose(s, k); } else if (s.phase === "plan") { // 大絕招集滿就放(小遊戲分數模擬:打得好 75–95、其他 40–70) if (bot !== "idle" && ultReady(s)) { const score = bot === "greedy" ? 75 + d.next() * 20 : 40 + d.next() * 30; const r = ultimate(s, "rally", score); if (!("error" in r)) s = r; } if (bot === "random") s = playRandom(s, d); else if (bot === "naive") s = playNaive(s); else if (bot === "casual") s = playCasual(s); else if (bot !== "idle") s = playGreedy(s); next = endWeek(s); } else if (s.phase === "scene") { next = choose(s, bot === "idle" ? 0 : pickScene(s, bot, d)); // 選不了(例如錢不夠提告)就照順序換一個 for (let k = 0; "error" in next && k < 4; k++) next = choose(s, k); } else if (s.phase === "route") next = choose(s, pickRouteFor(s, bot, d)); else { const p = bot === "idle" ? { pick: "skip" as const, target: null } : pickStopFor(s, bot, d); next = choose(s, p.pick, p.target); // 選不了(例如錢不夠)就離開這一站 if ("error" in next) next = choose(s, "skip"); } if ("error" in next) throw new Error(`${bot} 第 ${s.week} 週 ${s.phase}:${next.error}`); watch?.(next, s.phase === "plan" && !s.scene ? "week" : s.phase === "scene" || s.scene ? "scene" : "stop"); s = next; } return s; } export const cardName = (id: string, up = false) => cardDef(id, up)?.name ?? id;