import { AGE_BANDS, type RogueTrait } from "@election2026/protocol"; import { CELLS_PER_VILLAGE, N_LEANS, aggregate, computeVoteModel, createMatch, viewFor, type World } from "@election2026/engine"; import type { RogueSetup, TownSetup } from "./state.ts"; /** 地圖拓撲(topology.json)裡用得到的部分 */ export interface TopologyLike { objects: Record }[] }>; } /** * 從真實資料建開局(docs/21): * - 各區預計投票人數、雙方底盤:用原本的選民模型(人口、年齡、政黨傾向、歷史投票率)算開局的預期得票。 * - 各區特色:年齡結構、每千人宮廟數、人口密度、客家人口比例,和全縣市平均比較。 * 規則本身不碰選民模型;開局之後的變化都是牌面上看得到的數字。 */ const YOUNG = [AGE_BANDS.indexOf("20-29"), AGE_BANDS.indexOf("30-39")]; const OLD = AGE_BANDS.indexOf("65+"); interface TownStats { adults: number; young: number; old: number; temples: number; density: number; } function townStats(world: World): TownStats[] { const { pack } = world; const stats = pack.towns.map(() => ({ adults: 0, young: 0, old: 0, temples: 0, density: 0 })); pack.villages.forEach((v, vi) => { const s = stats[v.townIndex]!; const base = vi * CELLS_PER_VILLAGE; let adults = 0; for (let k = 0; k < CELLS_PER_VILLAGE; k++) { const n = pack.cells[base + k]!; const age = Math.floor(k / N_LEANS); adults += n; if (YOUNG.includes(age)) s.young += n; if (age === OLD) s.old += n; } s.adults += adults; s.temples += v.templesPer1000 * adults; s.density += v.density * adults; }); return stats; } /** 和全縣市平均比,明顯偏高(或偏低)才算這區的特色 */ export function townTraits(world: World): RogueTrait[][] { const stats = townStats(world); const all = stats.reduce((a, s) => ({ adults: a.adults + s.adults, young: a.young + s.young, old: a.old + s.old, temples: a.temples + s.temples, density: a.density + s.density }), { adults: 0, young: 0, old: 0, temples: 0, density: 0, }); const mean = { young: all.young / all.adults, old: all.old / all.adults, temples: all.temples / all.adults, density: all.density / all.adults }; return stats.map((s, ti) => { const traits: RogueTrait[] = []; if (s.adults === 0) return traits; if (s.young / s.adults >= mean.young * 1.05) traits.push("young"); if (s.old / s.adults >= mean.old * 1.15) traits.push("old"); if (s.temples / s.adults >= mean.temples * 1.4) traits.push("temples"); const density = s.density / s.adults / mean.density; if (density >= 1.5) traits.push("dense"); if (density <= 0.3) traits.push("rural"); if ((world.pack.towns[ti]!.hakkaShare ?? 0) >= 0.4) traits.push("hakka"); return traits; }); } /** 把 arcs(多層巢狀陣列)攤平成 arc 編號;負數 ~i 和 i 是同一條邊 */ function arcIds(arcs: unknown, out: number[] = []): number[] { if (typeof arcs === "number") out.push(arcs < 0 ? ~arcs : arcs); else if (Array.isArray(arcs)) for (const a of arcs) arcIds(a, out); return out; } /** * 相鄰的區:共用同一條邊界(arc)的就是鄰居。縣市層級(總統選舉)用鄉鎮的邊界組成縣市。 * codes 是遊戲裡的區代碼;不在裡面的區(選區外)不算。 */ export function townNeighbors(topology: TopologyLike, codes: readonly string[], level: "town" | "county" = "town"): Map { const wanted = new Set(codes); const byArc = new Map>(); for (const g of topology.objects.towns?.geometries ?? []) { const town = String(g.properties?.townCode ?? ""); const code = level === "county" ? `${town.slice(0, 5)}000` : town; if (!wanted.has(code)) continue; for (const arc of arcIds(g.arcs)) { const set = byArc.get(arc) ?? new Set(); set.add(code); byArc.set(arc, set); } } const out = new Map>(codes.map((c) => [c, new Set()])); for (const set of byArc.values()) { if (set.size < 2) continue; for (const a of set) for (const b of set) if (a !== b) out.get(a)!.add(b); } return new Map([...out].map(([k, v]) => [k, [...v].sort()])); } export interface SetupOptions { /** 勢均力敵:雙方全市底盤拉平(劇本 id 結尾是 -even 的一定拉平) */ even?: boolean; /** 照真實底盤時最多落後幾個百分點(比例,例如 0.15):政治生涯保留真實差距,但不會開局就沒機會(18 第 57 項) */ maxGap?: number; topology?: TopologyLike | null; } /** 由劇本與玩家選的候選人建開局;對手是開局預期得票最高的其他候選人,其他人合併成「其他」 */ export function buildSetup(world: World, candidateId: string, opts: SetupOptions = {}): RogueSetup { const { scenario, pack, params } = world; const ci = scenario.candidates.findIndex((c) => c.id === candidateId); if (ci < 0) throw new Error(`劇本中沒有候選人 ${candidateId}`); const state = createMatch(world, "rogue-setup", 1, candidateId); const agg = aggregate(computeVoteModel(state, scenario, pack, params, null), pack, scenario.candidates.length); const ri = agg.votes.map((v, i) => ({ v, i })).filter((x) => x.i !== ci).sort((a, b) => b.v - a.v)[0]!.i; const traits = townTraits(world); // 「勢均力敵」劇本:雙方全市底盤拉平,各區的強弱分布不變 const even = opts.even || scenario.id.endsWith("-even"); const youAll = agg.byTown.reduce((a, row) => a + row[ci]!, 0); const rivalAll = agg.byTown.reduce((a, row) => a + row[ri]!, 0); const castAll = agg.byTown.reduce((a, row) => a + row.reduce((x, y) => x + y, 0), 0) || 1; const cap = opts.maxGap ?? null; const tooFar = !even && cap !== null && (rivalAll - youAll) / castAll > cap; // 落後超過上限:雙方合計不變,拉到剛好落後 cap(各區的強弱分布不變) const capped = tooFar ? { you: (youAll + rivalAll - cap * castAll) / 2, rival: (youAll + rivalAll + cap * castAll) / 2 } : null; const fix = even ? { you: (youAll + rivalAll) / 2 / youAll, rival: (youAll + rivalAll) / 2 / rivalAll } : capped ? { you: capped.you / youAll, rival: capped.rival / rivalAll } : { you: 1, rival: 1 }; const towns: TownSetup[] = pack.towns.map((t, ti) => { const row = agg.byTown[ti]!; const cast = row.reduce((a, b) => a + b, 0) || 1; const others = Math.max(0, cast - row[ci]! - row[ri]!) / cast; const you = (row[ci]! * fix.you) / cast; const rival = (row[ri]! * fix.rival) / cast; // 拉平後各區比例可能不再加總 1,依比例縮回去 const sum = you + rival + others; return { code: t.code, name: t.name, voters: Math.round(cast), lean: { you: you / sum, rival: rival / sum, others: others / sum }, traits: traits[ti]! }; }); if (opts.topology) { const neighbors = townNeighbors(opts.topology, towns.map((t) => t.code), scenario.region.regionLevel ?? "town"); for (const t of towns) t.neighbors = neighbors.get(t.code) ?? []; } // 其他候選人裡最強的一位:開票時要贏過的是他,不是其他人的票加起來 const otherVotes = agg.votes.map((v, i) => (i === ci || i === ri ? 0 : v)); const othersSum = otherVotes.reduce((a, b) => a + b, 0); const othersTop = othersSum > 0 ? Math.max(...otherVotes) / othersSum : 1; const people = viewFor(state, world, candidateId).candidates; const style = scenario.candidates[ri]!.aiStyle; return { scenarioId: scenario.id, scenarioName: scenario.name, packId: scenario.packId, countyCode: scenario.region.countyCode, countyName: scenario.region.countyName, area: scenario.region.area ?? scenario.region.countyName, office: scenario.region.office, you: people[ci]!, rival: people[ri]!, others: people.filter((_, i) => i !== ci && i !== ri), towns, // 劇本的起始資金(元)換成萬元;遊戲裡的花費也是萬元 money: Math.max(300, Math.round(scenario.candidates[ci]!.startingMoney / 10_000)), rivalStyle: style === "ground" || style === "air" ? style : "balanced", // 自創角色以外都是真實人物 rivalReal: scenario.candidates[ri]!.id !== "custom", othersTop, }; }