選戰卡牌第四版:本週戰場、加開行程、逆風重排、逐張地圖校準;手機版修正;刪除人物資料庫與 AI 評分

玩法(docs/26):
- 本週戰場:每週一個選情接近的大區,對手全力搶攻,週末淨增多的一方贏(聲勢 +1、多抽一張)
- 加開行程:每週一次花資金換 1 點體力;起始資金壓到 500–1,000 萬
- 對手落後 3 個百分點以上急起直追;打對台可以搶廣告版面、讓造勢冷場;大絕招集氣加快
- 逆風 0–10 重排成一級一條規則(ASC_RULES),每一級都看得出差別
- 平衡:空戰對手、對手規則、六種類型、空戰/攻防流派、擴散不看鄰區數、區的大小係數、
  對手規模依區數、只有一區的選區沒有本命區和戰場、總統大選全國動員、勢均力敵的第三位候選人
- 逐張地圖校準:apps/sim rogue-calibrate 跑過 219 張勢均力敵地圖,calibration.ts 存每張的對手係數
- 模擬工具載入劇本和伺服器一致(總統合成縣市、立委只取選區村里)

畫面:
- 戰場比數、加開按鈕、急起直追提示、週末戰場輸贏;遊戲中「存檔離開」回主選單
- 手機直放、橫放的破版修正(圖鑑完成度、遊戲畫面、首頁、捏人物、服裝店、小遊戲等)

刪除(依使用者決定):人物資料庫(Wikidata、內閣、現任名單 → people.json)與 AI 評分管線、
config/people、相關測試、protocol 的 people.ts、docs/rubric-v1.md;records 用到的 names、cec_results 保留

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha5kfuiGbEBhsk7ijDg
This commit is contained in:
王性驊 2026-10-30 07:42:15 +08:00
parent 5ae67fd469
commit bfdf2e3df8
113 changed files with 1755 additions and 5864 deletions

View File

@ -1,6 +1,6 @@
# 選舉小鎮 — 後端
遊戲規則、資料管線、人物資料庫與 AI 評分。前端在另一個程式庫(`../web`),只透過 `packages/protocol` 的協定和後端溝通。設計文件在 [`docs/`](docs/README.md)。
遊戲規則、資料管線、歷屆參選人資料庫。前端在另一個程式庫(`../web`),只透過 `packages/protocol` 的協定和後端溝通。設計文件在 [`docs/`](docs/README.md)。
## 目錄
@ -120,23 +120,6 @@ cd ../..
pnpm avatar:build # 頭像部件 SVG → packages/protocol/src/avatar/*.generated.ts
```
## 人物資料庫與 AI 評分
> 目前遊戲不讀 `people.json` 和評分結果;歷屆參選人頁用的是上面 `records` 產生的客觀資歷分數。
```bash
cd data/pipeline
.venv/bin/python -m election_data.people # 產生 data/build/people/people.json
.venv/bin/python -m election_data.scoring --dry-run # 不呼叫 API:預覽證據包、估計費用
.venv/bin/python -m election_data.scoring --limit 5 # 先評 5 人試跑
.venv/bin/python -m election_data.scoring # 全部
```
- 人物資料第一次執行約 8 分鐘(Wikidata 查詢服務有流量限制),之後讀快取約 1 秒。可以設定環境變數 `ELECTION_DATA_CONTACT`(專案網址),放進給 Wikidata 的 User-Agent。人工維護的資料在 `data/pipeline/config/people/`。
- AI 評分使用 Claude API,憑證由 SDK 自行讀取:設定環境變數 `ANTHROPIC_API_KEY`,或安裝 `ant` 指令列工具後執行 `ant auth login`。
- 評分會產生費用。請先用 `--dry-run` 看估計,再決定範圍。
- 評分規則:[`docs/rubric-v1.md`](docs/rubric-v1.md)。輸出 `people_scored.json`、`scoring_report.md`(一致性、政黨偏差檢查)、`review_sample.csv`(人工抽查清單)。
## 測試
```bash

View File

@ -13,6 +13,7 @@ import {
createRun,
endWeek,
playCard,
rush,
toView,
tutorialSetup,
ultimate,
@ -72,7 +73,7 @@ const dailySeed = (date: string): number => {
/**
* 選戰卡牌(新玩法,docs/21、22)的 API:規則在伺服器跑,前端每出一張牌就拿到新的畫面狀態。
* POST /api/rogue/runs 開局;/tutorial 新手教學;/play 出牌;/end-week 結束這週;/choose 劇情、下一站的選擇。
* POST /api/rogue/runs 開局;/tutorial 新手教學;/play 出牌;/rush 加開行程;/end-week 結束這週;/choose 劇情、下一站的選擇。
* 每一局存成 JSON 檔(有版本號),伺服器重開也能繼續玩。
*/
export function registerRogue(app: FastifyInstance, ctx: RogueContext): void {
@ -268,6 +269,15 @@ export function registerRogue(app: FastifyInstance, ctx: RogueContext): void {
return save(r);
});
/** 加開行程(docs/26):花資金換 1 點體力,每週一次 */
app.post<{ Params: { id: string } }>("/api/rogue/runs/:id/rush", async (request, reply) => {
const s = await load(request.params.id);
if (!s) return ctx.fail(reply, 404, "找不到這一局(可能已過期或是舊版的存檔)");
const r = rush(s);
if ("error" in r) return ctx.fail(reply, 409, r.error);
return save(r);
});
app.post<{ Params: { id: string } }>("/api/rogue/runs/:id/end-week", async (request, reply) => {
const s = await load(request.params.id);
if (!s) return ctx.fail(reply, 404, "找不到這一局(可能已過期或是舊版的存檔)");

View File

@ -9,7 +9,8 @@
"typecheck": "tsc -p tsconfig.json",
"balance": "node src/balance.ts",
"calibrate-local": "node src/calibrate-local.ts",
"rogue-balance": "node src/rogue-balance.ts"
"rogue-balance": "node src/rogue-balance.ts",
"rogue-calibrate": "node src/rogue-calibrate.ts"
},
"dependencies": {
"@election2026/content": "workspace:*",

View File

@ -0,0 +1,89 @@
/**
* 逐張地圖的對手強度校準(docs/26):node src/rogue-calibrate.ts [--seeds 15] [--shard 0/6] [--out out/calib-0.jsonl]
* 量:每張「勢均力敵」地圖、每位主要候選人,用「隨手玩」打 seeds 局(亂數種子從 --base 開始;驗證時換一組沒用來校準的)(你和對手的類型輪流、對手風格照劇本),記下平均差距。
* 寫:node src/rogue-calibrate.ts --write out/calib-*.jsonl:依量到的差距調整 packages/rogue/src/calibration.ts 的係數
* (差距比目標高 → 對手強一點)。可以重複「量 → 寫」逼近目標;係數夾在 0.85–1.2。
*/
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { parseArgs } from "node:util";
import type { RogueArchetype } from "@election2026/protocol";
import { MAP_CALIBRATION, runBot } from "@election2026/rogue";
import { DEFAULT_PACKS_ROOT } from "@election2026/pack-loader";
import { loadScenarioRegistry } from "@election2026/scenarios";
import { buildSetup, type TopologyLike } from "@election2026/rogue/setup";
import { loadWorld } from "./world.ts";
/** 目標:隨手玩的平均差距(百分點);桃園 2022 校準時約 −0.3(勝率四成多) */
const TARGET = -0.3;
/** 對手強度每多 1%,隨手玩的差距少多少個百分點(模擬量的,約 0.11) */
const SLOPE = 0.11;
/** 每次只修正量到的偏差的一部分(每張地圖幾十局,雜訊約 ±0.4 個百分點,和地圖之間的差距差不多大);--shrink 可以改 */
const SHRINK = 0.6;
const ARCH: RogueArchetype[] = ["media", "organization", "eloquence", "finance", "integrity", "newcomer"];
interface Row {
id: string;
n: number;
margin: number;
}
const baseId = (id: string) => id.replace(/-even$/, "");
async function measure(seeds: number, base: number, shard: [number, number], out: string): Promise<void> {
const reg = await loadScenarioRegistry();
const ids = reg.all.map((s) => s.id).filter((id) => id.endsWith("-even")).sort();
const mine = ids.filter((_, i) => i % shard[1] === shard[0]);
const lines: string[] = [];
for (const id of mine) {
const world = await loadWorld(id);
const topology = JSON.parse(await readFile(join(DEFAULT_PACKS_ROOT, world.scenario.packId, "topology.json"), "utf-8")) as TopologyLike;
const majors = world.scenario.candidates.filter((c) => c.slot === "a" || c.slot === "b");
let sum = 0;
let n = 0;
for (const [ci, cand] of majors.entries()) {
const setup = buildSetup(world, cand.id, { topology });
for (let seed = base; seed < base + seeds; seed++) {
const r = runBot(setup, seed, "casual", { archetype: ARCH[(seed + ci) % 6], rivalArchetype: ARCH[(seed * 5 + 1) % 6] }).result!;
sum += (r.youShare - r.rivalShare) * 100;
n++;
}
}
const row: Row = { id: baseId(id), n, margin: sum / (n || 1) };
lines.push(JSON.stringify(row));
console.log(`${row.id} ${row.margin.toFixed(2)}(${n} 局)`);
}
await writeFile(out, lines.join("\n") + "\n");
}
async function write(files: string[], shrink: number): Promise<void> {
const rows: Row[] = [];
for (const f of files) for (const line of (await readFile(f, "utf-8")).split("\n").filter(Boolean)) rows.push(JSON.parse(line) as Row);
const next: Record<string, number> = { ...MAP_CALIBRATION };
for (const r of rows) {
const now = MAP_CALIBRATION[r.id] ?? 1;
// 差距比目標高(太簡單)→ 對手強一點
const f = now * (1 + (shrink * (r.margin - TARGET)) / SLOPE / 100);
next[r.id] = Math.round(Math.min(1.2, Math.max(0.85, f)) * 1000) / 1000;
}
const body = Object.keys(next)
.sort()
.map((k) => ` "${k}": ${next[k]},`)
.join("\n");
const path = new URL("../../../packages/rogue/src/calibration.ts", import.meta.url);
const src = await readFile(path, "utf-8");
const out = src.replace(/export const MAP_CALIBRATION: Readonly<Record<string, number>> = \{[\s\S]*?\n?\};/, `export const MAP_CALIBRATION: Readonly<Record<string, number>> = {\n${body}\n};`);
await writeFile(path, out);
const spread = rows.map((r) => r.margin).sort((a, b) => a - b);
console.log(`寫入 ${Object.keys(next).length} 張地圖;這次量到的差距 ${spread[0]?.toFixed(2)}~${spread[spread.length - 1]?.toFixed(2)},中位數 ${spread[Math.floor(spread.length / 2)]?.toFixed(2)}`);
}
const { values, positionals } = parseArgs({
options: { seeds: { type: "string", default: "15" }, base: { type: "string", default: "9000" }, shrink: { type: "string", default: String(SHRINK) }, shard: { type: "string", default: "0/1" }, out: { type: "string", default: "out/calib.jsonl" }, write: { type: "boolean", default: false } },
allowPositionals: true,
});
if (values.write) await write(positionals, Number(values.shrink));
else {
const [k, n] = values.shard.split("/").map(Number) as [number, number];
await measure(Number(values.seeds), Number(values.base), [k, n], values.out);
}

View File

@ -6,6 +6,7 @@ import { loadPack } from "@election2026/pack-loader";
export async function loadWorld(scenarioId: string, mood?: Scenario["mood"]): Promise<World> {
const scenario = (await loadScenarioRegistry()).find(scenarioId);
if (!scenario) throw new Error(`找不到劇本 ${scenarioId}`);
const pack = await loadPack(scenario.packId);
// 和伺服器(apps/server/src/app.ts)一樣:總統選舉合成縣市、立委只取選區內的村里
const pack = await loadPack(scenario.packId, undefined, { regionLevel: scenario.region.regionLevel, villages: scenario.villages ? new Set(scenario.villages) : undefined });
return { scenario: mood ? { ...scenario, mood } : scenario, pack, content: CONTENT, params: DEFAULT_PARAMS };
}

View File

@ -1,31 +0,0 @@
# 代理中的縣市首長(手動維護)
#
# 內政部地方公職人員資訊專區只列當選人,不含停職與代理資訊,所以代理首長在這裡補上。
# 規則同 party_chairs.yaml:每筆都要有實際擷取並確認過的來源。
# 2026-10-25 查核:新竹市長高虹安已於 2025-12 復職(內政部專區仍列為市長),目前沒有代理;
# 宜蘭縣由副縣長林茂盛代理縣長。
acting:
- name: 林茂盛
category: official
county: 宜蘭縣
positions:
- title: 代理縣長
org: 宜蘭縣政府
from: "2024-12-31"
to: null
- title: 副縣長
org: 宜蘭縣政府
from: null
to: null
education:
- 台灣科技大學營建所碩士
- 東吳大學法律研究所碩士
sources:
- id: yilan-acting-magistrate
title: 宜蘭縣政府 代理縣長介紹
agency: 宜蘭縣政府
url: https://www.e-land.gov.tw/cp.aspx?n=2700
license: 宜蘭縣政府網站資料開放宣告
retrievedAt: "2026-10-25"
quote: "宜蘭縣政府代理縣長 林茂盛…經歷:宜蘭縣政府代理縣長(113年12月31日迄今)、宜蘭縣政府副縣長"

View File

@ -1,32 +0,0 @@
# 更正(手動維護):官方資料已知過時的欄位
#
# 目前只支援 field: party。內政部地方公職人員資訊專區的黨籍是 111 年選舉時的黨籍,
# 之後的退黨、恢復黨籍不會反映;查證到異動時在這裡更正,並附上實際擷取過的來源。
# value: null 代表「目前不屬於原政黨、現屬政黨未經查證」。
overrides:
- name: 鍾東錦
field: party
value: 中國國民黨
note: 2025-09-14 恢復中國國民黨黨籍(內政部專區仍為 111 年選舉時的「無」)
sources:
- id: udn-20251216-chung-tung-chin
title: 鍾東錦:不放棄爭取苗栗實中(新聞報導,2025-12-16)
agency: 聯合新聞網
url: https://udn.com/news/story/124678/9205131
license: 新聞報導(僅引用事實,未轉載內容)
retrievedAt: "2026-10-25"
quote: "鍾東錦今年9月14日恢復黨籍"
- name: 高虹安
field: party
value: null
note: 2024-07-26 宣布退出台灣民眾黨;截至 2026-10-25 未查得恢復黨籍的資料(內政部專區仍為台灣民眾黨)
sources:
- id: gvm-20240726-kao-hung-an
title: 高虹安宣布退出台灣民眾黨(新聞報導,2024-07-26)
agency: 遠見雜誌
url: https://www.gvm.com.tw/article/114603
license: 新聞報導(僅引用事實,未轉載內容)
retrievedAt: "2026-10-25"
quote: "高虹安並宣布「即刻退出台灣民眾黨,謝謝各界的關心。」"

View File

@ -1,88 +0,0 @@
# 政黨主席(手動維護)
#
# 規則:
# - 每一筆都要有至少一個 sources,且是實際擷取頁面、確認頁面文字後才填入(retrievedAt 為擷取日)。
# - 不憑記憶填寫;黨主席異動時更新本檔並更新 retrievedAt。
# - from:只有在來源寫明就任日期時才填,否則為 null。
# - quote:來源頁面上確認的原文片段,方便日後複查。
chairs:
- name: 賴清德
party: 民主進步黨
title: 黨主席
from: null
sources:
- id: dpp-chair-and-officers
title: 民主進步黨 主席及黨務主管
agency: 民主進步黨
url: https://www.dpp.org.tw/about/political
license: 政黨官方網站(僅引用事實資料)
retrievedAt: "2026-10-25"
quote: "主席及黨務主管|主席|賴清德|秘書長|徐國勇"
- name: 鄭麗文
party: 中國國民黨
title: 黨主席
from: null
sources:
- id: kmt-chair
title: 中國國民黨 主席(現任主席)
agency: 中國國民黨
url: https://www1.kmt.org.tw/people.aspx?mid=18
license: 政黨官方網站(僅引用事實資料)
retrievedAt: "2026-10-25"
quote: "現任主席|歷屆主席|主席|鄭麗文"
- id: kmt-press-20261025
title: 中國國民黨新聞稿(115.10.25)
agency: 中國國民黨文化傳播委員會
url: https://www.kmt.org.tw/2026/10/1128_0409609873.html
license: 政黨官方網站(僅引用事實資料)
retrievedAt: "2026-10-25"
quote: "中國國民黨主席鄭麗文今(25)日出席…"
- name: 黃國昌
party: 台灣民眾黨
title: 黨主席
from: null
sources:
- id: udn-20261007-tpp-chair
title: 民眾黨主席黃國昌出席記者會(新聞報導,2026-10-07)
agency: 聯合新聞網
url: https://udn.com/news/story/6656/9800691
license: 新聞報導(僅引用事實,未轉載內容)
retrievedAt: "2026-10-25"
quote: "雙十國慶即將到來,民眾黨主席黃國昌今天說…(2026-10-07)"
note: 台灣民眾黨官網(www.tpp.org.tw)有防爬蟲阻擋(HTTP 403),改用新聞報導
- id: cna-20260204-tpp-chair
title: 2026選舉 民眾黨徵召黃國昌參選新北市長(新聞報導)
agency: 中央通訊社
url: https://www.cna.com.tw/news/aipl/202602040186.aspx
license: 新聞報導(僅引用事實,未轉載內容)
retrievedAt: "2026-10-25"
quote: "徵召民眾黨主席黃國昌參選2026年新北市長(2026-02-04)"
- name: 王婉諭
party: 時代力量
title: 黨主席
from: null
sources:
- id: npp-20261010
title: 時代力量新聞稿(2026-10-10)
agency: 時代力量
url: https://newpowerparty.tw/archives/31242
license: 政黨官方網站(僅引用事實資料)
retrievedAt: "2026-10-25"
quote: "時代力量黨主席王婉諭今(10)日應國慶籌備委員會邀請…"
- name: 王興煥
party: 台灣基進
title: 黨主席
from: null
sources:
- id: tsp-chair
title: 台灣基進 主席的話
agency: 台灣基進
url: https://www.statebuilding.tw/about/chairman
license: 政黨官方網站(僅引用事實資料)
retrievedAt: "2026-10-25"
quote: "台灣基進黨主席 王興煥"

View File

@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "election-data"
version = "0.1.0"
description = "凍蒜 2026 資料管線:政府開放資料 → 資料包、人物資料庫、AI 評分"
description = "凍蒜 2026 資料管線:政府開放資料 → 資料包、歷屆參選人資料庫"
requires-python = ">=3.12"
dependencies = [
"pandas>=3.0",
@ -16,8 +16,6 @@ dependencies = [
"shapely>=2.0",
"pyshp>=2.3",
"jsonschema>=4.23",
"pyyaml>=6.0",
"anthropic>=0.70",
]
[project.optional-dependencies]

View File

@ -9,7 +9,6 @@ REPO_ROOT = PIPELINE_DIR.parents[1]
RAW_DIR = REPO_ROOT / "data" / "raw"
BUILD_DIR = REPO_ROOT / "data" / "build"
SCHEMA_DIR = REPO_ROOT / "packages" / "protocol" / "schema"
CONFIG_DIR = PIPELINE_DIR / "config"
PROTOCOL_VERSION = "1.0.0"

View File

@ -1,10 +1,5 @@
"""人物資料庫(docs/15):現任立委、縣市長、內閣、政黨主席、2026 縣市長候選人。
"""人名與中選會選舉結果的共用工具(歷屆參選人資料庫 records 用)。
執行:`python -m election_data.people`,輸出 data/build/people/{people.json, sources.json, report.md}。
原本的人物資料庫(Wikidata、內閣、現任名單 → people.json)與 AI 評分已在 2026-10-30 依使用者決定刪除;
遊戲的歷屆參選人頁用的是 records 的客觀資歷分數。這裡只留下 records 會用到的 names.py、cec_results.py。
"""
from __future__ import annotations
from .build import AS_OF, BuildResult, build_people
__all__ = ["AS_OF", "BuildResult", "build_people"]

View File

@ -1,31 +0,0 @@
"""python -m election_data.people [--as-of YYYY-MM-DD] [--skip-wikidata]"""
from __future__ import annotations
import argparse
import logging
from .build import AS_OF, build_people
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="產生人物資料庫(people.json、sources.json、report.md)")
parser.add_argument("--as-of", default=AS_OF, help="資料快照日期(YYYY-MM-DD)")
parser.add_argument("--skip-wikidata", action="store_true", help="不查詢 Wikidata(離線或除錯用)")
parser.add_argument("-v", "--verbose", action="store_true")
args = parser.parse_args(argv)
logging.basicConfig(
level=logging.DEBUG if args.verbose else logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
# httpx 在 INFO 會印出完整網址(SPARQL 查詢很長)
logging.getLogger("httpx").setLevel(logging.WARNING)
result = build_people(args.as_of, use_wikidata=not args.skip_wikidata)
log = logging.getLogger(__name__)
log.info("完成:%d 位人物", result.count)
log.info("輸出:%s、%s、%s", result.people_path, result.sources_path, result.report_path)
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,188 +0,0 @@
"""產生 data/build/people/{people.json, sources.json, report.md}。"""
from __future__ import annotations
import json
import logging
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from ..cec import CecArchive, fetch_votedata
from ..config import BUILD_DIR, CONFIG_DIR, PROTOCOL_VERSION, RAW_DIR
from ..sources import SourceRef, source_ref
from ..validate import validate
from .cabinet import fetch_cabinet
from .candidates import CandidateLoad, fetch_candidates
from .catalog import (
CEC_2026_ELCAND,
CEC_2026_QUALIFIED,
EY_AGENCY_HEADS,
EY_MINISTERS_WITHOUT_PORTFOLIO,
EY_PREMIER,
EY_SECRETARY_SPOKESPERSON,
EY_VICE_PREMIER,
LY_TERM11,
MOI_COUNTY,
MOI_MUNICIPAL,
WIKIDATA,
)
from .cec_results import load_cec_results
from .enrich import CEC_SOURCE_ID, attach_name_only, attach_strong, index_results
from .legislators import fetch_legislators
from .manual import load_manual
from .mayors import fetch_mayors
from .merge import apply_overrides, merge_claims
from .model import PersonDraft
from .output import assign_ids, people_file, referenced_source_ids
from .report import ReportInput, render_report
from .wd_match import WdNote, match_wikidata
from .wikidata import fetch_items
log = logging.getLogger(__name__)
EY_SPECS = (
EY_PREMIER,
EY_VICE_PREMIER,
EY_MINISTERS_WITHOUT_PORTFOLIO,
EY_SECRETARY_SPOKESPERSON,
EY_AGENCY_HEADS,
)
AS_OF = "2026-10-25"
SKIPPED_WIKIDATA = "本次執行略過 Wikidata(--skip-wikidata)。"
KNOWN_GAPS: tuple[str, ...] = (
"立法院 ID9 的「經歷」是沒有分隔的自由文字,沒有解析成職位;過去的職位只收錄有明確起訖日期的立委任期。",
"行政院部會首長頁面沒有到任日期,也沒有性別;性別只採用官方資料(立法院、中選會),"
"未曾參選或擔任立委的官員性別為 null。",
"內政部專區的黨籍是 111 年選舉時的黨籍;查證到的異動已在 config/people/overrides.yaml 更正,"
"其餘縣市長的現任黨籍沒有逐一查證。",
"內政部專區不含停職、代理資訊。宜蘭縣長林姿妙停職中,由副縣長林茂盛代理(config/people/acting_heads.yaml);"
"協定沒有「停職」欄位,林姿妙仍以縣長列出。新竹市長高虹安已於 2025-12 復職。",
"縣市長的就職日期沒有出現在擷取的官方頁面上,所以縣市長職位的 from 為 null;"
"政黨主席的就任日期同樣為 null。",
"職位的 to 為 null 代表「現任」;只有年份或年月的經歷無法用協定的 YYYY-MM-DD 表示,"
"因此未收錄(見最終報告的協定建議)。",
"2022 嘉義市長重行選舉的中選會檔案沒有性別與出生日期。",
"不分區立委的選舉紀錄來自政黨名單(elrepm),votes、share 為 null(不是個人得票)。",
"Wikidata 的出生日期只採用精確到日的值;只有年份的(例如王興煥)不填。",
"立委的委員會只收錄最新會期。",
"docs/15 的 M0 範圍另有總統、副總統、五院院長與副市長,本批未收錄。",
)
@dataclass(frozen=True)
class BuildResult:
people_path: Path
sources_path: Path
report_path: Path
count: int
def _write_json(path: Path, data: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def _candidate_status(cand: CandidateLoad, persons: list[PersonDraft]) -> list[str]:
by_office = Counter(e.office for e in cand.entries)
merged = sum(1 for p in persons if "candidate_2026" in p.roles and len(p.roles) > 1)
lines = [
f"已匯入中選會 {cand.qualified_on} 審定的候選人名單({CEC_2026_QUALIFIED.url}):"
f"直轄市長 {by_office.get('直轄市長', 0)} 人、縣市長 {by_office.get('縣市長', 0)} 人,"
f"共 {len(cand.entries)} 人,"
f"涵蓋 {len({e.county for e in cand.entries})} 個縣市。",
f"其中 {merged} 人同時是現任立委、縣市長或其他已收錄的人物(已合併,見下方合併紀錄)。",
]
if cand.elcand_offices:
lines.append(f"已改用正式公告的 elcand 檔:{'、'.join(cand.elcand_offices)}。")
pending = [o for o in ("直轄市長", "縣市長") if o not in cand.elcand_offices]
if pending:
lines.append(
"正式公告待發布(直轄市長 11/12、縣市長 11/17):"
f"{'、'.join(pending)}候選人的號次、政黨、性別、出生日期為 pending。"
"號次已於 10/23 抽籤,但本批沒有匯入各選委會的抽籤結果。"
)
lines.append(
"公告後把 elcand 格式的檔案放到 data/raw/people/cec2026/{municipal,county}/elcand.csv"
"(可附 elbase.csv、elpaty.csv)再重新執行,即會改用正式資料。"
)
return lines
def _sources(refs: list[SourceRef], used: set[str]) -> dict[str, Any]:
by_id: dict[str, SourceRef] = {}
for ref in refs:
by_id.setdefault(ref.id, ref)
missing = used - by_id.keys()
if missing:
raise ValueError(f"people.json 引用了 sources.json 沒有的來源:{sorted(missing)}")
return {
"protocolVersion": PROTOCOL_VERSION,
"sources": [by_id[i].to_json() for i in sorted(used)],
}
def build_people(as_of: str = AS_OF, *, use_wikidata: bool = True) -> BuildResult:
raw = RAW_DIR / "people"
out_dir = BUILD_DIR / "people"
refs: list[SourceRef] = []
legislators, ly_res = fetch_legislators(raw)
refs.append(LY_TERM11.ref(ly_res.retrieved_at))
mayors, moi_res = fetch_mayors(raw)
refs += [spec.ref(moi_res[spec.id].retrieved_at) for spec in (MOI_MUNICIPAL, MOI_COUNTY)]
cabinet, ey_res = fetch_cabinet(raw)
refs += [spec.ref(ey_res[spec.id].retrieved_at) for spec in EY_SPECS]
manual = load_manual(CONFIG_DIR / "people")
refs += list(manual.sources)
cand = fetch_candidates(raw)
refs.append(CEC_2026_QUALIFIED.ref(cand.press_release.retrieved_at))
refs.append(CEC_2026_ELCAND.ref(as_of))
persons, merge_notes = merge_claims([*legislators, *mayors, *cabinet, *manual.claims, *cand.claims])
persons, override_notes = apply_overrides(persons, manual.overrides)
merge_notes += override_notes
votedata = fetch_votedata()
refs.append(source_ref(CEC_SOURCE_ID, votedata.retrieved_at))
index = index_results(load_cec_results(CecArchive(votedata.path)))
persons, match_notes, done = attach_strong(persons, index)
wd_notes: list[WdNote] = []
if use_wikidata:
items, wd_date = fetch_items((p.name for p in persons), raw / "wikidata")
persons, wd_notes = match_wikidata(persons, items)
refs.append(WIKIDATA.ref(wd_date or as_of))
persons, name_only_notes = attach_name_only(persons, index, done)
match_notes += name_only_notes
ids = assign_ids(persons)
doc = people_file(persons, ids, PROTOCOL_VERSION, as_of)
sources = _sources(refs, referenced_source_ids(doc))
validate(doc, "people.schema.json")
validate(sources, "sources.schema.json")
report = render_report(
ReportInput(
as_of=as_of,
doc=doc,
roles_by_id={pid: p.roles for pid, p in zip(ids, persons, strict=True)},
merge_notes=merge_notes,
match_notes=match_notes,
wd_notes=wd_notes,
candidate_status=_candidate_status(cand, persons),
known_gaps=KNOWN_GAPS if use_wikidata else (*KNOWN_GAPS, SKIPPED_WIKIDATA),
)
)
people_path, sources_path, report_path = (
out_dir / "people.json",
out_dir / "sources.json",
out_dir / "report.md",
)
_write_json(people_path, doc)
_write_json(sources_path, sources)
report_path.write_text(report, encoding="utf-8")
log.info("已輸出 %d 位人物 → %s", len(doc["people"]), people_path)
return BuildResult(people_path, sources_path, report_path, len(doc["people"]))

View File

@ -1,192 +0,0 @@
"""行政院內閣:院長、副院長、政務委員、秘書長、發言人、部會首長(行政院網站,只有 HTML)。"""
from __future__ import annotations
import html
import logging
import re
from dataclasses import dataclass
from pathlib import Path
from ..fetch import FetchResult
from .catalog import (
EY_AGENCY_HEADS,
EY_MINISTERS_WITHOUT_PORTFOLIO,
EY_PREMIER,
EY_SECRETARY_SPOKESPERSON,
EY_VICE_PREMIER,
PeopleSourceSpec,
)
from .downloads import fetch as download
from .education import parse_education
from .htmltext import html_lines
from .model import EducationRec, PersonClaim, PositionRec
from .names import display_name
log = logging.getLogger(__name__)
# 長的職稱放前面,避免「代理主任委員」被當成「主任委員」
TITLES: tuple[str, ...] = tuple(
sorted(
(
"代理主任委員",
"代理委員長",
"代理部長",
"代理院長",
"代理總裁",
"代理主計長",
"代理人事長",
"主任委員",
"政務委員",
"委員長",
"副院長",
"秘書長",
"發言人",
"主計長",
"人事長",
"部長",
"院長",
"總裁",
),
key=len,
reverse=True,
)
)
_MEMBER = re.compile(
r'<span class="title">\s*<span[^>]*>(?P<org>[^<]+)</span>\s*<br\s*/?>\s*<span>(?P<person>[^<]+)</span>',
re.S,
)
_LEADER = re.compile(r"^行政院(?P<name>[\u4e00-\u9fff]{2,5}?)(?P<title>副院長|院長)$")
_ROC_DAY = re.compile(r"民國\s*(\d{2,3})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日")
@dataclass(frozen=True)
class Member:
org: str
name: str
title: str
@dataclass(frozen=True)
class Leader:
name: str
title: str
education: tuple[str, ...]
start: str | None
def split_name_title(text: str) -> tuple[str, str]:
"""「劉世芳部長」→(劉世芳, 部長);
「曾智勇 Ljaucu‧Zingrur 主任委員」→(曾智勇 Ljaucu‧Zingrur, 主任委員)。"""
cleaned = display_name(html.unescape(text))
for title in TITLES:
if cleaned.endswith(title) and len(cleaned) > len(title):
return display_name(cleaned[: -len(title)]), title
raise ValueError(f"無法從「{text}」分出姓名與職稱")
def parse_members(page: str) -> list[Member]:
out = []
for m in _MEMBER.finditer(page):
name, title = split_name_title(m["person"])
out.append(Member(display_name(html.unescape(m["org"])), name, title))
return out
def roc_day(text: str) -> str | None:
m = _ROC_DAY.search(text)
if not m:
return None
return f"{int(m[1]) + 1911:04d}-{int(m[2]):02d}-{int(m[3]):02d}"
def _pairs(lines: list[str]) -> list[tuple[str, str]]:
"""學經歷區塊是「期間、內容」交錯的行。"""
out: list[tuple[str, str]] = []
period = ""
for line in lines:
if line.startswith("民國"):
period = line
else:
out.append((period, line))
period = ""
return out
def parse_leader(page: str) -> Leader:
lines = [
line.replace(" ", "") if line.replace(" ", "") in ("學歷", "經歷") else line
for line in html_lines(page)
]
head = next(((i, m) for i, line in enumerate(lines) if (m := _LEADER.match(line))), None)
if head is None:
raise ValueError("行政院首長頁面找不到「行政院○○○院長」標題")
i, m = head
rest = lines[i + 1 :]
edu_start = rest.index("學歷") + 1 if "學歷" in rest else len(rest)
exp_start = rest.index("經歷") + 1 if "經歷" in rest else len(rest)
end = next((k for k, line in enumerate(rest) if line.startswith("以上內容之著作權")), len(rest))
education = tuple(text for _, text in _pairs(rest[edu_start : exp_start - 1]))
current_title = f"行政院{m['title']}"
start = next(
(roc_day(period) for period, text in _pairs(rest[exp_start:end]) if text == current_title), None
)
return Leader(display_name(m["name"]), m["title"], education, start)
def _education(lines: tuple[str, ...], src: tuple[str, ...]) -> tuple[EducationRec, ...]:
out: list[EducationRec] = []
for line in lines:
for degree, school in parse_education(line):
rec = EducationRec(degree, school, src)
if rec not in out:
out.append(rec)
return tuple(out)
def member_claim(member: Member, source_id: str) -> PersonClaim:
return PersonClaim(
name=member.name,
role="official",
category="official",
name_source=source_id,
positions=(PositionRec(member.title, member.org, None, None, (source_id,)),),
)
def leader_claim(leader: Leader, source_id: str) -> PersonClaim:
src = (source_id,)
return PersonClaim(
name=leader.name,
role="official",
category="official",
name_source=source_id,
positions=(PositionRec(leader.title, "行政院", leader.start, None, src),),
education=_education(leader.education, src),
)
def _page_id(spec: PeopleSourceSpec) -> str:
return spec.url.rsplit("/", 1)[-1]
def fetch_cabinet(raw_dir: Path) -> tuple[list[PersonClaim], dict[str, FetchResult]]:
claims: list[PersonClaim] = []
results: dict[str, FetchResult] = {}
for spec in (EY_PREMIER, EY_VICE_PREMIER):
res = download(spec.url, raw_dir / "ey" / f"{_page_id(spec)}.html")
results[spec.id] = res
claims.append(leader_claim(parse_leader(res.path.read_text(encoding="utf-8")), spec.id))
for spec, minimum in (
(EY_MINISTERS_WITHOUT_PORTFOLIO, 1),
(EY_SECRETARY_SPOKESPERSON, 1),
(EY_AGENCY_HEADS, 20),
):
res = download(spec.url, raw_dir / "ey" / f"{_page_id(spec)}.html")
results[spec.id] = res
members = parse_members(res.path.read_text(encoding="utf-8"))
if len(members) < minimum:
raise ValueError(f"{spec.title} 只解析到 {len(members)} 人,頁面格式可能已改變:{spec.url}")
claims.extend(member_claim(member, spec.id) for member in members)
log.info("內閣:%d 筆職位", len(claims))
return claims, results

View File

@ -1,192 +0,0 @@
"""2026(115 年)直轄市長、縣市長候選人。
- 目前可用的官方名單:中選會 115-10-16 審定候選人資格的新聞稿(只有縣市與姓名)。
中選會網站是前端渲染,內容來自 `api/central/article/{id}`。
- 正式公告(直轄市長 11/12、縣市長 11/17)後,若取得 elcand 格式的檔案,放在
data/raw/people/cec2026/{municipal,county}/elcand.csv(可附 elbase.csv、elpaty.csv),
就會改用該檔(含號次、政黨、性別、出生日期)。
"""
from __future__ import annotations
import csv
import json
import logging
import re
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from pathlib import Path
from ..codes import roc_to_iso_date
from ..fetch import FetchResult
from .catalog import CEC_2026_ELCAND, CEC_2026_QUALIFIED
from .downloads import fetch as download
from .htmltext import html_lines
from .model import PersonClaim, PositionRec, Sourced
from .names import county_key, display_name
log = logging.getLogger(__name__)
CEC_ARTICLE_API = "https://web.cec.gov.tw/api/central/article/65213"
MUNICIPAL = "直轄市長"
COUNTY = "縣市長"
ELECTION_ORG = {MUNICIPAL: "115年直轄市長選舉", COUNTY: "115年縣(市)長選舉"}
ELCAND_DIRS = {MUNICIPAL: "municipal", COUNTY: "county"}
_SECTION = re.compile(
r"^[一二三四五六]、(?P<office>直轄市長|縣\(市\)長|縣(市)長)候選人部分.*?受理登記計(?P<n>\d+)人"
)
_OTHER_SECTION = re.compile(r"^[一二三四五六七八九]、")
_COUNTY_LINE = re.compile(
r"^([一二三四五六七八九十]+)(?P<county>.+?[市縣])(?P<n>\d+)人[::](?P<names>.+?)。?$"
)
_GENDER = {"1": "M", "2": "F"}
_INDEPENDENT_CODES = frozenset({"999", "0", ""})
@dataclass(frozen=True)
class CandidateEntry:
name: str
county: str
office: str # 直轄市長 / 縣市長
source_id: str
number: int | None = None
party: str | None = None
party_known: bool = False
gender: str | None = None
birth_date: str | None = None
def article_html(api_json: dict) -> tuple[str, str | None]:
"""中選會文章 API → (內文 HTML, 發布日期 YYYY-MM-DD)。"""
data = api_json.get("data") or {}
blocks = json.loads(data.get("content") or "{}").get("content") or []
body = "".join(b.get("content", "") for b in blocks if b.get("blockType") == "Text")
begin = str(data.get("beginTime") or "")
date = f"{begin[:4]}-{begin[4:6]}-{begin[6:8]}" if re.fullmatch(r"\d{8}", begin) else None
return body, date
def parse_press_release(body_html: str, source_id: str) -> list[CandidateEntry]:
"""解析審定名單;每個縣市的人數與總數都要和姓名數一致,否則丟出錯誤。"""
entries: list[CandidateEntry] = []
office: str | None = None
expected: dict[str, int] = {}
for line in html_lines(body_html):
if m := _SECTION.match(line):
office = MUNICIPAL if m["office"] == MUNICIPAL else COUNTY
expected[office] = int(m["n"])
continue
if _OTHER_SECTION.match(line):
office = None
continue
if office and (m := _COUNTY_LINE.match(line)):
names = [display_name(n) for n in m["names"].split("、") if n.strip()]
if len(names) != int(m["n"]):
raise ValueError(f"{m['county']} 應有 {m['n']} 人,解析到 {len(names)} 人:{line}")
county = county_key(m["county"])
entries += [CandidateEntry(n, county, office, source_id) for n in names]
for kind, total in expected.items():
got = sum(e.office == kind for e in entries)
if got != total:
raise ValueError(f"{kind}候選人應有 {total} 人,解析到 {got} 人")
if not entries:
raise ValueError("中選會新聞稿中找不到候選人名單")
return entries
def parse_elcand(
elcand: Iterable[Sequence[str]],
elbase: Iterable[Sequence[str]],
elpaty: Iterable[Sequence[str]],
office: str,
source_id: str,
) -> list[CandidateEntry]:
"""中選會 elcand 格式:
省市,縣市,選區,鄉鎮,村里,號次,姓名,政黨代號,性別,出生日期,年齡,出生地,學歷,現任,當選註記,副手。"""
counties = {
(r[0], r[1]): county_key(r[5]) for r in elbase if len(r) >= 6 and r[3] == "000" and r[4] == "0000"
}
parties = {r[0]: r[1] for r in elpaty if len(r) >= 2}
out = []
for row in elcand:
if len(row) < 10 or row[15:16] == ["Y"]:
continue
county = counties.get((row[0], row[1]))
if county is None:
raise ValueError(f"elcand 的縣市代碼 {row[0]}/{row[1]} 在 elbase 找不到")
code = row[7].strip()
out.append(
CandidateEntry(
name=display_name(row[6]),
county=county,
office=office,
source_id=source_id,
number=int(row[5]) if row[5].strip().isdigit() else None,
party=None if code in _INDEPENDENT_CODES else parties.get(code, code),
party_known=True,
gender=_GENDER.get(row[8].strip()),
birth_date=roc_to_iso_date(row[9]),
)
)
return out
def to_claim(entry: CandidateEntry, qualified_on: str | None) -> PersonClaim:
src = (entry.source_id,)
number = f"(號次 {entry.number})" if entry.number is not None else ""
title = f"{entry.county}長候選人{number}"
return PersonClaim(
name=entry.name,
role="candidate_2026",
category="politician",
name_source=entry.source_id,
county=entry.county,
gender=Sourced(entry.gender, src) if entry.gender else None,
birth_date=Sourced(entry.birth_date, src) if entry.birth_date else None,
party=Sourced(entry.party, src) if entry.party_known else None,
positions=(PositionRec(title, ELECTION_ORG[entry.office], qualified_on, None, src),),
)
def _read_csv(path: Path) -> list[list[str]]:
if not path.exists():
return []
with path.open(encoding="utf-8-sig", newline="") as fh:
return [[c.strip().strip("'") for c in row] for row in csv.reader(fh) if row]
def load_elcand_dir(base: Path, office: str) -> list[CandidateEntry]:
folder = base / ELCAND_DIRS[office]
rows = _read_csv(folder / "elcand.csv")
if not rows:
return []
entries = parse_elcand(
rows, _read_csv(folder / "elbase.csv"), _read_csv(folder / "elpaty.csv"), office, CEC_2026_ELCAND.id
)
log.info("使用正式公告的 elcand 檔:%s(%d 人)", folder, len(entries))
return entries
@dataclass(frozen=True)
class CandidateLoad:
claims: tuple[PersonClaim, ...]
entries: tuple[CandidateEntry, ...]
press_release: FetchResult
elcand_offices: tuple[str, ...]
qualified_on: str | None
def fetch_candidates(raw_dir: Path) -> CandidateLoad:
result = download(CEC_ARTICLE_API, raw_dir / "cec2026" / "article_65213.json")
body, qualified_on = article_html(json.loads(result.path.read_text(encoding="utf-8")))
entries = parse_press_release(body, CEC_2026_QUALIFIED.id)
elcand_offices = []
for office in (MUNICIPAL, COUNTY):
official = load_elcand_dir(raw_dir / "cec2026", office)
if official:
elcand_offices.append(office)
entries = [e for e in entries if e.office != office] + official
claims = tuple(to_claim(e, qualified_on) for e in entries)
log.info("2026 縣市長候選人:%d 人", len(claims))
return CandidateLoad(claims, tuple(entries), result, tuple(elcand_offices), qualified_on)

View File

@ -1,110 +0,0 @@
"""人物資料用到的資料來源(不放進共用的 sources.CATALOG)。
手動維護的 YAML(黨主席、代理首長、更正)自帶來源,見 manual.py。
"""
from __future__ import annotations
from dataclasses import dataclass
from ..sources import LICENSE_OGDL, SourceRef
@dataclass(frozen=True)
class PeopleSourceSpec:
id: str
title: str
agency: str
url: str
license: str
note: str | None = None
def ref(self, retrieved_at: str, note: str | None = None) -> SourceRef:
return SourceRef(
id=self.id,
title=self.title,
agency=self.agency,
url=self.url,
license=self.license,
retrieved_at=retrieved_at,
note=note or self.note,
)
LY_TERM11 = PeopleSourceSpec(
"ly-legislators-term11",
"第11屆立法委員基本資料(開放資料 ID9)",
"立法院",
"https://data.ly.gov.tw/getds.action?id=9",
LICENSE_OGDL,
"含姓名、性別、黨籍、選區、委員會、學歷、到職與離職;離職者只用來補充其他來源已收錄的人",
)
MOI_MUNICIPAL = PeopleSourceSpec(
"moi-local-officials-municipal-mayors",
"地方公職人員資訊專區-直轄市長",
"內政部",
"https://www.moi.gov.tw/LocalOfficial.aspx?n=578&TYP=KND0004",
"內政部政府網站資料開放宣告",
"黨籍欄為該屆(111年)選舉時的黨籍,之後的變動不會反映;不含停職、代理資訊",
)
MOI_COUNTY = PeopleSourceSpec(
"moi-local-officials-county-mayors",
"地方公職人員資訊專區-縣市長",
"內政部",
"https://www.moi.gov.tw/LocalOfficial.aspx?n=579&TYP=KND0005",
"內政部政府網站資料開放宣告",
"黨籍欄為該屆(111年)選舉時的黨籍,之後的變動不會反映;不含停職、代理資訊",
)
_EY_LICENSE = "行政院網站著作權聲明(僅擷取姓名、職稱、學經歷等事實資料)"
EY_PREMIER = PeopleSourceSpec(
"ey-premier", "行政院院長", "行政院", "https://www.ey.gov.tw/Page/3C927BC7FA83C969", _EY_LICENSE
)
EY_VICE_PREMIER = PeopleSourceSpec(
"ey-vice-premier", "行政院副院長", "行政院", "https://www.ey.gov.tw/Page/4E333C98644BB79B", _EY_LICENSE
)
EY_MINISTERS_WITHOUT_PORTFOLIO = PeopleSourceSpec(
"ey-ministers-without-portfolio",
"行政院政務委員",
"行政院",
"https://www.ey.gov.tw/Page/B49E392542E2F582",
_EY_LICENSE,
)
EY_SECRETARY_SPOKESPERSON = PeopleSourceSpec(
"ey-secretary-general-spokesperson",
"行政院秘書長、發言人",
"行政院",
"https://www.ey.gov.tw/Page/AC17C70FEBCEFD1F",
_EY_LICENSE,
)
EY_AGENCY_HEADS = PeopleSourceSpec(
"ey-agency-heads",
"行政院部會首長",
"行政院",
"https://www.ey.gov.tw/Page/7AC6136EBB87A125",
_EY_LICENSE,
)
CEC_2026_QUALIFIED = PeopleSourceSpec(
"cec-2026-candidates-qualified",
"中選會審定115年直轄市長、直轄市議員、縣(市)長及縣(市)議員選舉候選人資格(新聞稿)",
"中央選舉委員會",
"https://web.cec.gov.tw/central/article/65213",
"中央選舉委員會政府網站資料開放宣告",
"115-10-16 委員會議審定的候選人名單,只有姓名與縣市;號次、政黨、性別、出生日期待正式公告"
"(直轄市長 11/12、縣市長 11/17)",
)
CEC_2026_ELCAND = PeopleSourceSpec(
"cec-2026-candidates-elcand",
"115年地方公職人員選舉候選人(elcand 格式)",
"中央選舉委員會",
"https://web.cec.gov.tw/",
"中央選舉委員會政府網站資料開放宣告",
"正式公告的候選人資料;檔案放在 data/raw/people/cec2026/ 時才會使用",
)
WIKIDATA = PeopleSourceSpec(
"wikidata",
"Wikidata(SPARQL 查詢)",
"Wikimedia Foundation",
"https://query.wikidata.org/",
"CC0 1.0",
"只在官方資料沒有時補出生日期(精確到日);QID 依姓名、台灣、職位或政黨保守比對",
)

View File

@ -18,9 +18,13 @@ from pathlib import Path
from ..cec import CecArchive
from ..codes import roc_to_iso_date
from .legislators import AT_LARGE, MOUNTAIN, PLAINS
from .names import county_key, display_name
# 中選會的選區名稱(原本在 legislators.py,人物資料庫刪除後搬來這裡)
AT_LARGE = "全國不分區及僑居國外國民"
MOUNTAIN = "山地原住民選舉區"
PLAINS = "平地原住民選舉區"
_GENDER = {"1": "M", "2": "F"}
_INDEPENDENT = frozenset({"999", "無", "無黨籍", "無黨籍及未經政黨推薦", ""})
CHIAYI_2022_DIR = "votedata/votedata/2022年_嘉義市長重行選舉/"

View File

@ -1,87 +0,0 @@
"""人物資料的下載:一般情況交給 fetch.download;少數主機需要舊式 TLS 重新協商。
data.ly.gov.tw 的伺服器要求 TLS「legacy renegotiation」,OpenSSL 3 預設拒絕
(UNSAFE_LEGACY_RENEGOTIATION_DISABLED)。只對允許清單中的主機開啟 OP_LEGACY_SERVER_CONNECT,
仍然驗證憑證鏈與主機名稱;快取檔與 .meta.json 的格式和 fetch.download 相同,
另外記錄 legacyRenegotiation=true。之後的執行直接讀快取。
"""
from __future__ import annotations
import hashlib
import json
import logging
import ssl
import time
from datetime import UTC, datetime
from pathlib import Path
from urllib.parse import urlsplit
import certifi
import httpx
from ..fetch import USER_AGENT, FetchResult, download
log = logging.getLogger(__name__)
LEGACY_RENEGOTIATION_HOSTS = frozenset({"data.ly.gov.tw"})
def _legacy_context() -> ssl.SSLContext:
ctx = ssl.create_default_context(cafile=certifi.where())
ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT
ctx.options |= getattr(ssl, "OP_LEGACY_SERVER_CONNECT", 0x4)
return ctx
def _download_legacy(url: str, dest: Path, timeout: float, retries: int) -> FetchResult:
dest.parent.mkdir(parents=True, exist_ok=True)
tmp = dest.with_name(dest.name + ".part")
last: Exception | None = None
for attempt in range(1, retries + 1):
try:
with (
httpx.Client(
verify=_legacy_context(),
timeout=timeout,
follow_redirects=True,
headers={"User-Agent": USER_AGENT},
) as client,
client.stream("GET", url) as resp,
):
resp.raise_for_status()
with tmp.open("wb") as fh:
for chunk in resp.iter_bytes(1 << 16):
fh.write(chunk)
break
except httpx.HTTPError as exc:
last = exc
log.warning("下載失敗(第 %d 次):%s:%s", attempt, url, exc)
time.sleep(2 * attempt)
else:
raise RuntimeError(f"下載失敗:{url}") from last
tmp.replace(dest)
body = dest.read_bytes()
retrieved_at = datetime.now(UTC).date().isoformat()
sha = hashlib.sha256(body).hexdigest()
meta = {
"url": url,
"retrievedAt": retrieved_at,
"sha256": sha,
"tlsVerified": True,
"legacyRenegotiation": True,
"bytes": len(body),
}
meta_file = dest.with_name(dest.name + ".meta.json")
meta_file.write_text(json.dumps(meta, ensure_ascii=False, indent=2), "utf-8")
log.info("已下載 %s(%d bytes,舊式 TLS 重新協商)", dest.name, len(body))
return FetchResult(dest, url, retrieved_at, sha, True, False)
def fetch(url: str, dest: Path, *, timeout: float = 180.0, retries: int = 3) -> FetchResult:
"""有快取就用快取;允許清單中的主機改用舊式 TLS 重新協商下載,其餘交給 fetch.download。"""
meta = dest.with_name(dest.name + ".meta.json")
host = urlsplit(url).hostname or ""
if host in LEGACY_RENEGOTIATION_HOSTS and not (dest.exists() and meta.exists()):
return _download_legacy(url, dest, timeout, retries)
return download(url, dest, timeout=timeout, retries=retries)

View File

@ -1,94 +0,0 @@
"""學歷字串解析。
官方資料的學歷是自由文字(立法院 ID9 的 degree、內政部與行政院頁面的學歷欄),格式不一。
原則:只採用字面上明確的學位;看不出學位的就標「未註明」,不推測。
"""
from __future__ import annotations
import html
import re
UNSPECIFIED = "未註明"
_SPLIT = re.compile(r"[;;\n]+")
_LIST_SPLIT = re.compile(r"[、//]")
_YEARS = re.compile(r"[((][^()()]*\d[^()()]*[))]")
_WS = re.compile(r"[\s ]+")
# 證照、考試不是學歷
_NOT_EDUCATION = re.compile(r"及格|證照|執照|執業|考試|檢定")
_SCHOOL_ONLY = re.compile(r"(國小|小學|國中|初中|高中|女中|中學|高職|商職|工職|家商|高工|高商)$")
_TRAILING_DEGREE = re.compile(
r"(?:[法文理工商醫農]學)?(?:雙)?(?:博士候選人|博士|碩士(?:在職專班|學位班|班)?|學士)(?:學位)?$"
)
_TRAILING_NOISE = re.compile(r"(?:學位|畢業|畢|結業|肄業)$")
# (判斷用的正規式, 學位名稱);依序比對,先符合者為準。學制層級的規則比對去掉「畢業」後的文字。
_RULES: tuple[tuple[re.Pattern[str], str], ...] = (
(re.compile(r"博士後"), ""), # 博士後研究不是學位,略過
(re.compile(r"博士候選人"), "博士候選人"),
(re.compile(r"博士"), "博士"),
(re.compile(r"碩士|E?MBA"), "碩士"),
(re.compile(r"學士"), "學士"),
(re.compile(r"結業$"), "結業"),
(re.compile(r"肄業$"), "肄業"),
(re.compile(r"(大學|學院).*系(畢業|畢)$"), "學士"),
)
_LEVEL_RULES: tuple[tuple[re.Pattern[str], str], ...] = (
(re.compile(r"(專科|師專|藥專|工專|商專|專校)"), "專科"),
(re.compile(r"(國小|小學)$"), "國小"),
(re.compile(r"(國中|初中|國中部)$"), "國中"),
(
re.compile(r"(高中|女中|中學|高職|商職|工職|家商|高工|高商|高中部|[一二三四]中|高級.*(中學|學校))$"),
"高中職",
),
)
def _segments(text: str) -> list[str]:
out: list[str] = []
for raw in _SPLIT.split(html.unescape(text)):
seg = _WS.sub(" ", raw).strip(" ,,。、;;")
if not seg:
continue
parts = [p.strip(" 、") for p in _LIST_SPLIT.split(seg)]
if len(parts) > 1 and all(p and _SCHOOL_ONLY.search(p) for p in parts):
out.extend(parts)
else:
out.append(seg)
return out
def classify(segment: str) -> str | None:
"""回傳學位名稱;不是學歷(或應略過)時回傳 None。"""
if _NOT_EDUCATION.search(segment):
return None
for pattern, degree in _RULES:
if pattern.search(segment):
return degree or None
core = _TRAILING_NOISE.sub("", segment).strip()
for pattern, degree in _LEVEL_RULES:
if pattern.search(core):
return degree
return UNSPECIFIED
def school_of(segment: str) -> str | None:
text = _YEARS.sub("", segment).strip()
for _ in range(2):
text = _TRAILING_NOISE.sub("", text).strip()
text = _TRAILING_DEGREE.sub("", text).strip()
return text or None
def parse_education(text: str) -> list[tuple[str, str | None]]:
"""把學歷文字拆成 (學位, 學校) 串列;重複的項目只留一次,保留原順序。"""
out: list[tuple[str, str | None]] = []
for seg in _segments(text):
degree = classify(_YEARS.sub("", seg).strip())
if degree is None:
continue
item = (degree, school_of(seg))
if item not in out:
out.append(item)
return out

View File

@ -1,162 +0,0 @@
"""把中選會選舉紀錄接到人物上。
兩層比對:
1. 強比對:同名,且選區或縣市脈絡一致(立委的選區、縣市長與候選人的縣市)。
2. 只有姓名:人物沒有對應的脈絡(例如部會首長、黨主席、總統選舉)。只有在該場選舉中同名者唯一,
且人物已知的出生日期(官方或 Wikidata)與中選會的出生日期完全相同時才接受;否則列入報告,不猜。
同一場選舉有多個可能的紀錄時一律不接,列為模稜兩可。
"""
from __future__ import annotations
from collections import defaultdict
from collections.abc import Sequence
from dataclasses import dataclass, replace
from .cec_results import CecResult
from .model import EducationRec, ElectionRec, PersonDraft, Sourced
from .names import han_key, name_key
CEC_SOURCE_ID = "cec-votedata"
_SKIP_EDUCATION = frozenset({"其他", "不識字", ""})
@dataclass(frozen=True)
class MatchNote:
name: str
kind: str # strong / name_only / unverified / ambiguous / conflict / different_birth
election: str
detail: str
def _key(name: str) -> str:
return han_key(name) or name_key(name)
def index_results(results: Sequence[CecResult]) -> dict[str, list[CecResult]]:
out: dict[str, list[CecResult]] = defaultdict(list)
for r in results:
out[_key(r.name)].append(r)
return out
def is_strong(person: PersonDraft, r: CecResult) -> bool:
if r.kind == "president":
return False
if r.district in person.districts:
return True
return r.county is not None and r.county in person.counties
def _official(value: Sourced | None) -> bool:
return value is not None and value.value is not None and value.source_ids != ("wikidata",)
def conflicts_with(person: PersonDraft, r: CecResult) -> list[str]:
"""官方資料已有的性別、出生日期與中選會紀錄不同時,回傳差異說明(不接這筆紀錄)。"""
out = []
if r.gender and person.gender and person.gender.value and person.gender.value != r.gender:
out.append(f"性別 {person.gender.value} ≠ 中選會 {r.gender}")
if r.birth_date and _official(person.birth_date) and person.birth_date.value != r.birth_date: # type: ignore[union-attr]
out.append(f"出生日期 {person.birth_date.value} ≠ 中選會 {r.birth_date}") # type: ignore[union-attr]
return out
def apply_result(person: PersonDraft, r: CecResult) -> PersonDraft:
"""接上一筆選舉紀錄;官方性別、出生日期為空時以中選會資料補上。呼叫前先檢查 conflicts_with。"""
src = (CEC_SOURCE_ID,)
label = f"{r.election}(副總統候選人)" if r.running_mate else r.election
record = ElectionRec(label, r.district, r.party, r.votes, r.share, r.elected, src)
gender = person.gender
if r.gender:
gender = gender.with_source(CEC_SOURCE_ID) if gender and gender.value else Sourced(r.gender, src)
birth = person.birth_date
if r.birth_date:
birth = birth.with_source(CEC_SOURCE_ID) if _official(birth) else Sourced(r.birth_date, src) # type: ignore[union-attr]
education = person.education
if not education and r.education and r.education not in _SKIP_EDUCATION:
education = (EducationRec(r.education, None, src),)
return replace(
person,
gender=gender,
birth_date=birth,
education=education,
elections=(*person.elections, record),
)
def _by_election(results: Sequence[CecResult]) -> dict[str, list[CecResult]]:
out: dict[str, list[CecResult]] = defaultdict(list)
for r in results:
out[r.election].append(r)
return out
def attach_strong(
persons: Sequence[PersonDraft], index: dict[str, list[CecResult]]
) -> tuple[list[PersonDraft], list[MatchNote], dict[int, set[str]]]:
"""回傳(更新後的人物, 紀錄, 每個人已比對到的選舉)。"""
out, notes = [], []
done: dict[int, set[str]] = {}
for i, person in enumerate(persons):
done[i] = set()
strong = [r for r in index.get(_key(person.name), []) if is_strong(person, r)]
for election, rs in _by_election(strong).items():
exact = [r for r in rs if r.district in person.districts]
chosen = exact if len(exact) == 1 else rs
if len(chosen) != 1:
where = "、".join(r.district for r in rs)
notes.append(MatchNote(person.name, "ambiguous", election, f"同縣市有多筆同名紀錄:{where}"))
continue
if diffs := conflicts_with(person, chosen[0]):
notes.append(MatchNote(person.name, "conflict", election, ";".join(diffs) + ",未採用"))
continue
person = apply_result(person, chosen[0])
notes.append(MatchNote(person.name, "strong", election, chosen[0].district))
done[i].add(election)
out.append(person)
return out, notes, done
def attach_name_only(
persons: Sequence[PersonDraft],
index: dict[str, list[CecResult]],
done: dict[int, set[str]],
) -> tuple[list[PersonDraft], list[MatchNote]]:
out, notes = [], []
for i, person in enumerate(persons):
for election, rs in _by_election(index.get(_key(person.name), [])).items():
if election in done.get(i, set()):
continue
birth = person.birth_date.value if person.birth_date else None
if len(rs) != 1:
notes.append(
MatchNote(person.name, "ambiguous", election, f"該場選舉有 {len(rs)} 位同名候選人")
)
continue
r = rs[0]
if birth and r.birth_date and birth == r.birth_date and not conflicts_with(person, r):
person = apply_result(person, r)
notes.append(
MatchNote(person.name, "name_only", election, f"姓名唯一且出生日期相同({birth})")
)
elif birth and r.birth_date:
notes.append(
MatchNote(
person.name,
"different_birth",
election,
f"同名但出生日期不同({birth} / {r.birth_date})",
)
)
else:
notes.append(
MatchNote(
person.name,
"unverified",
election,
f"同名({r.district}),缺出生日期無法確認,未採用",
)
)
out.append(person)
return out, notes

View File

@ -1,61 +0,0 @@
"""把 HTML 轉成逐行文字,給機關網站的簡單頁面解析用(不執行 JavaScript)。"""
from __future__ import annotations
import re
from html.parser import HTMLParser
_SKIP_TAGS = frozenset({"script", "style", "noscript", "template"})
_WS = re.compile(r"[ \t\r\f\v  ]+")
class _LineCollector(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self._chunks: list[str] = []
self._skip_depth = 0
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag in _SKIP_TAGS:
self._skip_depth += 1
self._chunks.append("\n")
def handle_endtag(self, tag: str) -> None:
if tag in _SKIP_TAGS and self._skip_depth:
self._skip_depth -= 1
self._chunks.append("\n")
def handle_data(self, data: str) -> None:
if not self._skip_depth:
self._chunks.append(data)
def lines(self) -> list[str]:
text = "".join(self._chunks)
out = []
for raw in text.split("\n"):
line = _WS.sub(" ", raw).strip()
if line:
out.append(line)
return out
def html_lines(html: str) -> list[str]:
"""去掉 script/style 後,以標籤為界切成非空白的文字行。"""
parser = _LineCollector()
parser.feed(html)
parser.close()
return parser.lines()
def section(lines: list[str], start: str, stops: tuple[str, ...]) -> list[str]:
"""取出標題 start 之後、下一個 stops 標題之前的各行(找不到 start 時回傳空串列)。"""
try:
i = lines.index(start)
except ValueError:
return []
out = []
for line in lines[i + 1 :]:
if line in stops:
break
out.append(line)
return out

View File

@ -1,126 +0,0 @@
"""現任立法委員(立法院開放資料 ID9,第 11 屆)。"""
from __future__ import annotations
import json
import logging
import re
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from ..fetch import FetchResult
from .catalog import LY_TERM11
from .downloads import fetch as download
from .education import parse_education
from .model import EducationRec, PersonClaim, PositionRec, Sourced
from .names import county_key, display_name
log = logging.getLogger(__name__)
LY_ID9_URL = "https://data.ly.gov.tw/odw/ID9Action.action?term=11&fileType=json"
TERM = 11
AT_LARGE = "全國不分區及僑居國外國民"
MOUNTAIN = "山地原住民選舉區"
PLAINS = "平地原住民選舉區"
_NUMBERED = re.compile(r"^(?P<county>.+?[縣市])第(?P<no>\d+)選舉區$")
_SINGLE = re.compile(r"^(?P<county>.+?[縣市])選舉區$")
_SESSION = re.compile(r"第\d+屆第(?P<session>\d+)會期[::](?P<committee>[^;;]+)")
_GENDER = {"男": "M", "女": "F"}
_INDEPENDENT = frozenset({"無黨籍", "無", ""})
@dataclass(frozen=True)
class District:
label: str
county: str | None
def parse_district(area_name: str) -> District:
"""立法院的選區名稱 → 正規化的選區標籤與縣市。"""
area = county_key(area_name.strip())
if area.startswith("全國不分區"):
return District(AT_LARGE, None)
if area.startswith("山地原住民"):
return District(MOUNTAIN, None)
if area.startswith("平地原住民"):
return District(PLAINS, None)
if m := _NUMBERED.match(area):
return District(f"{m['county']}第{int(m['no'])}選舉區", m["county"])
if m := _SINGLE.match(area):
return District(f"{m['county']}選舉區", m["county"])
raise ValueError(f"無法解析的立委選區:{area_name!r}")
def ly_date(value: str) -> str | None:
"""2024/02/01 → 2024-02-01。"""
m = re.fullmatch(r"\s*(\d{4})[/-](\d{1,2})[/-](\d{1,2})\s*", value or "")
return f"{int(m[1]):04d}-{int(m[2]):02d}-{int(m[3]):02d}" if m else None
def latest_session(records: Iterable[Mapping[str, Any]]) -> int:
sessions = [int(m["session"]) for r in records for m in _SESSION.finditer(r.get("committee", ""))]
return max(sessions, default=0)
def committees_in_session(committee_text: str, session: int) -> list[str]:
out: list[str] = []
for m in _SESSION.finditer(committee_text):
name = m["committee"].strip()
if int(m["session"]) == session and name and name not in out:
out.append(name)
return out
def parse_record(record: Mapping[str, Any], session: int, source_id: str) -> PersonClaim:
src = (source_id,)
district = parse_district(record["areaName"])
current = record.get("leaveFlag", "否") != "是"
start = ly_date(record.get("onboardDate", ""))
end = None if current else ly_date(record.get("leaveDate", ""))
positions = [PositionRec(f"立法委員(第{TERM}屆,{district.label})", "立法院", start, end, src)]
if current:
positions += [
PositionRec(f"{name}委員(第{TERM}屆第{session}會期)", "立法院", None, None, src)
for name in committees_in_session(record.get("committee", ""), session)
]
party_name = record.get("party", "").strip()
gender = _GENDER.get(record.get("sex", "").strip())
return PersonClaim(
name=display_name(record["name"]),
role="legislator",
category="politician",
name_source=source_id,
current=current,
county=district.county,
district=district.label,
gender=Sourced(gender, src) if gender else None,
party=Sourced(None if party_name in _INDEPENDENT else party_name, src),
positions=tuple(positions),
education=tuple(
EducationRec(degree, school, src) for degree, school in parse_education(record.get("degree", ""))
),
)
def parse_legislators(records: list[Mapping[str, Any]], source_id: str) -> list[PersonClaim]:
session = latest_session(records)
return [parse_record(r, session, source_id) for r in records]
def load_ly_json(path: Path) -> list[dict[str, Any]]:
# 立法院 API 回應前面有空白行
data = json.loads(path.read_text(encoding="utf-8").strip())
records = data.get("dataList")
if not isinstance(records, list) or not records:
raise ValueError(f"立法院 ID9 回應沒有 dataList:{path}")
return records
def fetch_legislators(raw_dir: Path) -> tuple[list[PersonClaim], FetchResult]:
result = download(LY_ID9_URL, raw_dir / "ly" / f"id9_term{TERM}.json")
claims = parse_legislators(load_ly_json(result.path), LY_TERM11.id)
log.info("立法委員:%d 筆(現任 %d)", len(claims), sum(c.current for c in claims))
return claims, result

View File

@ -1,198 +0,0 @@
"""手動維護的人物資料(config/people/*.yaml):黨主席、代理首長、欄位更正。"""
from __future__ import annotations
import re
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import yaml
from ..sources import SourceRef
from .education import parse_education
from .model import EducationRec, PersonClaim, PositionRec, Sourced
from .names import county_key, display_name
_ISO = re.compile(r"^\d{4}-\d{2}-\d{2}$")
_SUPPORTED_OVERRIDES = frozenset({"party"})
class ManualDataError(ValueError):
pass
@dataclass(frozen=True)
class Override:
name: str
field: str
value: str | None
note: str
source_ids: tuple[str, ...]
@dataclass(frozen=True)
class ManualData:
claims: tuple[PersonClaim, ...]
overrides: tuple[Override, ...]
sources: tuple[SourceRef, ...]
def _require(entry: Mapping[str, Any], key: str, where: str) -> Any:
value = entry.get(key)
if value in (None, "", []):
raise ManualDataError(f"{where}:缺少必填欄位 {key}")
return value
def _date(value: Any, where: str) -> str | None:
if value is None:
return None
text = str(value)
if not _ISO.match(text):
raise ManualDataError(f"{where}:日期格式應為 YYYY-MM-DD,實際為 {value!r}")
return text
def parse_sources(entries: list[Mapping[str, Any]], where: str) -> list[SourceRef]:
refs = []
for i, src in enumerate(entries or []):
at = f"{where}.sources[{i}]"
url = str(_require(src, "url", at))
if not url.startswith("https://"):
raise ManualDataError(f"{at}:網址必須是 https:{url}")
note_parts = [str(src["note"])] if src.get("note") else []
if src.get("quote"):
note_parts.append(f"確認文字:{src['quote']}")
refs.append(
SourceRef(
id=str(_require(src, "id", at)),
title=str(_require(src, "title", at)),
agency=str(_require(src, "agency", at)),
url=url,
license=str(_require(src, "license", at)),
retrieved_at=_date(_require(src, "retrievedAt", at), at) or "",
note=";".join(note_parts) or None,
)
)
if not refs:
raise ManualDataError(f"{where}:至少要有一個 sources")
return refs
def _positions(entries: list[Mapping[str, Any]], src: tuple[str, ...], where: str) -> tuple[PositionRec, ...]:
out = []
for i, pos in enumerate(entries):
at = f"{where}.positions[{i}]"
out.append(
PositionRec(
str(_require(pos, "title", at)),
str(_require(pos, "org", at)),
_date(pos.get("from"), at),
_date(pos.get("to"), at),
src,
)
)
return tuple(out)
def _education(lines: list[str], src: tuple[str, ...]) -> tuple[EducationRec, ...]:
return tuple(EducationRec(d, s, src) for line in lines for d, s in parse_education(str(line)))
def parse_party_chairs(doc: Mapping[str, Any]) -> tuple[list[PersonClaim], list[SourceRef]]:
claims, refs = [], []
for i, entry in enumerate(doc.get("chairs") or []):
where = f"party_chairs.yaml chairs[{i}]"
sources = parse_sources(entry.get("sources"), where)
src = tuple(s.id for s in sources)
party = str(_require(entry, "party", where))
title = str(entry.get("title") or "黨主席")
claims.append(
PersonClaim(
name=display_name(str(_require(entry, "name", where))),
role="party_chair",
category="politician",
name_source=src[0],
party=Sourced(party, src),
positions=(PositionRec(title, party, _date(entry.get("from"), where), None, src),),
)
)
refs.extend(sources)
return claims, refs
def parse_acting_heads(doc: Mapping[str, Any]) -> tuple[list[PersonClaim], list[SourceRef]]:
claims, refs = [], []
for i, entry in enumerate(doc.get("acting") or []):
where = f"acting_heads.yaml acting[{i}]"
sources = parse_sources(entry.get("sources"), where)
src = tuple(s.id for s in sources)
category = str(entry.get("category") or "official")
if category not in ("politician", "official"):
raise ManualDataError(f"{where}:category 只能是 politician 或 official")
claims.append(
PersonClaim(
name=display_name(str(_require(entry, "name", where))),
role="acting_head",
category=category, # type: ignore[arg-type]
name_source=src[0],
county=county_key(str(entry["county"])) if entry.get("county") else None,
positions=_positions(_require(entry, "positions", where), src, where),
education=_education(entry.get("education") or [], src),
)
)
refs.extend(sources)
return claims, refs
def parse_overrides(doc: Mapping[str, Any]) -> tuple[list[Override], list[SourceRef]]:
out, refs = [], []
for i, entry in enumerate(doc.get("overrides") or []):
where = f"overrides.yaml overrides[{i}]"
field = str(_require(entry, "field", where))
if field not in _SUPPORTED_OVERRIDES:
raise ManualDataError(f"{where}:不支援的欄位 {field}")
sources = parse_sources(entry.get("sources"), where)
value = entry.get("value")
out.append(
Override(
name=display_name(str(_require(entry, "name", where))),
field=field,
value=None if value is None else str(value),
note=str(entry.get("note") or ""),
source_ids=tuple(s.id for s in sources),
)
)
refs.extend(sources)
return out, refs
def _load(path: Path) -> Mapping[str, Any]:
if not path.exists():
return {}
doc = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
if not isinstance(doc, Mapping):
raise ManualDataError(f"{path} 的最上層應該是物件")
return doc
def _dedupe_sources(refs: list[SourceRef]) -> tuple[SourceRef, ...]:
seen: dict[str, SourceRef] = {}
for ref in refs:
if ref.id in seen and seen[ref.id] != ref:
raise ManualDataError(f"來源 id {ref.id} 重複且內容不同")
seen[ref.id] = ref
return tuple(seen.values())
def load_manual(config_dir: Path) -> ManualData:
chairs, chair_refs = parse_party_chairs(_load(config_dir / "party_chairs.yaml"))
acting, acting_refs = parse_acting_heads(_load(config_dir / "acting_heads.yaml"))
overrides, override_refs = parse_overrides(_load(config_dir / "overrides.yaml"))
return ManualData(
claims=tuple(chairs + acting),
overrides=tuple(overrides),
sources=_dedupe_sources(chair_refs + acting_refs + override_refs),
)

View File

@ -1,142 +0,0 @@
"""現任直轄市長、縣市長(內政部地方公職人員資訊專區)。
清單頁的每一筆有姓名、縣市、機關、職稱、黨籍與詳細資訊連結;詳細頁另有學歷與簡歷。
該專區的「轉出 ODS」是 ASP.NET 表單按鈕,清單頁本身已含完整資料,所以直接解析 HTML。
"""
from __future__ import annotations
import html
import logging
import re
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import parse_qs, urljoin, urlsplit
from ..fetch import FetchResult
from .catalog import MOI_COUNTY, MOI_MUNICIPAL, PeopleSourceSpec
from .downloads import fetch as download
from .education import parse_education
from .htmltext import html_lines, section
from .model import EducationRec, PersonClaim, PositionRec, Sourced
from .names import county_key, display_name
log = logging.getLogger(__name__)
MOI_BASE = "https://www.moi.gov.tw/"
LISTS: tuple[tuple[PeopleSourceSpec, str, int], ...] = (
(MOI_MUNICIPAL, "LocalOfficial.aspx?n=578&TYP=KND0004&PageSize=50", 6),
(MOI_COUNTY, "LocalOfficial.aspx?n=579&TYP=KND0005&PageSize=50", 16),
)
_BLOCK = re.compile(
r'<div class="caption">\s*<span>(?P<name>.*?)</span>.*?'
r'<div class="locate">\s*<span>(?P<county>.*?)</span>.*?'
r'<div class="position">(?P<position>.*?)</div>.*?'
r'<div class="group">\s*<span>(?P<party>.*?)</span>.*?'
r'<div class="more-btn">.*?href="(?P<href>[^"]+)"',
re.S,
)
_SPAN = re.compile(r"<span>(.*?)</span>", re.S)
_DETAIL_STOPS = ("黨籍", "選舉屆次", "學歷", "簡歷", "辦公地址", "聯絡電話(辦公)", "電子信箱")
_INDEPENDENT = frozenset({"無", "無黨籍", ""})
@dataclass(frozen=True)
class MoiEntry:
name: str
county: str
org: str
title: str
party: str | None
detail_url: str
@dataclass(frozen=True)
class MoiDetail:
party: str | None
term: str | None
education: tuple[str, ...]
def _text(fragment: str) -> str:
return html.unescape(re.sub(r"<[^>]+>", "", fragment)).strip()
def parse_list(page: str) -> list[MoiEntry]:
entries = []
for m in _BLOCK.finditer(page):
spans = [_text(s) for s in _SPAN.findall(m["position"])]
if len(spans) < 2:
raise ValueError(f"內政部清單的職稱欄位格式不符:{m['position']!r}")
party = _text(m["party"])
entries.append(
MoiEntry(
name=display_name(_text(m["name"])),
county=county_key(_text(m["county"])),
org=spans[0],
title=spans[1],
party=None if party in _INDEPENDENT else party,
detail_url=urljoin(MOI_BASE, html.unescape(m["href"])),
)
)
return entries
def parse_detail(page: str) -> MoiDetail:
lines = html_lines(page)
party = section(lines, "黨籍", _DETAIL_STOPS)
term = section(lines, "選舉屆次", _DETAIL_STOPS)
education = section(lines, "學歷", _DETAIL_STOPS)
party_value = party[0] if party else None
return MoiDetail(
party=None if party_value in _INDEPENDENT else party_value,
term=term[0] if term else None,
education=tuple(education),
)
def to_claim(entry: MoiEntry, detail: MoiDetail | None, source_id: str) -> PersonClaim:
src = (source_id,)
education: list[EducationRec] = []
for line in detail.education if detail else ():
for degree, school in parse_education(line):
rec = EducationRec(degree, school, src)
if rec not in education:
education.append(rec)
return PersonClaim(
name=entry.name,
role="mayor",
category="politician",
name_source=source_id,
county=entry.county,
party=Sourced(entry.party, src),
positions=(PositionRec(entry.title, entry.org, None, None, src),),
education=tuple(education),
)
def _detail_dest(raw_dir: Path, url: str) -> Path:
parent = parse_qs(urlsplit(url).query).get("_PARENT_ID", ["unknown"])[0]
return raw_dir / "moi" / f"detail_{re.sub(r'[^A-Za-z0-9]', '', parent)}.html"
def fetch_mayors(raw_dir: Path) -> tuple[list[PersonClaim], dict[str, FetchResult]]:
claims: list[PersonClaim] = []
results: dict[str, FetchResult] = {}
for spec, path, expected in LISTS:
url = urljoin(MOI_BASE, path)
listing = download(url, raw_dir / "moi" / f"{path.split('TYP=')[1].split('&')[0]}.html")
results[spec.id] = listing
entries = parse_list(listing.path.read_text(encoding="utf-8"))
if len(entries) != expected:
log.warning("%s:預期 %d 筆,實際 %d 筆", spec.title, expected, len(entries))
if not entries:
raise ValueError(f"{spec.title} 清單解析不到任何人:{url}")
for entry in entries:
detail_file = download(entry.detail_url, _detail_dest(raw_dir, entry.detail_url))
detail = parse_detail(detail_file.path.read_text(encoding="utf-8"))
if detail.party != entry.party:
log.warning("%s 的黨籍在清單與詳細頁不一致:%s / %s", entry.name, entry.party, detail.party)
claims.append(to_claim(entry, detail, spec.id))
log.info("縣市首長:%d 人", len(claims))
return claims, results

View File

@ -1,188 +0,0 @@
"""把各來源的 PersonClaim 合併成人物。
同名才可能是同一人;同名但縣市脈絡衝突(例如兩個不同縣市的候選人)、或同一種現任職位出現兩次時,
不合併並記錄下來。已離職的立委只用來補充其他來源已收錄的同名人物(例如轉任部長、擔任黨主席)。
"""
from __future__ import annotations
from collections.abc import Iterable, Sequence
from dataclasses import dataclass, replace
from .manual import Override
from .model import EducationRec, PersonClaim, PersonDraft, PositionRec, Sourced
from .names import han_key, name_key
# 合併時的優先順序:顯示姓名、黨籍以排在前面的來源為準
ROLE_ORDER: tuple[str, ...] = (
"legislator",
"mayor",
"acting_head",
"party_chair",
"official",
"candidate_2026",
)
# 這些現任職位同一人不會有兩個
_EXCLUSIVE_ROLES = frozenset({"legislator", "mayor", "candidate_2026"})
@dataclass(frozen=True)
class MergeNote:
name: str
kind: str # merged / not_merged / departed_attached / departed_dropped / override / override_missing
detail: str
def _role_rank(claim: PersonClaim) -> int:
return ROLE_ORDER.index(claim.role) if claim.role in ROLE_ORDER else len(ROLE_ORDER)
def _key(claim_name: str) -> str:
return han_key(claim_name) or name_key(claim_name)
def compatible(cluster: Sequence[PersonClaim], claim: PersonClaim) -> bool:
counties = {c.county for c in cluster if c.county}
if claim.county and counties and claim.county not in counties:
return False
roles = {c.role for c in cluster if c.current}
return not (claim.current and claim.role in _EXCLUSIVE_ROLES and claim.role in roles)
def _cluster(claims: Iterable[PersonClaim]) -> tuple[list[list[PersonClaim]], list[MergeNote]]:
clusters: list[list[PersonClaim]] = []
notes: list[MergeNote] = []
current = sorted((c for c in claims if c.current), key=_role_rank)
departed = [c for c in claims if not c.current]
by_key: dict[str, list[list[PersonClaim]]] = {}
for claim in current:
groups = by_key.setdefault(_key(claim.name), [])
fits = [g for g in groups if compatible(g, claim)]
if len(fits) == 1:
fits[0].append(claim)
continue
if groups:
reason = "多個同名人物都可能是同一人" if fits else "同名但縣市或現任職位衝突"
notes.append(
MergeNote(claim.name, "not_merged", f"{claim.role}({claim.county or '-'}):{reason}")
)
group = [claim]
groups.append(group)
clusters.append(group)
for claim in departed:
groups = by_key.get(_key(claim.name), [])
fits = [g for g in groups if compatible(g, claim)]
if len(fits) == 1:
fits[0].append(claim)
roles = "、".join(sorted({c.role for c in fits[0] if c is not claim}))
notes.append(MergeNote(claim.name, "departed_attached", f"已離職立委,併入現任的{roles}"))
else:
notes.append(MergeNote(claim.name, "departed_dropped", "已離職立委,且沒有其他現任職位,未收錄"))
for group in clusters:
roles = sorted({c.role for c in group if c.current})
if len(roles) > 1:
notes.append(MergeNote(group[0].name, "merged", "+".join(roles)))
return clusters, notes
def _first(values: Iterable[Sourced | None]) -> tuple[Sourced | None, list[Sourced]]:
present = [v for v in values if v is not None]
if not present:
return None, []
chosen = present[0]
conflicts = []
for other in present[1:]:
if other.value == chosen.value:
for sid in other.source_ids:
chosen = chosen.with_source(sid)
else:
conflicts.append(other)
return chosen, conflicts
def _merge_education(items: Iterable[EducationRec]) -> tuple[EducationRec, ...]:
out: dict[tuple[str, str | None], EducationRec] = {}
for item in items:
key = (item.degree, item.school)
if key in out:
merged = tuple(dict.fromkeys(out[key].source_ids + item.source_ids))
out[key] = replace(out[key], source_ids=merged)
else:
out[key] = item
return tuple(out.values())
def _merge_positions(items: Iterable[PositionRec]) -> tuple[PositionRec, ...]:
return tuple(dict.fromkeys(items))
def _describe(value: Sourced | None) -> str:
if value is None:
return "None"
return f"{value.value}({','.join(value.source_ids)})"
def build_draft(group: Sequence[PersonClaim]) -> tuple[PersonDraft, list[MergeNote]]:
ordered = sorted(group, key=lambda c: (not c.current, _role_rank(c)))
head = ordered[0]
notes = []
gender, g_conf = _first(c.gender for c in ordered)
birth, b_conf = _first(c.birth_date for c in ordered)
party, p_conf = _first(c.party for c in ordered if c.current)
for label, conflicts, chosen in (
("性別", g_conf, gender),
("出生日期", b_conf, birth),
("黨籍", p_conf, party),
):
for other in conflicts:
notes.append(
MergeNote(
head.name,
"conflict",
f"{label}不一致:採用 {_describe(chosen)},另有 {_describe(other)}",
)
)
draft = PersonDraft(
name=head.name,
category="politician" if any(c.category == "politician" for c in group) else "official",
roles=frozenset(c.role for c in group if c.current),
name_sources=tuple(dict.fromkeys(c.name_source for c in ordered)),
counties=frozenset(c.county for c in group if c.county),
districts=frozenset(c.district for c in group if c.district),
gender=gender,
birth_date=birth,
party=party,
positions=_merge_positions(p for c in ordered for p in c.positions),
education=_merge_education(e for c in ordered for e in c.education),
elections=tuple(e for c in ordered for e in c.elections),
)
return draft, notes
def merge_claims(claims: Iterable[PersonClaim]) -> tuple[list[PersonDraft], list[MergeNote]]:
clusters, notes = _cluster(list(claims))
drafts = []
for group in clusters:
draft, extra = build_draft(group)
drafts.append(draft)
notes.extend(extra)
return drafts, notes
def apply_overrides(
drafts: Sequence[PersonDraft], overrides: Iterable[Override]
) -> tuple[list[PersonDraft], list[MergeNote]]:
out = list(drafts)
notes = []
for ov in overrides:
hits = [i for i, d in enumerate(out) if _key(d.name) == _key(ov.name)]
if len(hits) != 1:
notes.append(
MergeNote(ov.name, "override_missing", f"找到 {len(hits)} 位同名人物,未套用 {ov.field} 更正")
)
continue
i = hits[0]
before = out[i].party.value if out[i].party else None
out[i] = replace(out[i], party=Sourced(ov.value, ov.source_ids), notes=(*out[i].notes, ov.note))
notes.append(MergeNote(ov.name, "override", f"黨籍 {before} → {ov.value}:{ov.note}"))
return out, notes

View File

@ -1,111 +0,0 @@
"""人物資料的中間紀錄(不可變)。輸出格式對應 packages/protocol/src/people.ts。"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Literal
Category = Literal["politician", "official"]
Gender = Literal["M", "F"]
@dataclass(frozen=True)
class Sourced:
"""附出處的純量值。value 為 None 但有出處時,代表「已查證為無」(例如無黨籍)。"""
value: str | None
source_ids: tuple[str, ...]
def with_source(self, source_id: str) -> Sourced:
if source_id in self.source_ids:
return self
return Sourced(self.value, (*self.source_ids, source_id))
@dataclass(frozen=True)
class PositionRec:
title: str
org: str
start: str | None
end: str | None
source_ids: tuple[str, ...]
def to_json(self) -> dict[str, Any]:
return {
"title": self.title,
"org": self.org,
"from": self.start,
"to": self.end,
"sourceIds": list(self.source_ids),
}
@dataclass(frozen=True)
class EducationRec:
degree: str
school: str | None
source_ids: tuple[str, ...]
def to_json(self) -> dict[str, Any]:
return {"degree": self.degree, "school": self.school, "sourceIds": list(self.source_ids)}
@dataclass(frozen=True)
class ElectionRec:
election: str
district: str | None
party: str | None
votes: int | None
share: float | None
elected: bool
source_ids: tuple[str, ...]
def to_json(self) -> dict[str, Any]:
return {
"election": self.election,
"district": self.district,
"party": self.party,
"votes": self.votes,
"share": self.share,
"elected": self.elected,
"sourceIds": list(self.source_ids),
}
@dataclass(frozen=True)
class PersonClaim:
"""單一來源對某個人的描述;合併後才成為一個人物。"""
name: str
role: str # legislator / mayor / official / party_chair / candidate_2026 / acting_head
category: Category
name_source: str
current: bool = True # False:已離職的立委,只用來補充其他來源已收錄的人
county: str | None = None # 比對選舉紀錄用的縣市脈絡
district: str | None = None # 立委選區,例如「臺北市第1選舉區」「山地原住民」「全國不分區」
gender: Sourced | None = None
birth_date: Sourced | None = None
party: Sourced | None = None
positions: tuple[PositionRec, ...] = ()
education: tuple[EducationRec, ...] = ()
elections: tuple[ElectionRec, ...] = ()
@dataclass(frozen=True)
class PersonDraft:
"""合併後、輸出前的人物。"""
name: str
category: Category
roles: frozenset[str]
name_sources: tuple[str, ...]
counties: frozenset[str] = frozenset()
districts: frozenset[str] = frozenset()
gender: Sourced | None = None
birth_date: Sourced | None = None
party: Sourced | None = None
wikidata_id: Sourced | None = None
positions: tuple[PositionRec, ...] = ()
education: tuple[EducationRec, ...] = ()
elections: tuple[ElectionRec, ...] = ()
notes: tuple[str, ...] = field(default=())

View File

@ -1,116 +0,0 @@
"""PersonDraft → people.json 的 Person(packages/protocol/src/people.ts)。"""
from __future__ import annotations
from collections import defaultdict
from collections.abc import Sequence
from typing import Any
from .model import PersonDraft, Sourced
from .names import name_key, slug_name
STAT_KEYS: tuple[str, ...] = (
"awareness",
"network",
"affinity",
"eloquence",
"strategy",
"online",
"image",
"wealth",
"stamina",
)
def slug_id(p: PersonDraft) -> str:
year = p.birth_date.value[:4] if p.birth_date and p.birth_date.value else "x"
return f"tw-{p.category}-{slug_name(p.name)}-{year}"
def _sort_key(p: PersonDraft) -> tuple[str, ...]:
"""同 id 的人物排序(決定 -2、-3 的歸屬),只用資料內容,不受輸入順序影響。"""
return (
name_key(p.name),
p.birth_date.value or "" if p.birth_date else "",
p.name,
",".join(sorted(p.roles)),
",".join(sorted(p.counties)),
",".join(sorted(p.districts)),
",".join(f"{x.org}/{x.title}" for x in p.positions),
)
def assign_ids(persons: Sequence[PersonDraft]) -> list[str]:
"""有 Wikidata QID 就用 QID;否則用 tw-<類別>-<姓名>-<出生年或 x>。同 id 依固定排序加上 -2、-3。"""
base = [p.wikidata_id.value if p.wikidata_id and p.wikidata_id.value else slug_id(p) for p in persons]
groups: dict[str, list[int]] = defaultdict(list)
for i, b in enumerate(base):
groups[b].append(i)
ids = list(base)
for b, idx in groups.items():
if len(idx) > 1:
for n, i in enumerate(sorted(idx, key=lambda k: _sort_key(persons[k]))):
ids[i] = b if n == 0 else f"{b}-{n + 1}"
if len(set(ids)) != len(ids):
raise ValueError("人物 id 不唯一")
return ids
def _field_sources(p: PersonDraft) -> dict[str, list[str]]:
out: dict[str, list[str]] = {"name": list(p.name_sources)}
scalars: dict[str, Sourced | None] = {
"gender": p.gender,
"birthDate": p.birth_date,
"party": p.party,
"wikidataId": p.wikidata_id,
}
for field, value in scalars.items():
if value is not None and (value.value is not None or field == "party"):
out[field] = list(value.source_ids)
return out
def _value(v: Sourced | None) -> str | None:
return v.value if v else None
def person_json(p: PersonDraft, person_id: str, as_of: str) -> dict[str, Any]:
return {
"id": person_id,
"kind": "real",
"category": p.category,
"name": p.name,
"gender": _value(p.gender),
"birthDate": _value(p.birth_date),
"party": _value(p.party),
"wikidataId": _value(p.wikidata_id),
"positions": [x.to_json() for x in p.positions],
"education": [x.to_json() for x in p.education],
"electionHistory": [x.to_json() for x in p.elections],
"stats": dict.fromkeys(STAT_KEYS),
"scoring": [],
"fieldSources": _field_sources(p),
"asOf": as_of,
}
def people_file(
persons: Sequence[PersonDraft], ids: Sequence[str], protocol_version: str, as_of: str
) -> dict[str, Any]:
rows = sorted(zip(ids, persons, strict=True), key=lambda t: (t[1].category, name_key(t[1].name), t[0]))
return {
"protocolVersion": protocol_version,
"asOf": as_of,
"people": [person_json(p, pid, as_of) for pid, p in rows],
}
def referenced_source_ids(doc: dict[str, Any]) -> set[str]:
out: set[str] = set()
for person in doc["people"]:
for ids in person["fieldSources"].values():
out.update(ids)
for key in ("positions", "education", "electionHistory"):
for item in person[key]:
out.update(item["sourceIds"])
return out

View File

@ -1,166 +0,0 @@
"""data/build/people/report.md:覆蓋率、比對結果、待確認事項。"""
from __future__ import annotations
from collections import Counter
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from typing import Any
from .enrich import MatchNote
from .merge import MergeNote
from .wd_match import WdNote
ROLE_LABELS = {
"legislator": "現任立法委員",
"mayor": "直轄市長、縣市長(內政部專區)",
"acting_head": "代理縣市長",
"official": "行政院內閣",
"party_chair": "政黨主席",
"candidate_2026": "2026 縣市長候選人",
}
@dataclass(frozen=True)
class ReportInput:
as_of: str
doc: dict[str, Any]
roles_by_id: dict[str, frozenset[str]]
merge_notes: Sequence[MergeNote]
match_notes: Sequence[MatchNote]
wd_notes: Sequence[WdNote]
candidate_status: Sequence[str]
known_gaps: Sequence[str]
_NAME_DETAIL = "- {n.name}:{n.detail}"
_MATCH_DETAIL = "- {n.name}|{n.election}|{n.kind}|{n.detail}"
def _pct(n: int, total: int) -> str:
return f"{n}/{total}({n / total:.0%})" if total else "0/0"
def _table(header: Sequence[str], rows: Iterable[Sequence[Any]]) -> list[str]:
lines = ["| " + " | ".join(header) + " |", "|" + "---|" * len(header)]
lines += ["| " + " | ".join(str(c) for c in row) + " |" for row in rows]
return lines
def _counts(inp: ReportInput) -> list[str]:
people = inp.doc["people"]
by_cat = Counter(p["category"] for p in people)
by_role = Counter(r for roles in inp.roles_by_id.values() for r in roles)
multi = sum(1 for roles in inp.roles_by_id.values() if len(roles) > 1)
cats = f"politician {by_cat['politician']}、official {by_cat['official']}"
out = [f"- 人物總數:**{len(people)}**({cats})"]
out += [f"- 同時具有多種身分(已合併):{multi} 人", ""]
out += _table(("身分", "人數"), ((ROLE_LABELS.get(k, k), v) for k, v in sorted(by_role.items())))
return out
def _coverage(inp: ReportInput) -> list[str]:
people = inp.doc["people"]
n = len(people)
def has(field: str, src: str | None = None) -> int:
return sum(
1
for p in people
if p[field] is not None and (src is None or src in p["fieldSources"].get(field, []))
)
wd_birth = sum(1 for p in people if p["fieldSources"].get("birthDate") == ["wikidata"])
party_known = sum(1 for p in people if "party" in p["fieldSources"])
rows = [
("性別(官方)", _pct(has("gender"), n)),
("出生日期(全部)", _pct(has("birthDate"), n)),
(" 其中官方(中選會)", _pct(has("birthDate") - wd_birth, n)),
(" 其中只來自 Wikidata", _pct(wd_birth, n)),
("黨籍已查證(含無黨籍)", _pct(party_known, n)),
("Wikidata QID", _pct(has("wikidataId"), n)),
("學歷(至少一筆)", _pct(sum(1 for p in people if p["education"]), n)),
("選舉紀錄(至少一筆)", _pct(sum(1 for p in people if p["electionHistory"]), n)),
]
return _table(("欄位", "覆蓋"), rows)
def _note_lines(notes: Iterable[Any], kinds: set[str], fmt: str) -> list[str]:
lines = [fmt.format(n=n) for n in notes if n.kind in kinds]
return lines or ["- (無)"]
def render_report(inp: ReportInput) -> str:
match_counts = Counter(n.kind for n in inp.match_notes)
wd_counts = Counter(n.kind for n in inp.wd_notes)
parts: list[str] = [
"# 人物資料庫 M0 報告",
"",
f"資料快照日期:{inp.as_of} | 產生程式:`python -m election_data.people`",
"",
"## 人數",
"",
*_counts(inp),
"",
"## 欄位覆蓋率",
"",
*_coverage(inp),
"",
"## 2026 縣市長候選人",
"",
*[f"- {line}" for line in inp.candidate_status],
"",
"## 跨來源合併",
"",
"同名且縣市脈絡不衝突時合併為同一人。請人工確認下列合併:",
"",
*_note_lines(inp.merge_notes, {"merged", "departed_attached"}, "- {n.name}:{n.detail}"),
"",
"未合併或未收錄:",
"",
*_note_lines(inp.merge_notes, {"not_merged", "departed_dropped", "override_missing"}, _NAME_DETAIL),
"",
"黨籍更正(config/people/overrides.yaml)與來源間不一致:",
"",
*_note_lines(inp.merge_notes, {"override", "conflict"}, "- {n.name}:{n.detail}"),
"",
"## 選舉紀錄比對(中選會)",
"",
f"- 強比對(同名+選區或縣市):{match_counts['strong']} 筆",
f"- 只有姓名、以出生日期確認:{match_counts['name_only']} 筆",
f"- 同名但出生日期不同(判定為不同人):{match_counts['different_birth']} 筆",
"",
"以出生日期確認的比對:",
"",
*_note_lines(inp.match_notes, {"name_only"}, "- {n.name}|{n.election}|{n.detail}"),
"",
"模稜兩可、無法確認、資料衝突或同名不同人(未採用,請人工複查):",
"",
*_note_lines(
inp.match_notes, {"ambiguous", "unverified", "conflict", "different_birth"}, _MATCH_DETAIL
),
"",
"## Wikidata 比對",
"",
f"- 符合:{wd_counts['matched']};較弱規則符合(medium):{wd_counts['matched_medium']};"
f"模稜兩可:{wd_counts['ambiguous']};未找到:{wd_counts['unmatched']};"
f"QID 重複:{wd_counts['duplicate_qid']}",
"",
"medium(同名臺灣人唯一且有政府職位,請人工複查):",
"",
*_note_lines(inp.wd_notes, {"matched_medium"}, "- {n.name} → {n.qid}:{n.detail}"),
"",
"模稜兩可或 QID 重複(未採用):",
"",
*_note_lines(inp.wd_notes, {"ambiguous", "duplicate_qid"}, "- {n.name}:{n.detail}"),
"",
"未找到(wikidataId 為 null):",
"",
*_note_lines(inp.wd_notes, {"unmatched"}, "- {n.name}:{n.detail}"),
"",
"## 已知缺口與注意事項",
"",
*[f"- {gap}" for gap in inp.known_gaps],
"",
]
return "\n".join(parts)

View File

@ -1,147 +0,0 @@
"""人物與 Wikidata 項目的保守比對。
接受一個 Wikidata 項目的條件(全部都要符合):
- 標籤或別名與姓名相同;
- 若人物已有官方出生日期,項目的出生日期(精確到日)不得不同;
- 至少一項證據:職位標籤含人物職位的關鍵字(例如「立法委員」、縣市名、部會名)、政黨相同、
或出生日期相同(只有出生日期相同時,項目還要標示國籍為臺灣 Q865)。
符合的項目超過一個就視為模稜兩可,不採用。
部會首長沒有黨籍也常缺職位資料,另有一條較弱的規則(記為 medium):同名且國籍為臺灣的項目只有一個,
而且該項目有政府職位。報告會列出所有 medium 比對,方便人工複查。
"""
from __future__ import annotations
from collections import Counter, defaultdict
from collections.abc import Sequence
from dataclasses import dataclass, replace
from .model import PersonDraft, Sourced
from .names import county_key, han_key, name_key
from .wikidata import WdItem
WIKIDATA_SOURCE_ID = "wikidata"
TAIWAN = "Q865"
_OFFICE_WORDS = (
"部長",
"委員",
"院長",
"署長",
"局長",
"主計長",
"人事長",
"總裁",
"秘書長",
"發言人",
"市長",
"縣長",
)
@dataclass(frozen=True)
class WdNote:
name: str
kind: str # matched / matched_medium / ambiguous / unmatched / duplicate_qid
qid: str | None
detail: str
def _norm(text: str) -> str:
return county_key(text)
def evidence_terms(p: PersonDraft) -> frozenset[str]:
terms: set[str] = set()
if "legislator" in p.roles or p.districts:
terms.add("立法委員")
terms.update(_norm(c) for c in p.counties)
for pos in p.positions:
org = _norm(pos.org)
if org == "行政院":
terms.add("政務委員" if pos.title == "政務委員" else f"行政院{pos.title}")
elif "official" in p.roles and not org.startswith(("立法院", "115年")):
terms.add(org)
return frozenset(terms)
def _official_birth(p: PersonDraft) -> str | None:
if p.birth_date and p.birth_date.value and p.birth_date.source_ids != (WIKIDATA_SOURCE_ID,):
return p.birth_date.value
return None
def _evidence(p: PersonDraft, item: WdItem, terms: frozenset[str]) -> list[str]:
reasons = []
labels = [_norm(x) for x in item.positions]
hits = sorted({t for t in terms for label in labels if t in label})
if hits:
reasons.append("職位:" + "/".join(hits))
if p.party and p.party.value and _norm(p.party.value) in {_norm(x) for x in item.parties}:
reasons.append("政黨:" + p.party.value)
birth = _official_birth(p)
if birth and birth in item.day_births() and (reasons or TAIWAN in item.countries):
reasons.append("出生日期:" + birth)
return reasons
def candidates_for(p: PersonDraft, by_key: dict[str, list[WdItem]]) -> list[WdItem]:
keys = {name_key(p.name), han_key(p.name)} - {""}
seen: dict[str, WdItem] = {}
for k in keys:
for item in by_key.get(k, []):
seen[item.qid] = item
return list(seen.values())
def match_one(p: PersonDraft, items: Sequence[WdItem]) -> WdNote:
birth = _official_birth(p)
terms = evidence_terms(p)
allowed = [it for it in items if not (birth and it.day_births() and birth not in it.day_births())]
scored = [(it, r) for it in allowed if (r := _evidence(p, it, terms))]
if len(scored) > 1:
with_birth = [(it, r) for it, r in scored if any(x.startswith("出生日期") for x in r)]
scored = with_birth if len(with_birth) == 1 else scored
if len(scored) == 1:
item, reasons = scored[0]
return WdNote(p.name, "matched", item.qid, "、".join(reasons))
if len(scored) > 1:
return WdNote(p.name, "ambiguous", None, "多個符合:" + "、".join(it.qid for it, _ in scored))
if p.category == "official" and p.roles <= {"official", "acting_head"}:
taiwanese = [it for it in allowed if TAIWAN in it.countries]
if len(taiwanese) == 1 and any(w in pos for pos in taiwanese[0].positions for w in _OFFICE_WORDS):
item = taiwanese[0]
return WdNote(
p.name,
"matched_medium",
item.qid,
"同名臺灣人唯一且有政府職位:" + "/".join(item.positions[:3]),
)
detail = f"{len(items)} 個同名項目" if items else "查無同名項目"
if len(items) != len(allowed):
detail += f"({len(items) - len(allowed)} 個出生日期不符)"
return WdNote(p.name, "unmatched", None, detail)
def match_wikidata(
persons: Sequence[PersonDraft], items: Sequence[WdItem]
) -> tuple[list[PersonDraft], list[WdNote]]:
by_key: dict[str, list[WdItem]] = defaultdict(list)
for item in items:
for k in item.label_keys:
by_key[k].append(item)
notes = [match_one(p, candidates_for(p, by_key)) for p in persons]
counts = Counter(n.qid for n in notes if n.qid)
for i, note in enumerate(notes):
if note.qid and counts[note.qid] > 1:
notes[i] = WdNote(note.name, "duplicate_qid", None, f"{note.qid} 同時符合多位人物,不採用")
item_by_qid = {it.qid: it for it in items}
out = []
for p, note in zip(persons, notes, strict=True):
if note.qid:
p = replace(p, wikidata_id=Sourced(note.qid, (WIKIDATA_SOURCE_ID,)))
births = item_by_qid[note.qid].day_births()
if _official_birth(p) is None and len(births) == 1:
p = replace(p, birth_date=Sourced(next(iter(births)), (WIKIDATA_SOURCE_ID,)))
out.append(p)
return out, notes

View File

@ -1,185 +0,0 @@
"""Wikidata(CC0)查詢與快取。
- 依 Wikimedia User-Agent 政策送出可辨識的 User-Agent;聯絡方式用環境變數 ELECTION_DATA_CONTACT 設定。
- 查詢結果快取在 data/raw/people/wikidata/,旁邊的 .meta.json 格式與 fetch.download 相同。
- 每批查詢之間間隔 5 秒;429 或 5xx 時依 Retry-After 退避重試(每次最多等 90 秒)。
"""
from __future__ import annotations
import hashlib
import json
import logging
import os
import time
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
from urllib.parse import urlencode
import httpx
from .names import name_key, wikidata_label_variants
log = logging.getLogger(__name__)
SPARQL_URL = "https://query.wikidata.org/sparql"
BATCH_SIZE = 40
_PAUSE_SECONDS = 5.0
_MAX_WAIT_SECONDS = 90.0
_LANGS = ("zh", "zh-tw", "zh-hant")
_LANG_FILTER = 'IN ("zh-tw", "zh-hant", "zh")'
# 查詢文字是快取鍵的一部分,修改時快取會失效(需要重新查詢)
_POSITION_CLAUSE = (
f"OPTIONAL {{ ?item wdt:P39 ?pos . ?pos rdfs:label ?posLabel . FILTER(LANG(?posLabel) {_LANG_FILTER}) }}"
)
_PARTY_CLAUSE = (
"OPTIONAL { ?item wdt:P102 ?pty . ?pty rdfs:label ?partyLabel . "
f"FILTER(LANG(?partyLabel) {_LANG_FILTER}) }}"
)
_DEFAULT_CONTACT = "research pipeline for a Taiwan election simulation game; set ELECTION_DATA_CONTACT"
def user_agent() -> str:
contact = os.environ.get("ELECTION_DATA_CONTACT", _DEFAULT_CONTACT)
return f"election-2026-people-pipeline/0.1 ({contact}) httpx/{httpx.__version__}"
@dataclass(frozen=True)
class WdItem:
qid: str
label_keys: frozenset[str]
births: tuple[tuple[str, int], ...] # (YYYY-MM-DD, 精確度;11 = 日)
positions: tuple[str, ...]
parties: tuple[str, ...]
countries: frozenset[str]
def day_births(self) -> frozenset[str]:
return frozenset(d for d, precision in self.births if precision >= 11)
def _escape(text: str) -> str:
return text.replace("\\", "\\\\").replace('"', '\\"')
def build_query(names: Sequence[str]) -> str:
values = " ".join(
f'"{_escape(v)}"@{lang}' for n in names for v in wikidata_label_variants(n) for lang in _LANGS
)
return f"""SELECT ?item ?name
(GROUP_CONCAT(DISTINCT CONCAT(STR(?birth), "/", STR(?prec)); separator="|") AS ?births)
(GROUP_CONCAT(DISTINCT ?posLabel; separator="|") AS ?positions)
(GROUP_CONCAT(DISTINCT ?partyLabel; separator="|") AS ?parties)
(GROUP_CONCAT(DISTINCT STRAFTER(STR(?country), "entity/"); separator="|") AS ?countries)
WHERE {{
VALUES ?name {{ {values} }}
?item rdfs:label|skos:altLabel ?name ; wdt:P31 wd:Q5 .
OPTIONAL {{ ?item p:P569/psv:P569 ?bv . ?bv wikibase:timeValue ?birth ; wikibase:timePrecision ?prec . }}
{_POSITION_CLAUSE}
{_PARTY_CLAUSE}
OPTIONAL {{ ?item wdt:P27 ?country }}
}} GROUP BY ?item ?name"""
def _split(value: str) -> list[str]:
return [v for v in value.split("|") if v]
def parse_bindings(payload: dict) -> list[WdItem]:
"""SPARQL JSON → 每個 QID 一筆(同一 QID 的多個標籤合併)。"""
merged: dict[str, dict[str, set]] = {}
for b in payload.get("results", {}).get("bindings", []):
qid = b["item"]["value"].rsplit("/", 1)[-1]
slot = merged.setdefault(
qid, {"keys": set(), "births": set(), "pos": set(), "party": set(), "c": set()}
)
slot["keys"].add(name_key(b["name"]["value"]))
for raw in _split(b.get("births", {}).get("value", "")):
date, _, precision = raw.partition("/")
if len(date) >= 10 and precision.isdigit() and not date.startswith("-"):
slot["births"].add((date[:10], int(precision)))
slot["pos"].update(_split(b.get("positions", {}).get("value", "")))
slot["party"].update(_split(b.get("parties", {}).get("value", "")))
slot["c"].update(_split(b.get("countries", {}).get("value", "")))
return [
WdItem(
qid=qid,
label_keys=frozenset(s["keys"]),
births=tuple(sorted(s["births"])),
positions=tuple(sorted(s["pos"])),
parties=tuple(sorted(s["party"])),
countries=frozenset(s["c"]),
)
for qid, s in sorted(merged.items())
]
def _write_cache(dest: Path, url: str, body: bytes) -> None:
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(body)
meta = {
"url": url,
"retrievedAt": datetime.now(UTC).date().isoformat(),
"sha256": hashlib.sha256(body).hexdigest(),
"tlsVerified": True,
"bytes": len(body),
}
dest.with_name(dest.name + ".meta.json").write_text(
json.dumps(meta, ensure_ascii=False, indent=2), "utf-8"
)
def run_query(query: str, cache_dir: Path, *, retries: int = 4) -> tuple[dict, str, bool]:
"""回傳(JSON, 擷取日期, 是否來自快取)。"""
digest = hashlib.sha256(query.encode("utf-8")).hexdigest()[:20]
dest = cache_dir / f"sparql_{digest}.json"
meta_file = dest.with_name(dest.name + ".meta.json")
if dest.exists() and meta_file.exists():
meta = json.loads(meta_file.read_text(encoding="utf-8"))
return json.loads(dest.read_text(encoding="utf-8")), meta["retrievedAt"], True
url = f"{SPARQL_URL}?{urlencode({'query': query})}"
headers = {"User-Agent": user_agent(), "Accept": "application/sparql-results+json"}
last: Exception | None = None
for attempt in range(1, retries + 1):
try:
resp = httpx.get(SPARQL_URL, params={"query": query}, headers=headers, timeout=120.0)
if resp.status_code in (429, 500, 502, 503, 504):
wait = float(resp.headers.get("Retry-After", 5 * attempt))
log.warning("Wikidata 回應 %d,%.0f 秒後重試", resp.status_code, wait)
time.sleep(min(wait, _MAX_WAIT_SECONDS))
continue
resp.raise_for_status()
payload = resp.json()
_write_cache(dest, url[:2000], resp.content)
time.sleep(_PAUSE_SECONDS)
return payload, datetime.now(UTC).date().isoformat(), False
except (httpx.HTTPError, ValueError) as exc:
last = exc
log.warning("Wikidata 查詢失敗(第 %d 次):%s", attempt, exc)
time.sleep(2 * attempt)
raise RuntimeError("Wikidata 查詢失敗") from last
def fetch_items(names: Iterable[str], cache_dir: Path) -> tuple[list[WdItem], str | None]:
"""依姓名分批查詢;回傳所有候選項目與最早的擷取日期。"""
unique = sorted(dict.fromkeys(names))
items: dict[str, WdItem] = {}
dates: list[str] = []
for start in range(0, len(unique), BATCH_SIZE):
payload, retrieved_at, cached = run_query(build_query(unique[start : start + BATCH_SIZE]), cache_dir)
dates.append(retrieved_at)
for item in parse_bindings(payload):
if item.qid in items:
old = items[item.qid]
item = WdItem(
item.qid,
old.label_keys | item.label_keys,
item.births,
item.positions,
item.parties,
item.countries,
)
items[item.qid] = item
log.info("Wikidata 批次 %d:%s", start // BATCH_SIZE + 1, "快取" if cached else "已查詢")
return list(items.values()), min(dates) if dates else None

View File

@ -1 +0,0 @@
"""人物 AI 評分管線(docs/15):收集證據 → 依公開評分規則打分 → 一致性與偏差檢查 → 人工抽查。"""

View File

@ -1,72 +0,0 @@
"""python -m election_data.scoring [--limit N] [--no-web] [--dry-run]
--dry-run 不呼叫 API:只產生證據包與提示預覽,並粗估費用。真正執行前請先確認費用。
"""
from __future__ import annotations
import argparse
import json
import logging
from datetime import date
from pathlib import Path
from ..config import BUILD_DIR
from .evidence import record_evidence, render_packet
from .pipeline import RUNS, ScoringStats, score_person, write_outputs
log = logging.getLogger(__name__)
# 粗估用的價格與用量(claude-opus-5-5:輸入 $4、輸出 $20 / 百萬 tokens;網路搜尋 $10 / 千次)
PRICE_IN, PRICE_OUT, PRICE_SEARCH = 4.0, 20.0, 10.0
EST_RESEARCH_IN, EST_RESEARCH_OUT, EST_SEARCHES = 30_000, 2_500, 5
EST_SCORE_IN, EST_SCORE_OUT = 4_000, 1_500
def estimate(n: int, use_web: bool) -> str:
research = (
EST_RESEARCH_IN * PRICE_IN + EST_RESEARCH_OUT * PRICE_OUT
) / 1e6 + EST_SEARCHES * PRICE_SEARCH / 1000
scoring = RUNS * (EST_SCORE_IN * PRICE_IN + EST_SCORE_OUT * PRICE_OUT) / 1e6
per_person = scoring + (research if use_web else 0)
return f"約 {n} 人 × US${per_person:.2f} ≈ US${n * per_person:.0f}(粗估,實際依搜尋結果長度而定)"
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="election_data.scoring", description="人物 AI 評分")
parser.add_argument("--people", default=str(BUILD_DIR / "people" / "people.json"))
parser.add_argument("--limit", type=int, default=0, help="只評前 N 人(0 = 全部)")
parser.add_argument("--no-web", action="store_true", help="不做網路研究,只用資料庫紀錄")
parser.add_argument("--effort", default="medium", choices=["low", "medium", "high", "xhigh", "max"])
parser.add_argument("--dry-run", action="store_true", help="不呼叫 API,只輸出預覽與費用估計")
args = parser.parse_args(argv)
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
people_file = json.loads(Path(args.people).read_text(encoding="utf-8"))
people = people_file["people"][: args.limit or None]
out_dir = BUILD_DIR / "people"
evidence_dir = out_dir / "evidence"
evidence_dir.mkdir(parents=True, exist_ok=True)
use_web = not args.no_web
if args.dry_run:
preview = out_dir / "scoring_preview.md"
sample = people[:3]
parts = [f"# 評分預覽(不呼叫 API)\n\n費用估計:{estimate(len(people), use_web)}\n"]
parts += [f"## {p['name']}\n\n```\n{render_packet(p, record_evidence(p), 0)}\n```\n" for p in sample]
preview.write_text("\n".join(parts), encoding="utf-8")
log.info("費用估計:%s;預覽:%s", estimate(len(people), use_web), preview)
return 0
from .llm import AnthropicBackend # 只有真正執行時才需要憑證
backend = AnthropicBackend(effort=args.effort)
stats = ScoringStats()
scored = [score_person(p, backend, stats, evidence_dir, date.today(), use_web) for p in people]
out = write_outputs(out_dir, people_file, scored, stats)
log.info("完成:%s", out)
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,67 +0,0 @@
"""由公開資料直接計算的屬性(不經 AI):知名度、人脈;體力用預設值。"""
from __future__ import annotations
import math
from collections.abc import Mapping
from datetime import date
# 職位層級:用來估計知名度下限(初始值,M1 平衡時調整)。
# 依序比對、取第一個符合的,所以「副」字頭的職稱要排在正職前面。
POSITION_LEVELS: tuple[tuple[str, int], ...] = (
("副總統", 95),
("總統", 100),
("副院長", 85),
("院長", 92),
("黨主席", 85),
("副市長", 65),
("市長", 85),
("副縣長", 60),
("縣長", 80),
("政務次長", 60),
("部長", 75),
("主任委員", 70),
("主席", 80),
("立法委員", 60),
("議員", 45),
)
DEFAULT_STAMINA = 60
def _level(title: str) -> int:
return next((lvl for key, lvl in POSITION_LEVELS if key in title), 40)
def _years(start: str | None, end: str | None, today: date) -> float:
if not start:
return 1.0
begin = date.fromisoformat(start)
finish = date.fromisoformat(end) if end else today
return max(0.0, (finish - begin).days / 365.25)
def awareness(person: Mapping) -> tuple[int, list[str]]:
"""max(職位層級, 得票換算);得票 100 萬約 60 分、500 萬約 70 分。"""
best, sources = 30, []
for pos in person.get("positions", []):
lvl = _level(pos["title"])
if lvl > best:
best, sources = lvl, list(pos["sourceIds"])
for rec in person.get("electionHistory", []):
votes = rec.get("votes") or 0
if votes > 0:
score = int(min(95, max(0, 15 * math.log10(votes) - 30)))
if score > best:
best, sources = score, list(rec["sourceIds"])
return best, sources
def network(person: Mapping, today: date) -> tuple[int, list[str]]:
"""公職年資與歷任職位數:30 + 每年 3 分 + 每多一個職位 5 分,上限 95。"""
positions = person.get("positions", [])
if not positions:
return 30, []
years = sum(_years(p.get("from"), p.get("to"), today) for p in positions)
score = int(min(95, 30 + 3 * years + 5 * (len(positions) - 1)))
sources = sorted({s for p in positions for s in p["sourceIds"]})
return score, sources

View File

@ -1,58 +0,0 @@
"""證據包:每位人物的公開資料條目,給模型引用。
- R 開頭:人物資料庫中的結構化紀錄(職位、學歷、選舉紀錄),出處是 people.json 的 sourceIds。
- W 開頭:研究階段由網路搜尋找到的公開事實,出處是網址。
"""
from __future__ import annotations
import random
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
@dataclass(frozen=True)
class EvidenceItem:
id: str
text: str
sources: tuple[str, ...] # 出處 id 或網址
def record_evidence(person: Mapping) -> list[EvidenceItem]:
items: list[EvidenceItem] = []
def add(text: str, sources: Sequence[str]) -> None:
items.append(EvidenceItem(f"R{len(items) + 1}", text, tuple(sources)))
if person.get("party"):
add(f"政黨:{person['party']}", person.get("fieldSources", {}).get("party", []))
for pos in person.get("positions", []):
span = f"{pos.get('from') or '?'}~{pos.get('to') or '現在'}"
add(f"職位:{pos['org']} {pos['title']}({span})", pos["sourceIds"])
for edu in person.get("education", []):
add(f"學歷:{edu.get('school') or ''} {edu['degree']}".strip(), edu["sourceIds"])
for rec in person.get("electionHistory", []):
result = "當選" if rec["elected"] else "未當選"
votes = f",得票 {rec['votes']:,}" if rec.get("votes") is not None else ""
share = f"({rec['share']:.1%})" if rec.get("share") is not None else ""
district = f" {rec['district']}" if rec.get("district") else ""
add(f"選舉:{rec['election']}{district},{result}{votes}{share}", rec["sourceIds"])
return items
def web_evidence(raw_items: Sequence[Mapping]) -> list[EvidenceItem]:
out = []
for i, item in enumerate(raw_items, 1):
date = f"({item['published']})" if item.get("published") else ""
out.append(EvidenceItem(f"W{i}", f"{item['claim']}{date}", (item["url"],)))
return out
def render_packet(person: Mapping, items: Sequence[EvidenceItem], seed: int) -> str:
"""證據清單;以 seed 打亂順序,讓三次評分看到不同排列(一致性檢查)。"""
shuffled = list(items)
random.Random(seed).shuffle(shuffled)
header = f"人物:{person['name']}({person['category']})"
lines = [header, "", "證據清單(請以編號引用):"]
lines += [f"[{item.id}] {item.text}" for item in shuffled]
return "\n".join(lines)

View File

@ -1,142 +0,0 @@
"""呼叫 Claude:研究(網路搜尋找公開事實)與評分(結構化輸出)。
- 模型預設 claude-opus-5-5,effort 明確設定(此模型預設 medium)。
- 開啟伺服器端拒絕回退(fallbacks: "default"),被安全分類器拒絕時由伺服器改用其他模型;
實際回應的模型記錄在每筆評分的 model 欄位。
- 憑證由 SDK 自行解析(ANTHROPIC_API_KEY、ANTHROPIC_AUTH_TOKEN 或 `ant auth login` 的設定檔)。
"""
from __future__ import annotations
import json
import logging
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Protocol
import anthropic
from .rubric import render_rubric, score_schema
log = logging.getLogger(__name__)
MODEL = "claude-opus-5-5"
FALLBACK_BETA = "server-side-fallback-2026-07-01"
MAX_CONTINUATIONS = 5
STAT_ENUM = ["affinity", "eloquence", "strategy", "online", "image", "wealth"]
RESEARCH_SYSTEM = (
"你是台灣政治資料研究員。任務:為指定的公眾人物整理與其公開角色相關、可查證的公開事實,"
"供遊戲的屬性評分使用。只收錄公開報導、官方資料、公開民調、公開的社群數據。"
"不收錄私生活、家人、住址、外貌,也不收錄尚未定案的指控。"
"每一條都要附上你實際看過的網址。整理完成後呼叫 submit_evidence 提交。"
)
SUBMIT_EVIDENCE_TOOL = {
"name": "submit_evidence",
"description": "提交整理好的公開事實清單(最多 15 條),每條附網址與相關的屬性。",
"strict": True,
"input_schema": {
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"claim": {"type": "string", "description": "一句話的事實陳述,繁體中文"},
"url": {"type": "string"},
"published": {"type": "string", "description": "YYYY-MM;不確定時留空字串"},
"stats": {"type": "array", "items": {"type": "string", "enum": STAT_ENUM}},
},
"required": ["claim", "url", "published", "stats"],
"additionalProperties": False,
},
}
},
"required": ["items"],
"additionalProperties": False,
},
}
@dataclass(frozen=True)
class LlmResult:
data: Mapping
model: str
input_tokens: int
output_tokens: int
class ScoringBackend(Protocol):
def research(self, person_summary: str, max_searches: int) -> LlmResult: ...
def score(self, packet: str) -> LlmResult: ...
class RefusedError(RuntimeError):
pass
@dataclass
class AnthropicBackend:
model: str = MODEL
effort: str = "medium"
client: anthropic.Anthropic | None = None
def __post_init__(self) -> None:
self.client = self.client or anthropic.Anthropic()
def _create(self, *, output_config: Mapping | None = None, **kwargs: object): # noqa: ANN202
"""回傳 SDK 的 BetaMessage。effort 一律明確設定;其他 output_config 欄位(例如 format)合併進來。"""
assert self.client is not None
return self.client.beta.messages.create(
model=self.model,
max_tokens=16000,
betas=[FALLBACK_BETA],
fallbacks="default",
output_config={"effort": self.effort, **(output_config or {})},
**kwargs,
)
def research(self, person_summary: str, max_searches: int = 6) -> LlmResult:
tools = [
{"type": "web_search_20260209", "name": "web_search", "max_uses": max_searches},
SUBMIT_EVIDENCE_TOOL,
]
user = {"role": "user", "content": f"{person_summary}\n\n請搜尋並整理,完成後呼叫 submit_evidence。"}
messages: list[dict] = [user]
tokens_in = tokens_out = 0
nudged = False
for _ in range(MAX_CONTINUATIONS + 1):
response = self._create(system=RESEARCH_SYSTEM, tools=tools, messages=messages)
tokens_in += response.usage.input_tokens
tokens_out += response.usage.output_tokens
if response.stop_reason == "refusal":
raise RefusedError(f"研究被拒絕:{getattr(response.stop_details, 'category', None)}")
submit = next(
(b for b in response.content if b.type == "tool_use" and b.name == "submit_evidence"), None
)
if submit is not None:
return LlmResult(dict(submit.input), response.model, tokens_in, tokens_out)
# 對話只往後附加,不修改先前的內容(保留思考區塊的完整性)
messages = [*messages, {"role": "assistant", "content": response.content}]
if response.stop_reason == "pause_turn":
continue
if nudged:
break
messages.append({"role": "user", "content": "請把整理好的事實以 submit_evidence 提交。"})
nudged = True
raise RuntimeError("研究階段沒有提交證據")
def score(self, packet: str) -> LlmResult:
response = self._create(
system=[{"type": "text", "text": render_rubric(), "cache_control": {"type": "ephemeral"}}],
messages=[{"role": "user", "content": f"{packet}\n\n請依評分規則,為六個屬性各給一筆評分。"}],
output_config={"format": {"type": "json_schema", "schema": score_schema()}},
)
if response.stop_reason == "refusal":
raise RefusedError(f"評分被拒絕:{getattr(response.stop_details, 'category', None)}")
text = next(b.text for b in response.content if b.type == "text")
return LlmResult(
json.loads(text), response.model, response.usage.input_tokens, response.usage.output_tokens
)

View File

@ -1,257 +0,0 @@
"""評分流程:衍生屬性 → 研究 → 三次評分取中位數 → 一致性、偏差檢查 → 人工抽查清單。"""
from __future__ import annotations
import csv
import hashlib
import json
import logging
import random
import statistics
from collections import defaultdict
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from datetime import UTC, date, datetime
from pathlib import Path
from jsonschema import Draft202012Validator
from ..validate import validate
from .derive import DEFAULT_STAMINA, awareness, network
from .evidence import EvidenceItem, record_evidence, render_packet, web_evidence
from .llm import RefusedError, ScoringBackend
from .rubric import AI_STATS, RUBRIC_VERSION, score_schema
log = logging.getLogger(__name__)
RUNS = 3
CONSISTENCY_LIMIT = 10 # 三次分數差超過這個值就標記人工複核
BIAS_LIMIT = 8.0 # 各政黨平均分數差超過這個值就整批複核規則
MIN_GROUP = 5
REVIEW_SAMPLE_RATE = 0.05
DEFAULT_VALUE = 50
TIER_A_KEYWORDS = ("總統", "院長", "市長", "縣長", "黨主席", "部長")
_RANGE_VALIDATOR = Draft202012Validator(
{"type": "object", "properties": {"value": {"type": ["integer", "null"], "minimum": 0, "maximum": 100}}}
)
@dataclass
class ScoringStats:
people: int = 0
research_failures: list[str] = field(default_factory=list)
refusals: list[str] = field(default_factory=list)
inconsistent: list[tuple[str, str, list[int]]] = field(default_factory=list)
input_tokens: int = 0
output_tokens: int = 0
def _seed(person_id: str, run: int) -> int:
return int(hashlib.sha256(f"{person_id}:{run}".encode()).hexdigest()[:8], 16)
def _record(stat: str, value: int, method: str, rationale: str | None, citations: Sequence[str],
confidence: str, model: str | None, now: str) -> dict: # fmt: skip
return {
"stat": stat,
"value": int(value),
"method": method,
"rationale": rationale,
"citations": list(citations),
"confidence": confidence,
"model": model,
"rubricVersion": RUBRIC_VERSION,
"scoredAt": now,
"reviewed": False,
}
def _summary(person: Mapping, items: Sequence[EvidenceItem]) -> str:
known = "\n".join(f"- {item.text}" for item in items[:20])
return f"人物:{person['name']}\n類別:{person['category']}\n已知公開紀錄:\n{known}"
def _aggregate(
stat: str, runs: Sequence[Mapping], valid_ids: set[str]
) -> tuple[int, str, list[str], str, bool]:
"""回傳 (分數, 方法, 引用, 理由, 是否不一致)。引用不在證據清單中的分數視為無效(docs/15)。"""
usable = []
for run in runs:
entry = next((s for s in run["scores"] if s["stat"] == stat), None)
if entry is None or entry["insufficient"] or entry["value"] is None:
continue
cited = [c for c in entry["citations"] if c in valid_ids]
if not cited or list(_RANGE_VALIDATOR.iter_errors(entry)):
continue
usable.append((entry, cited))
if len(usable) < 2:
return DEFAULT_VALUE, "default", [], "證據不足,使用預設值。", False
values = sorted(e["value"] for e, _ in usable)
median = int(statistics.median(values))
closest = min(usable, key=lambda pair: abs(pair[0]["value"] - median))
inconsistent = values[-1] - values[0] > CONSISTENCY_LIMIT
return (
median,
"ai",
sorted({c for _, cited in usable for c in cited}),
closest[0]["rationale"],
inconsistent,
)
def score_person(
person: Mapping,
backend: ScoringBackend,
stats: ScoringStats,
evidence_dir: Path,
today: date,
use_web: bool,
) -> dict:
now = datetime.now(UTC).isoformat(timespec="seconds")
records: list[dict] = []
value, sources = awareness(person)
records.append(
_record("awareness", value, "derived", "依最高職位層級與歷屆得票計算。", sources, "high", None, now)
)
value, sources = network(person, today)
records.append(
_record("network", value, "derived", "依公職年資與歷任職位數計算。", sources, "high", None, now)
)
records.append(
_record("stamina", DEFAULT_STAMINA, "default", "沒有客觀資料,使用預設值。", [], "low", None, now)
)
items = record_evidence(person)
cache = evidence_dir / f"{person['id']}.json"
if use_web:
if cache.exists():
web_raw = json.loads(cache.read_text(encoding="utf-8"))["items"]
else:
try:
result = backend.research(_summary(person, items), max_searches=6)
web_raw = list(result.data.get("items", []))
stats.input_tokens += result.input_tokens
stats.output_tokens += result.output_tokens
cache.write_text(
json.dumps({"model": result.model, "items": web_raw}, ensure_ascii=False, indent=1),
encoding="utf-8",
)
except RefusedError as exc:
stats.refusals.append(f"{person['id']} 研究:{exc}")
web_raw = []
except Exception as exc: # noqa: BLE001 - 單人失敗不中斷整批
log.exception("研究失敗:%s", person["id"])
stats.research_failures.append(f"{person['id']}:{exc}")
web_raw = []
items = items + web_evidence(web_raw)
valid_ids = {item.id for item in items}
citation_sources = {item.id: item.sources for item in items}
runs, model = [], None
for run in range(RUNS):
try:
result = backend.score(render_packet(person, items, _seed(person["id"], run)))
except RefusedError as exc:
stats.refusals.append(f"{person['id']} 評分:{exc}")
continue
validate_scores(result.data)
runs.append(result.data)
model = result.model
stats.input_tokens += result.input_tokens
stats.output_tokens += result.output_tokens
for rubric in AI_STATS:
value, method, cited, rationale, inconsistent = _aggregate(rubric.key, runs, valid_ids)
if inconsistent:
per_run = [
s["value"]
for r in runs
for s in r["scores"]
if s["stat"] == rubric.key and s["value"] is not None
]
stats.inconsistent.append((person["id"], rubric.key, per_run))
expanded = sorted({src for c in cited for src in citation_sources[c]})
confidence = "low" if method == "default" else ("medium" if inconsistent else "high")
records.append(
_record(rubric.key, value, method, rationale, expanded or cited, confidence, model, now)
)
stats.people += 1
by_stat = {r["stat"]: r["value"] for r in records}
return {**person, "stats": {**person["stats"], **by_stat}, "scoring": records}
def validate_scores(data: Mapping) -> None:
errors = list(Draft202012Validator(score_schema()).iter_errors(data))
if errors:
raise ValueError(f"評分輸出不符合結構:{errors[0].message}")
def bias_report(people: Sequence[Mapping]) -> list[str]:
"""各政黨的 AI 屬性平均;差距超過門檻的列出來(需要人工判斷是否有客觀原因)。"""
lines = []
for rubric in AI_STATS:
groups: dict[str, list[int]] = defaultdict(list)
for p in people:
rec = next((r for r in p["scoring"] if r["stat"] == rubric.key and r["method"] == "ai"), None)
if rec:
groups[p.get("party") or "無黨籍"].append(rec["value"])
means = {party: statistics.mean(v) for party, v in groups.items() if len(v) >= MIN_GROUP}
if len(means) < 2:
continue
spread = max(means.values()) - min(means.values())
flag = "⚠ 需要複核" if spread > BIAS_LIMIT else "通過"
detail = "、".join(f"{k} {v:.1f}({len(groups[k])} 人)" for k, v in sorted(means.items()))
lines.append(f"| {rubric.name} | {detail} | {spread:.1f} | {flag} |")
return lines
def review_sample(people: Sequence[Mapping], seed: int = 2026) -> list[Mapping]:
"""全部 A 級人物,加上其餘人物隨機抽 5%。"""
tier_a = [p for p in people if any(k in pos["title"] for pos in p["positions"] for k in TIER_A_KEYWORDS)]
rest = [p for p in people if p not in tier_a]
k = max(1, round(len(rest) * REVIEW_SAMPLE_RATE)) if rest else 0
return tier_a + random.Random(seed).sample(rest, k)
def write_outputs(
out_dir: Path, people_file: Mapping, scored: Sequence[Mapping], stats: ScoringStats
) -> Path:
payload = {**people_file, "people": list(scored)}
validate(payload, "people.schema.json")
out = out_dir / "people_scored.json"
out.write_text(json.dumps(payload, ensure_ascii=False, indent=1), encoding="utf-8")
sample = review_sample(scored)
with (out_dir / "review_sample.csv").open("w", encoding="utf-8-sig", newline="") as fh:
writer = csv.writer(fh)
writer.writerow(["id", "姓名", "屬性", "分數", "方法", "信心", "理由", "出處", "複核結果"])
for p in sample:
for r in p["scoring"]:
writer.writerow([p["id"], p["name"], r["stat"], r["value"], r["method"], r["confidence"],
r["rationale"], " ".join(r["citations"]), ""]) # fmt: skip
lines = [
f"# AI 評分報告(規則 {RUBRIC_VERSION})",
"",
f"- 評分人數:{stats.people}",
f"- 用量:輸入 {stats.input_tokens:,} tokens,輸出 {stats.output_tokens:,} tokens",
f"- 研究失敗:{len(stats.research_failures)};被拒絕:{len(stats.refusals)}",
f"- 三次評分差距超過 {CONSISTENCY_LIMIT} 分:{len(stats.inconsistent)} 筆"
"(已標記為中信心,需人工複核)",
f"- 人工抽查清單:review_sample.csv({len(sample)} 人)",
"",
"## 政黨偏差檢查",
"",
"| 屬性 | 各政黨平均 | 最大差距 | 結果 |",
"|---|---|---|---|",
*(bias_report(scored) or ["| (人數不足以比較) | | | |"]),
"",
"## 不一致的評分",
"",
*[f"- {pid} {stat}:{vals}" for pid, stat, vals in stats.inconsistent[:50]],
"",
"## 失敗與拒絕",
"",
*[f"- {x}" for x in stats.research_failures + stats.refusals],
]
(out_dir / "scoring_report.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
return out

View File

@ -1,141 +0,0 @@
"""公開評分規則 v1。規則改版時 RUBRIC_VERSION 要升版,所有人重新評分(docs/15)。"""
from __future__ import annotations
from dataclasses import dataclass
RUBRIC_VERSION = "v1"
@dataclass(frozen=True)
class StatRubric:
key: str
name: str
definition: str
anchors: tuple[tuple[str, str], ...] # (分數段, 描述)
AI_STATS: tuple[StatRubric, ...] = (
StatRubric(
"affinity",
"親和力",
"與一般民眾互動的溫度與接地氣程度,包括基層走訪、服務案件、與選民面對面的互動。",
(
("80–100", "長期以基層經營著稱,親民形象被多家媒體反覆報導"),
("60–79", "有穩定、可查的地方走訪或服務紀錄"),
("40–59", "一般;公開資料沒有特別突出的正面或負面紀錄"),
("20–39", "公開報導多描述其距離感,基層互動紀錄少"),
("0–19", "多次因對待民眾的態度引發廣泛的公開批評"),
),
),
StatRubric(
"eloquence",
"口才",
"辯論、質詢、受訪、演講的表達能力與臨場反應。",
(
("80–100", "在全國性辯論、質詢或重大記者會中的表現被廣泛報導為出色"),
("60–79", "公開發言條理清楚,有可查的良好表現紀錄"),
("40–59", "一般"),
("20–39", "公開發言常被報導為不清楚或失準"),
("0–19", "多次重大失言並造成廣泛負面報導"),
),
),
StatRubric(
"strategy",
"謀略",
"選戰操盤、議程設定、協商與組織動員的成效。",
(
("80–100", "多次在困難選情中勝選,或主導重大政治協商、法案、組織改造成功"),
("60–79", "有可查的成功選戰或協商紀錄"),
("40–59", "一般"),
("20–39", "公開紀錄中策略失誤多於成功"),
("0–19", "多次重大策略失誤並被廣泛報導"),
),
),
StatRubric(
"online",
"網路魅力",
"社群平台的經營成效與網路聲量,以公開的追蹤數與互動情形為主要依據。",
(
("80–100", "主要平台追蹤數居全國政治人物前列,經常產生大量互動"),
("60–79", "追蹤數與互動在同層級公職中屬前段"),
("40–59", "一般"),
("20–39", "社群經營有限"),
("0–19", "幾乎沒有經營社群,或網路聲量以負面為主"),
),
),
StatRubric(
"image",
"形象",
"公眾對其清廉、專業、可信度的整體觀感,以公開民調的好感度、信任度為主要依據。",
(
("80–100", "公開民調的好感或信任度長期居前段"),
("60–79", "好感度高於同層級平均"),
("40–59", "一般或資料不足以判斷高低"),
("20–39", "好感度明顯低於同層級平均"),
("0–19", "長期居於各項民調的末段"),
),
),
StatRubric(
"wealth",
"財力",
"個人可動用的財務資源,以公開的財產申報與公開報導為依據。",
(
("80–100", "公開申報或報導顯示資產規模在政治人物中居前段"),
("60–79", "高於同層級平均"),
("40–59", "一般或資料不足"),
("20–39", "低於同層級平均"),
("0–19", "公開資料顯示資源非常有限"),
),
),
)
RULES: tuple[str, ...] = (
"分數以全台灣的政治人物與公眾人物為比較基準,50 分代表一般水準。",
"每個分數都必須引用證據清單中的編號;沒有證據支持時,回報資料不足(insufficient),不要猜。",
"只使用與其公開角色相關的公開資訊。不考慮私生活、家人、外貌。",
"政黨、政治立場不是評分因素;同樣的表現不論政黨都給同樣的分數。",
"爭議中、尚未定案的指控不能作為扣分依據;只有確定判決或官方正式認定的事項可以。",
"理由用繁體中文寫一到兩句,直接說明依據,不超過 120 字。",
)
def render_rubric() -> str:
"""產生公開版評分規則(docs/rubric-v1.md 與模型的系統提示共用同一份文字)。"""
lines = [f"# 人物評分規則 {RUBRIC_VERSION}", "", "## 共通規則", ""]
lines += [f"{i}. {rule}" for i, rule in enumerate(RULES, 1)]
for stat in AI_STATS:
lines += [
"",
f"## {stat.name}({stat.key})",
"",
stat.definition,
"",
"| 分數 | 描述 |",
"|---|---|",
]
lines += [f"| {band} | {desc} |" for band, desc in stat.anchors]
return "\n".join(lines) + "\n"
def score_schema() -> dict:
"""結構化輸出的 JSON Schema。數值範圍另以 jsonschema 在本地驗證。"""
item = {
"type": "object",
"properties": {
"stat": {"type": "string", "enum": [s.key for s in AI_STATS]},
"insufficient": {"type": "boolean"},
"value": {"type": ["integer", "null"]},
"confidence": {"type": "string", "enum": ["high", "medium", "low"]},
"rationale": {"type": "string"},
"citations": {"type": "array", "items": {"type": "string"}},
},
"required": ["stat", "insufficient", "value", "confidence", "rationale", "citations"],
"additionalProperties": False,
}
return {
"type": "object",
"properties": {"scores": {"type": "array", "items": item}},
"required": ["scores"],
"additionalProperties": False,
}

View File

@ -1,16 +0,0 @@
from __future__ import annotations
from pathlib import Path
import pytest
FIXTURES = Path(__file__).parent / "fixtures"
@pytest.fixture
def fixtures() -> Path:
return FIXTURES
def read_fixture(name: str) -> str:
return (FIXTURES / name).read_text(encoding="utf-8")

View File

@ -1,42 +0,0 @@
<ul class="grid2 effect" id="grid">
<li class="member_img hvr-outline-in">
<div class="member_box">
<a href="https://www.moi.gov.tw/cp.aspx?n=27" target="_blank" title="內政部劉世芳(另開視窗)" rel="noreferrer noopener">
<span></span>
<span class="title"><span style="color: #414641;border-bottom: none;">內政部</span><br /><span>劉世芳部長</span></span>
</a>
</div>
</li>
<li class="member_img hvr-outline-in">
<div class="member_box">
<a href="https://www.ocac.gov.tw/OCAC/Pages/Detail.aspx?nodeid=555&pid=78817233" target="_blank" title="僑務委員會李姸慧(另開視窗)" rel="noreferrer noopener">
<span></span>
<span class="title"><span style="color: #414641;border-bottom: none;">僑務委員會</span><br /><span>李姸慧代理委員長</span></span>
</a>
</div>
</li>
<li class="member_img hvr-outline-in">
<div class="member_box">
<a href="https://www.cip.gov.tw/zh-tw/menu/data-list/80A47B1EC7BF5A12-info.html?cumid=80A47B1EC7BF5A12" target="_blank" title="原住民族委員會曾智勇(另開視窗)" rel="noreferrer noopener">
<span></span>
<span class="title"><span style="color: #414641;border-bottom: none;">原住民族委員會</span><br /><span>曾智勇 Ljaucu‧Zingrur 主任委員</span></span>
</a>
</div>
</li>
<li class="member_img hvr-outline-in">
<div class="member_box">
<a href="https://www.cbc.gov.tw/tw/cp-326-27196-EF74B-1.html" target="_blank" title="中央銀行楊金龍(另開視窗)" rel="noreferrer noopener">
<span></span>
<span class="title"><span style="color: #414641;border-bottom: none;">中央銀行</span><br /><span>楊金龍總裁</span></span>
</a>
</div>
</li>
<li class="member_img hvr-outline-in">
<div class="member_box">
<a href="https://www.ftc.gov.tw/internet/main/doc/docDetail.aspx?uid=1948&docid=17978" target="_blank" title="公平交易委員會陳志民(另開視窗)" rel="noreferrer noopener">
<span></span>
<span class="title"><span style="color: #414641;border-bottom: none;">公平交易委員會</span><br /><span>陳志民代理主任委員</span></span>
</a>
</div>
</li>
</ul>

View File

@ -1,26 +0,0 @@
<html><head><title>
行政院全球資訊網-院長
</title></head><body><div class="ail main_people">
<span class="h2">
行政院卓榮泰院長
</span>
<div class="words_content">
<div class="col-2 right_content">
<div class="other_link ail other_people">
</div>
</div>
<div class="data_left col-8">
<!--學 歷 -->
<span class="principal_title">學 歷</span><ul class="principal"><li><span>民國68年09月-73年06月 </span><span>中興大學法律系畢業</span></li></ul>
<!--經 歷 -->
<span class="principal_title">經 歷</span><ul class="principal"><li><span>民國78年-87年 </span><span>臺北市議員</span></li><li><span>民國88年-93年 </span><span>立法委員</span></li><li><span>民國93年-94年 </span><span>總統府副秘書長</span></li><li><span>民國94年-95年 </span><span>行政院秘書長</span></li><li><span>民國95年-96年 </span><span>總統府副秘書長</span></li><li><span>民國96年-97年 </span><span>民進黨秘書長</span></li><li><span>民國106年04月-106年09月 </span><span>民進黨副秘書長</span></li><li><span>民國106年-107年 </span><span>行政院秘書長</span></li><li><span>民國108年-109年 </span><span>民進黨主席</span></li><li><span>民國113年5月20日- </span><span>行政院院長</span></li></ul>
</div>
<hr class="clear">
<div class="notice_box">
<p></p>
<p>以上內容之著作權均屬行政院或原著作權人所有,除有合理使用情形外,應取得著作權人之同意或授權後,方得利用。</body></html>

View File

@ -1,76 +0,0 @@
{
"dataList": [
{
"term": "11",
"name": "丁學忠",
"sex": "男",
"party": "中國國民黨",
"partyGroup": "中國國民黨",
"areaName": "雲林縣第1選舉區",
"committee": "第11屆第1會期:內政委員會;第11屆第2會期:內政委員會;第11屆第3會期:內政委員會;第11屆第4會期:內政委員會;第11屆第5會期:內政委員會;第11屆第6會期:內政委員會;",
"onboardDate": "2024/02/01",
"degree": "國立虎尾科技大學碩士學位",
"leaveFlag": "否",
"leaveDate": "",
"leaveReason": ""
},
{
"term": "11",
"name": "伍麗華Saidhai‧Tahovecahe",
"sex": "女",
"party": "民主進步黨",
"partyGroup": "民主進步黨",
"areaName": "山地原住民選舉區",
"committee": "第11屆第1會期:財政委員會;第11屆第2會期:財政委員會;第11屆第3會期:教育及文化委員會;第11屆第3會期:修憲委員會;第11屆第4會期:教育及文化委員會;第11屆第5會期:教育及文化委員會;第11屆第5會期:修憲委員會;第11屆第6會期:教育及文化委員會;",
"onboardDate": "2024/02/01",
"degree": "國立屏東大學教育行政研究所博士;屏東師範學院國民教育硏究所碩士(85年-87年);屏東師範學院(80年-84年);屏東師專(73年-78年)",
"leaveFlag": "否",
"leaveDate": "",
"leaveReason": ""
},
{
"term": "11",
"name": "吳春城",
"sex": "男",
"party": "台灣民眾黨",
"partyGroup": "台灣民眾黨",
"areaName": "全國不分區及僑居國外國民",
"committee": "第11屆第1會期:教育及文化委員會;第11屆第2會期:教育及文化委員會;",
"onboardDate": "2024/02/01",
"degree": "復旦大學管理學博士;中山大學法學碩士;中央大學文學士",
"leaveFlag": "是",
"leaveDate": "2025/02/27",
"leaveReason": "辭職"
},
{
"term": "11",
"name": "高金素梅",
"sex": "女",
"party": "無黨籍",
"partyGroup": "中國國民黨",
"areaName": "山地原住民選舉區",
"committee": "第11屆第1會期:內政委員會;第11屆第2會期:內政委員會;第11屆第3會期:內政委員會;第11屆第4會期:內政委員會;第11屆第5會期:內政委員會;第11屆第6會期:內政委員會;",
"onboardDate": "2024/02/01",
"degree": "臺中市青年高級中學",
"leaveFlag": "否",
"leaveDate": "",
"leaveReason": ""
},
{
"term": "11",
"name": "陳俊宇",
"sex": "男",
"party": "民主進步黨",
"partyGroup": "民主進步黨",
"areaName": "宜蘭縣選舉區",
"committee": "第11屆第1會期:司法及法制委員會;第11屆第2會期:司法及法制委員會;第11屆第3會期:外交及國防委員會;第11屆第4會期:外交及國防委員會;第11屆第5會期:外交及國防委員會;第11屆第6會期:外交及國防委員會;",
"onboardDate": "2024/02/01",
"degree": "佛光大學公共事務學系碩士;蘭陽技術學院國際貿易科;宜蘭高商資料處理科;復興國中;大湖國小",
"leaveFlag": "否",
"leaveDate": "",
"leaveReason": ""
}
]
}

View File

@ -1,56 +0,0 @@
<html><body><div id="CCMS_Content" data-func="{&#39;linkType&#39;:{&#39;domains&#39;:[&#39;https://ws.moi.gov.tw&#39;,&#39;https://ws.moi.gov.tw&#39;]}, &#39;imgMapRwd&#39;:{}}" data-index="2" data-type="3" data-child="3"><div class="in"><div class="ct"><div class="in"> <div class="area-editor user-edit" data-type="0" data-child="1"><div class="in"><div class="ct"><div class="in"><div class="lead-info">
<div class="lead-img">
<a href="https://ws.moi.gov.tw/001/Upload/localofficial/urllink/3847b2ad-9cac-4446-a4e8-51e57e4b8884.jpg" rel="noreferrer" target="_blank" title="高虹安(另開視窗)">
</a>
</div>
<div class="lead-data">
<div class="figcaption">
<div class="title">新竹市政府</div> <div class="name">
<span>高虹安</span>
</div>
</div>
<div class="essay">
<div class="caption">黨籍</div>
<div class="p">
<ul>
<li>台灣民眾黨</li> </ul>
</div>
</div>
<div class="essay">
<div class="caption">選舉屆次</div>
<div class="p">
<ul>
<li>111年度縣市長選舉</li> </ul>
</div>
</div>
<div class="essay">
<div class="caption">學歷</div>
<div class="p">
<ul>
<li>美國辛辛那提大學機械工程博士
國立台灣大學資訊工程碩士
國立臺灣師範大學資訊教育學士
台北市立第一女子高級中學</li>
</ul>
</div>
</div>
<div class="essay">
<div class="caption">簡歷</div>
<div class="p">
<ul>
<li>第十屆立法委員
台灣民眾黨立法院黨團副總召
財團法人郭台銘文教基金會董事
財團法人消防發展基金會董事
鴻海科技集團副總經理</li>
</ul>
</div>
</div>
<div>辦公地址</div></div></body></html>

View File

@ -1,74 +0,0 @@
<div class="result-list">
<div class="block">
<div class="in">
<div class="img">
<span>
</span>
</div>
<div class="essay">
<div class="caption">
<span>高虹安</span> </div>
<div class="locate">
<span>新竹市</span> </div>
<div class="position">
<span>新竹市政府</span><span>市長</span> </div>
<div class="group">
<span>台灣民眾黨</span>
</div>
</div>
<!-- 更多按鈕這裡,title可能有個無障礙問題,解法是在title裡面補上人名,例如:柯文哲詳細資訓 這樣 -->
<div class="more-btn">
<ul>
<li><a href="/LocalOfficial_Content.aspx?n=579&_PARENT_ID=MYR11112OE0001&_TYP=MYR&TYP=KND0005" title="高虹安詳細資訊">詳細資訊</a></li> </ul>
</div>
</div>
</div>
<div class="block">
<div class="in">
<div class="img">
<span>
</span>
</div>
<div class="essay">
<div class="caption">
<span>陳福海</span> </div>
<div class="locate">
<span>金門縣</span> </div>
<div class="position">
<span>金門縣政府</span><span>縣長</span> </div>
<div class="group">
<span>無</span>
</div>
</div>
<!-- 更多按鈕這裡,title可能有個無障礙問題,解法是在title裡面補上人名,例如:柯文哲詳細資訓 這樣 -->
<div class="more-btn">
<ul>
<li><a href="/LocalOfficial_Content.aspx?n=579&_PARENT_ID=MYR11112WE0001&_TYP=MYR&TYP=KND0005" title="陳福海詳細資訊">詳細資訊</a></li> </ul>
</div>
</div>
</div>
<div class="block">
<div class="in">
<div class="img">
<span>
</span>
</div>
<div class="essay">
<div class="caption">
<span>王忠銘</span> </div>
<div class="locate">
<span>連江縣</span> </div>
<div class="position">
<span>連江縣政府</span><span>縣長</span> </div>
<div class="group">
<span>中國國民黨</span>
</div>
</div>
<!-- 更多按鈕這裡,title可能有個無障礙問題,解法是在title裡面補上人名,例如:柯文哲詳細資訓 這樣 -->
<div class="more-btn">
<ul>
<li><a href="/LocalOfficial_Content.aspx?n=579&_PARENT_ID=MYR11112ZE0001&_TYP=MYR&TYP=KND0005" title="王忠銘詳細資訊">詳細資訊</a></li> </ul>
</div>
</div>
</div>
</div>

View File

@ -1,784 +0,0 @@
{
"results": {
"bindings": [
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q21055059"
},
"name": {
"xml:lang": "zh-tw",
"type": "literal",
"value": "吳宗憲"
},
"births": {
"type": "literal",
"value": "1959-01-17T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": "桃園市議員|桃園市議員|桃園市議員"
},
"parties": {
"type": "literal",
"value": "中國國民黨|中國國民黨|中國國民黨|民主進步黨|民主進步黨|民主進步黨"
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q21055059"
},
"name": {
"xml:lang": "zh-hant",
"type": "literal",
"value": "吳宗憲"
},
"births": {
"type": "literal",
"value": "1959-01-17T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": "桃園市議員|桃園市議員|桃園市議員"
},
"parties": {
"type": "literal",
"value": "中國國民黨|中國國民黨|中國國民黨|民主進步黨|民主進步黨|民主進步黨"
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q21055059"
},
"name": {
"xml:lang": "zh",
"type": "literal",
"value": "吳宗憲"
},
"births": {
"type": "literal",
"value": "1959-01-17T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": "桃園市議員|桃園市議員|桃園市議員"
},
"parties": {
"type": "literal",
"value": "中國國民黨|中國國民黨|中國國民黨|民主進步黨|民主進步黨|民主進步黨"
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q121904956"
},
"name": {
"xml:lang": "zh-tw",
"type": "literal",
"value": "丁學忠"
},
"births": {
"type": "literal",
"value": "1970-06-28T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": "中國國民黨|中國國民黨|中國國民黨"
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q121904956"
},
"name": {
"xml:lang": "zh-hant",
"type": "literal",
"value": "丁學忠"
},
"births": {
"type": "literal",
"value": "1970-06-28T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": "中國國民黨|中國國民黨|中國國民黨"
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q121904956"
},
"name": {
"xml:lang": "zh",
"type": "literal",
"value": "丁學忠"
},
"births": {
"type": "literal",
"value": "1970-06-28T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": "中國國民黨|中國國民黨|中國國民黨"
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q124293468"
},
"name": {
"xml:lang": "zh-hant",
"type": "literal",
"value": "吳宗憲"
},
"births": {
"type": "literal",
"value": "1971-09-27T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": "中國國民黨|中國國民黨|中國國民黨"
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q124293468"
},
"name": {
"xml:lang": "zh",
"type": "literal",
"value": "吳宗憲"
},
"births": {
"type": "literal",
"value": "1971-09-27T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": "中國國民黨|中國國民黨|中國國民黨"
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q7198343"
},
"name": {
"xml:lang": "zh-tw",
"type": "literal",
"value": "陳瑩"
},
"births": {
"type": "literal",
"value": "1972-11-15T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": "立法委員|立法委員|立法委員"
},
"parties": {
"type": "literal",
"value": "民主進步黨|民主進步黨|民主進步黨"
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q7198343"
},
"name": {
"xml:lang": "zh-hant",
"type": "literal",
"value": "陳瑩"
},
"births": {
"type": "literal",
"value": "1972-11-15T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": "立法委員|立法委員|立法委員"
},
"parties": {
"type": "literal",
"value": "民主進步黨|民主進步黨|民主進步黨"
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q7198343"
},
"name": {
"xml:lang": "zh",
"type": "literal",
"value": "陳瑩"
},
"births": {
"type": "literal",
"value": "1972-11-15T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": "立法委員|立法委員|立法委員"
},
"parties": {
"type": "literal",
"value": "民主進步黨|民主進步黨|民主進步黨"
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q116894056"
},
"name": {
"xml:lang": "zh-tw",
"type": "literal",
"value": "王興煥"
},
"births": {
"type": "literal",
"value": "1973-01-01T00:00:00Z/9"
},
"positions": {
"type": "literal",
"value": "台灣基進秘書長|台湾基进秘书长|台湾基进党主席"
},
"parties": {
"type": "literal",
"value": "台灣基進|台灣基進|台灣基進"
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q116894056"
},
"name": {
"xml:lang": "zh",
"type": "literal",
"value": "王興煥"
},
"births": {
"type": "literal",
"value": "1973-01-01T00:00:00Z/9"
},
"positions": {
"type": "literal",
"value": "台灣基進秘書長|台湾基进秘书长|台湾基进党主席"
},
"parties": {
"type": "literal",
"value": "台灣基進|台灣基進|台灣基進"
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q697458"
},
"name": {
"xml:lang": "zh-tw",
"type": "literal",
"value": "吳宗憲"
},
"births": {
"type": "literal",
"value": "1962-09-26T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q697458"
},
"name": {
"xml:lang": "zh-hant",
"type": "literal",
"value": "吳宗憲"
},
"births": {
"type": "literal",
"value": "1962-09-26T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q697458"
},
"name": {
"xml:lang": "zh",
"type": "literal",
"value": "吳宗憲"
},
"births": {
"type": "literal",
"value": "1962-09-26T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q9369618"
},
"name": {
"xml:lang": "zh-tw",
"type": "literal",
"value": "陳瑩"
},
"births": {
"type": "literal",
"value": "1976-10-16T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q9369618"
},
"name": {
"xml:lang": "zh-hant",
"type": "literal",
"value": "陳瑩"
},
"births": {
"type": "literal",
"value": "1976-10-16T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q9369618"
},
"name": {
"xml:lang": "zh",
"type": "literal",
"value": "陳瑩"
},
"births": {
"type": "literal",
"value": "1976-10-16T00:00:00Z/11"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q865"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q45405003"
},
"name": {
"xml:lang": "zh-hant",
"type": "literal",
"value": "陳瑩"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q7462"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q45405003"
},
"name": {
"xml:lang": "zh",
"type": "literal",
"value": "陳瑩"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q7462"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q45584156"
},
"name": {
"xml:lang": "zh-hant",
"type": "literal",
"value": "陳瑩"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q9903"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q45584156"
},
"name": {
"xml:lang": "zh",
"type": "literal",
"value": "陳瑩"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q9903"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q45608712"
},
"name": {
"xml:lang": "zh-hant",
"type": "literal",
"value": "陳瑩"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q9903"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q45608712"
},
"name": {
"xml:lang": "zh",
"type": "literal",
"value": "陳瑩"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q9903"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q45657305"
},
"name": {
"xml:lang": "zh-hant",
"type": "literal",
"value": "陳瑩"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q9903"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q45657305"
},
"name": {
"xml:lang": "zh",
"type": "literal",
"value": "陳瑩"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q9903"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q45696507"
},
"name": {
"xml:lang": "zh-hant",
"type": "literal",
"value": "陳瑩"
},
"births": {
"type": "literal",
"value": "1899-01-01T00:00:00Z/9"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q13426199"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q45696507"
},
"name": {
"xml:lang": "zh",
"type": "literal",
"value": "陳瑩"
},
"births": {
"type": "literal",
"value": "1899-01-01T00:00:00Z/9"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q13426199"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q47689971"
},
"name": {
"xml:lang": "zh",
"type": "literal",
"value": "吳宗憲"
},
"births": {
"type": "literal",
"value": "1961-01-01T00:00:00Z/9"
},
"positions": {
"type": "literal",
"value": ""
},
"parties": {
"type": "literal",
"value": ""
},
"countries": {
"type": "literal",
"value": "Q865"
}
}
]
}
}

View File

@ -1,138 +1,15 @@
"""2026 候選人名單與中選會選舉結果的解析。"""
"""中選會選舉結果的解析(歷屆參選人資料庫用)。"""
from __future__ import annotations
import json
from collections.abc import Iterator
import pytest
from election_data.people.candidates import (
COUNTY,
MUNICIPAL,
article_html,
parse_elcand,
parse_press_release,
to_claim,
)
from election_data.people.cec_results import ElectionSpec, candidate_totals, load_at_large, load_election
pytestmark = pytest.mark.unit
PRESS_BODY = (
"<p>中央選舉委員會今(16)日舉行委員會議…</p>"
"<p>一、直轄市長候選人部分:受理登記計3人,均符合規定:</p>"
"<p>(一)臺北市3人:郭璽、沈伯洋、蔣萬安。</p>"
"<p>二、縣(市)長候選人部分:受理登記計4人,均符合規定:</p>"
"<p>(一)新竹縣2人:鄭朝方、徐欣瑩。</p>"
"<p>(二)嘉義市2人:黃宏成台灣阿成世界偉人財神總統、張啓楷。</p>"
"<p>三、直轄市議員候選人部分:受理登記計610人…</p>"
"<p>(一)臺北市不符合規定者計1人:某某…</p>"
)
def _api(body: str) -> dict:
content = json.dumps({"content": [{"blockType": "Text", "content": body}]}, ensure_ascii=False)
return {"code": 0, "data": {"content": content, "beginTime": "20261016"}}
def test_parse_press_release() -> None:
body, date = article_html(_api(PRESS_BODY))
entries = parse_press_release(body, "cec")
assert date == "2026-10-16"
assert [(e.county, e.name, e.office) for e in entries][:2] == [
("臺北市", "郭璽", MUNICIPAL),
("臺北市", "沈伯洋", MUNICIPAL),
]
assert sum(e.office == COUNTY for e in entries) == 4
assert "某某" not in {e.name for e in entries} # 議員段落不算
def test_parse_press_release_count_mismatch_raises() -> None:
with pytest.raises(ValueError, match="應有 3 人"):
parse_press_release(PRESS_BODY.replace("郭璽、", ""), "cec")
def test_parse_press_release_total_mismatch_raises() -> None:
with pytest.raises(ValueError, match="候選人應有"):
parse_press_release(PRESS_BODY.replace("受理登記計4人", "受理登記計5人"), "cec")
def test_parse_elcand_and_claim() -> None:
elbase = [["63", "000", "00", "000", "0000", "臺北市"]]
elpaty = [["1", "中國國民黨"], ["999", "無黨籍及未經政黨推薦"]]
elcand = [
[
"63",
"000",
"00",
"000",
"0000",
"1",
"甲某",
"999",
"2",
"0650515",
"61",
"臺北市",
"博士",
"N",
"",
"",
],
[
"63",
"000",
"00",
"000",
"0000",
"2",
"乙某",
"1",
"1",
"0671226",
"47",
"臺北市",
"博士",
"Y",
"",
"",
],
[
"63",
"000",
"00",
"000",
"0000",
"2",
"副手某",
"1",
"1",
"0600101",
"66",
"臺北市",
"碩士",
"N",
"",
"Y",
],
]
entries = parse_elcand(elcand, elbase, elpaty, MUNICIPAL, "elcand")
assert [e.name for e in entries] == ["甲某", "乙某"]
first, second = entries
assert (first.party, first.party_known, first.gender, first.birth_date) == (None, True, "F", "1976-05-15")
assert (second.number, second.party) == (2, "中國國民黨")
claim = to_claim(second, "2026-11-12")
assert claim.positions[0].title == "臺北市長候選人(號次 2)"
assert claim.party and claim.party.value == "中國國民黨"
assert claim.birth_date and claim.birth_date.value == "1978-12-26"
def test_parse_elcand_unknown_county_raises() -> None:
row = ["99", "999", "00", "000", "0000", "1", "某", "1", "1", "0650515", "61", "", "", "N", "", ""]
with pytest.raises(ValueError):
parse_elcand([row], [], [], COUNTY, "x")
def _ctks(
prv: str, city: str, area: str, town: str, vil: str, station: str, no: str, votes: int

View File

@ -1,141 +0,0 @@
"""合併、選舉紀錄比對、更正的規則。"""
from __future__ import annotations
from dataclasses import replace
import pytest
from election_data.people.cec_results import CecResult
from election_data.people.enrich import CEC_SOURCE_ID, attach_name_only, attach_strong, index_results
from election_data.people.manual import Override
from election_data.people.merge import apply_overrides, merge_claims
from election_data.people.model import PersonClaim, PersonDraft, PositionRec, Sourced
pytestmark = pytest.mark.unit
def claim(name: str, role: str, county: str | None = None, **kw: object) -> PersonClaim:
category = "official" if role == "official" else "politician"
pos = PositionRec(role, "org", None, None, (role,))
return PersonClaim(
name=name, role=role, category=category, name_source=role, county=county, positions=(pos,), **kw
) # type: ignore[arg-type]
def result(
name: str, election: str, district: str, county: str | None, birth: str | None = None
) -> CecResult:
kind = "president" if district == "全國" else "mayor"
return CecResult(election, kind, district, county, name, "某黨", "M", birth, "碩士", 100, 0.5, True)
def test_candidate_merges_with_legislator_in_same_county() -> None:
persons, notes = merge_claims(
[
claim("張嘉郡", "legislator", "雲林縣", district="雲林縣第1選舉區"),
claim("張嘉郡", "candidate_2026", "雲林縣"),
]
)
assert len(persons) == 1
assert persons[0].roles == {"legislator", "candidate_2026"}
assert any(n.kind == "merged" for n in notes)
def test_same_name_in_different_counties_is_not_merged() -> None:
persons, notes = merge_claims(
[claim("王某", "mayor", "臺北市"), claim("王某", "candidate_2026", "高雄市")]
)
assert len(persons) == 2
assert [n.kind for n in notes] == ["not_merged"]
def test_two_current_legislators_with_same_name_stay_separate() -> None:
persons, _ = merge_claims([claim("林某", "legislator"), claim("林某", "legislator")])
assert len(persons) == 2
def test_departed_legislator_attaches_only_to_existing_person() -> None:
departed = replace(claim("洪某", "legislator"), current=False, gender=Sourced("M", ("ly",)))
persons, notes = merge_claims(
[claim("洪某", "official"), departed, replace(claim("黃某", "legislator"), current=False)]
)
assert len(persons) == 1
assert persons[0].gender and persons[0].gender.value == "M"
assert persons[0].roles == {"official"}
assert {n.kind for n in notes} == {"departed_attached", "departed_dropped"}
def test_party_conflict_is_reported_and_priority_kept() -> None:
persons, notes = merge_claims(
[
claim("甲", "mayor", "臺北市", party=Sourced("A黨", ("moi",))),
claim("甲", "party_chair", party=Sourced("B黨", ("yaml",))),
]
)
assert persons[0].party == Sourced("A黨", ("moi",))
assert any(n.kind == "conflict" for n in notes)
def test_apply_overrides() -> None:
persons, _ = merge_claims([claim("鍾某", "mayor", "苗栗縣", party=Sourced(None, ("moi",)))])
out, notes = apply_overrides(persons, [Override("鍾某", "party", "中國國民黨", "恢復黨籍", ("news",))])
assert out[0].party == Sourced("中國國民黨", ("news",))
missing, notes2 = apply_overrides(persons, [Override("不存在", "party", None, "", ("x",))])
assert missing == persons and notes2[0].kind == "override_missing"
def draft(name: str, counties: set[str] | None = None, birth: Sourced | None = None) -> PersonDraft:
return PersonDraft(
name=name,
category="politician",
roles=frozenset({"mayor"}),
name_sources=("x",),
counties=frozenset(counties or set()),
birth_date=birth,
)
def test_strong_match_by_county_adds_record_and_official_birth() -> None:
index = index_results([result("蔣某", "2022 直轄市長選舉", "臺北市", "臺北市", "1978-12-26")])
persons, notes, done = attach_strong([draft("蔣某", {"臺北市"})], index)
p = persons[0]
assert p.elections[0].election == "2022 直轄市長選舉" and p.elections[0].source_ids == (CEC_SOURCE_ID,)
assert p.birth_date == Sourced("1978-12-26", (CEC_SOURCE_ID,))
assert done[0] == {"2022 直轄市長選舉"} and notes[0].kind == "strong"
def test_strong_match_ambiguous_when_two_same_name_in_county() -> None:
rs = [
result("許某", "2024 立法委員選舉(區域)", "臺北市第1選舉區", "臺北市"),
result("許某", "2024 立法委員選舉(區域)", "臺北市第5選舉區", "臺北市"),
]
persons, notes, _ = attach_strong([draft("許某", {"臺北市"})], index_results(rs))
assert persons[0].elections == () and notes[0].kind == "ambiguous"
def test_strong_match_rejected_on_birth_conflict() -> None:
rs = [result("蔣某", "2022 直轄市長選舉", "臺北市", "臺北市", "1978-12-26")]
person = draft("蔣某", {"臺北市"}, Sourced("1980-01-01", ("cec-other",)))
persons, notes, _ = attach_strong([person], index_results(rs))
assert persons[0].elections == () and notes[0].kind == "conflict"
def test_name_only_requires_matching_birth() -> None:
rs = [result("賴某", "2024 總統副總統選舉", "全國", None, "1959-10-06")]
index = index_results(rs)
same, notes = attach_name_only([draft("賴某", birth=Sourced("1959-10-06", ("wikidata",)))], index, {})
assert same[0].elections and notes[0].kind == "name_only"
assert same[0].birth_date == Sourced("1959-10-06", (CEC_SOURCE_ID,)) # 官方資料取代 Wikidata
other, notes = attach_name_only([draft("賴某", birth=Sourced("1960-01-01", ("wikidata",)))], index, {})
assert other[0].elections == () and notes[0].kind == "different_birth"
unknown, notes = attach_name_only([draft("賴某")], index, {})
assert unknown[0].elections == () and notes[0].kind == "unverified"
def test_name_only_skips_elections_already_matched() -> None:
rs = [result("蔣某", "2022 直轄市長選舉", "臺北市", "臺北市", "1978-12-26")]
persons, notes = attach_name_only([draft("蔣某")], index_results(rs), {0: {"2022 直轄市長選舉"}})
assert persons[0].elections == () and notes == []

View File

@ -0,0 +1,32 @@
from __future__ import annotations
import pytest
from election_data.people.names import han_key, name_key, slug_name, wikidata_label_variants
pytestmark = pytest.mark.unit
def test_name_key_ignores_spacing_dots_and_case() -> None:
assert name_key("伍麗華 Saidhai.Tahovecahe") == name_key("伍麗華Saidhai‧Tahovecahe")
assert name_key("鄭天財 Sra‧Kacaw") == name_key("鄭天財Sra Kacaw") == "鄭天財srakacaw"
def test_name_key_folds_known_variants_but_slug_keeps_them() -> None:
assert name_key("張啓楷") == name_key("張啟楷")
assert name_key("李姸慧") == name_key("李妍慧")
assert slug_name("李姸慧") == "李姸慧"
def test_name_key_keeps_tai_characters_in_person_names() -> None:
assert "台灣" in name_key("黃宏成台灣阿成世界偉人財神總統")
def test_han_key_drops_romanized_indigenous_names() -> None:
assert han_key("伍麗華Saidhai‧Tahovecahe") == "伍麗華"
assert han_key("曾智勇 Ljaucu‧Zingrur") == "曾智勇"
def test_wikidata_label_variants_include_han_only_and_folded() -> None:
assert wikidata_label_variants("伍麗華Saidhai‧Tahovecahe") == ("伍麗華Saidhai‧Tahovecahe", "伍麗華")
assert wikidata_label_variants("李姸慧") == ("李姸慧", "李妍慧")

View File

@ -1,66 +0,0 @@
from __future__ import annotations
import pytest
from election_data.people.education import UNSPECIFIED, parse_education
from election_data.people.names import han_key, name_key, slug_name, wikidata_label_variants
pytestmark = pytest.mark.unit
def test_name_key_ignores_spacing_dots_and_case() -> None:
assert name_key("伍麗華 Saidhai.Tahovecahe") == name_key("伍麗華Saidhai‧Tahovecahe")
assert name_key("鄭天財 Sra‧Kacaw") == name_key("鄭天財Sra Kacaw") == "鄭天財srakacaw"
def test_name_key_folds_known_variants_but_slug_keeps_them() -> None:
assert name_key("張啓楷") == name_key("張啟楷")
assert name_key("李姸慧") == name_key("李妍慧")
assert slug_name("李姸慧") == "李姸慧"
def test_name_key_keeps_tai_characters_in_person_names() -> None:
assert "台灣" in name_key("黃宏成台灣阿成世界偉人財神總統")
def test_han_key_drops_romanized_indigenous_names() -> None:
assert han_key("伍麗華Saidhai‧Tahovecahe") == "伍麗華"
assert han_key("曾智勇 Ljaucu‧Zingrur") == "曾智勇"
def test_wikidata_label_variants_include_han_only_and_folded() -> None:
assert wikidata_label_variants("伍麗華Saidhai‧Tahovecahe") == ("伍麗華Saidhai‧Tahovecahe", "伍麗華")
assert wikidata_label_variants("李姸慧") == ("李姸慧", "李妍慧")
@pytest.mark.parametrize(
("text", "expected"),
[
("國立政治大學外交學系學士", [("學士", "國立政治大學外交學系")]),
("國立虎尾科技大學碩士學位", [("碩士", "國立虎尾科技大學")]),
("中興大學法律系畢業", [("學士", "中興大學法律系")]),
(
"法國巴黎第十大學政治、經濟、社會哲學博士候選人",
[("博士候選人", "法國巴黎第十大學政治、經濟、社會哲學")],
),
("屏東師範學院國民教育硏究所碩士(85年-87年)", [("碩士", "屏東師範學院國民教育硏究所")]),
("國立臺灣大學EMBA碩士班", [("碩士", "國立臺灣大學EMBA")]),
("國立政治大學新聞學系", [(UNSPECIFIED, "國立政治大學新聞學系")]),
(
"龜山國小、大有國中、武陵高中",
[("國小", "龜山國小"), ("國中", "大有國中"), ("高中職", "武陵高中")],
),
("嘉義大學管理碩士、", [("碩士", "嘉義大學管理")]),
("臺北縣立頂溪國小畢業", [("國小", "臺北縣立頂溪國小")]),
("屏東師專(73年-78年)", [("專科", "屏東師專")]),
("臺灣會計師高考及格", []),
("國立清華大學\t博士後研究", []),
],
)
def test_parse_education(text: str, expected: list[tuple[str, str | None]]) -> None:
assert parse_education(text) == expected
def test_parse_education_splits_semicolons_and_dedupes() -> None:
text = "東海大學社會工作學系學士;東海大學社會工作學系碩士;東海大學社會工作學系學士"
assert parse_education(text) == [("學士", "東海大學社會工作學系"), ("碩士", "東海大學社會工作學系")]

View File

@ -1,39 +0,0 @@
"""連網測試:確認官方來源的格式沒有改變(預設不執行:pytest -m network)。"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from election_data.people.cabinet import parse_members
from election_data.people.candidates import CEC_ARTICLE_API, article_html, parse_press_release
from election_data.people.catalog import EY_AGENCY_HEADS
from election_data.people.downloads import fetch
from election_data.people.legislators import LY_ID9_URL, load_ly_json, parse_legislators
from election_data.people.mayors import MOI_BASE, parse_list
pytestmark = pytest.mark.network
def test_ly_id9_live(tmp_path: Path) -> None:
result = fetch(LY_ID9_URL, tmp_path / "id9.json")
claims = parse_legislators(load_ly_json(result.path), "ly")
assert sum(c.current for c in claims) >= 100
def test_moi_county_mayors_live(tmp_path: Path) -> None:
result = fetch(MOI_BASE + "LocalOfficial.aspx?n=579&TYP=KND0005&PageSize=50", tmp_path / "moi.html")
assert len(parse_list(result.path.read_text(encoding="utf-8"))) == 16
def test_ey_agency_heads_live(tmp_path: Path) -> None:
result = fetch(EY_AGENCY_HEADS.url, tmp_path / "ey.html")
assert len(parse_members(result.path.read_text(encoding="utf-8"))) >= 20
def test_cec_candidates_live(tmp_path: Path) -> None:
result = fetch(CEC_ARTICLE_API, tmp_path / "cec.json")
body, _ = article_html(json.loads(result.path.read_text(encoding="utf-8")))
assert len(parse_press_release(body, "cec")) == 81

View File

@ -1,132 +0,0 @@
"""官方頁面解析:立法院 ID9、內政部地方公職人員、行政院內閣(使用存下來的小型頁面片段)。"""
from __future__ import annotations
import pytest
from election_data.people.cabinet import parse_leader, parse_members, roc_day, split_name_title
from election_data.people.legislators import (
AT_LARGE,
MOUNTAIN,
committees_in_session,
latest_session,
load_ly_json,
ly_date,
parse_district,
parse_legislators,
)
from election_data.people.mayors import parse_detail, parse_list, to_claim
from .conftest import FIXTURES, read_fixture
pytestmark = pytest.mark.unit
@pytest.mark.parametrize(
("area", "label", "county"),
[
("雲林縣第1選舉區", "雲林縣第1選舉區", "雲林縣"),
("台北市第10選舉區", "臺北市第10選舉區", "臺北市"),
("宜蘭縣選舉區", "宜蘭縣選舉區", "宜蘭縣"),
("全國不分區及僑居國外國民", AT_LARGE, None),
("山地原住民選舉區", MOUNTAIN, None),
],
)
def test_parse_district(area: str, label: str, county: str | None) -> None:
district = parse_district(area)
assert (district.label, district.county) == (label, county)
def test_parse_district_rejects_unknown() -> None:
with pytest.raises(ValueError):
parse_district("火星第1選舉區")
def test_ly_date() -> None:
assert ly_date("2024/02/01") == "2024-02-01"
assert ly_date("") is None
def test_committees_only_from_requested_session() -> None:
text = "第11屆第5會期:財政委員會;第11屆第6會期:內政委員會;第11屆第6會期:程序委員會;"
assert committees_in_session(text, 6) == ["內政委員會", "程序委員會"]
assert latest_session([{"committee": text}]) == 6
def test_parse_legislators_fixture() -> None:
claims = {c.name: c for c in parse_legislators(load_ly_json(FIXTURES / "ly_id9_sample.json"), "ly")}
ding = claims["丁學忠"]
assert ding.current and ding.gender and ding.gender.value == "M"
assert ding.county == "雲林縣" and ding.district == "雲林縣第1選舉區"
assert ding.party and ding.party.value == "中國國民黨"
assert ding.positions[0].start == "2024-02-01" and ding.positions[0].end is None
assert any(p.title.startswith("內政委員會委員") for p in ding.positions)
assert ding.education[0].degree == "碩士"
wu = claims["吳春城"]
assert not wu.current
assert wu.district == AT_LARGE and wu.county is None
assert wu.positions == wu.positions[:1] # 離職者不收委員會
assert wu.positions[0].end == "2025-02-27"
assert claims["伍麗華Saidhai‧Tahovecahe"].district == MOUNTAIN
assert claims["陳俊宇"].district == "宜蘭縣選舉區"
def test_moi_list_and_detail_fixture() -> None:
entries = parse_list(read_fixture("moi_list_sample.html"))
assert [e.name for e in entries] == ["高虹安", "陳福海", "王忠銘"]
kao, chen = entries[0], entries[1]
assert (kao.county, kao.org, kao.title, kao.party) == ("新竹市", "新竹市政府", "市長", "台灣民眾黨")
assert chen.party is None # 「無」= 無黨籍
assert kao.detail_url.startswith("https://www.moi.gov.tw/LocalOfficial_Content.aspx?")
detail = parse_detail(read_fixture("moi_detail_sample.html"))
assert detail.party == "台灣民眾黨" and detail.term == "111年度縣市長選舉"
assert detail.education[0] == "美國辛辛那提大學機械工程博士"
claim = to_claim(kao, detail, "moi")
assert claim.positions[0].title == "市長" and claim.positions[0].source_ids == ("moi",)
assert [e.degree for e in claim.education] == ["博士", "碩士", "學士", "高中職"]
chen_claim = to_claim(chen, None, "moi")
assert chen_claim.party and chen_claim.party.value is None and chen_claim.party.source_ids == ("moi",)
@pytest.mark.parametrize(
("text", "name", "title"),
[
("劉世芳部長", "劉世芳", "部長"),
("葉俊顯主任委員", "葉俊顯", "主任委員"),
("陳志民代理主任委員", "陳志民", "代理主任委員"),
("李姸慧代理委員長", "李姸慧", "代理委員長"),
("曾智勇 Ljaucu‧Zingrur 主任委員", "曾智勇 Ljaucu‧Zingrur", "主任委員"),
("陳淑姿主計長", "陳淑姿", "主計長"),
("張惇涵秘書長", "張惇涵", "秘書長"),
],
)
def test_split_name_title(text: str, name: str, title: str) -> None:
assert split_name_title(text) == (name, title)
def test_split_name_title_rejects_unknown_title() -> None:
with pytest.raises(ValueError):
split_name_title("某某顧問")
def test_parse_members_fixture() -> None:
members = parse_members(read_fixture("ey_agency_heads_sample.html"))
pairs = {(m.org, m.name, m.title) for m in members}
assert ("內政部", "劉世芳", "部長") in pairs
assert ("公平交易委員會", "陳志民", "代理主任委員") in pairs
assert ("中央銀行", "楊金龍", "總裁") in pairs
def test_parse_leader_fixture_skips_title_tag() -> None:
leader = parse_leader(read_fixture("ey_premier_sample.html"))
assert (leader.name, leader.title, leader.start) == ("卓榮泰", "院長", "2024-05-20")
assert leader.education == ("中興大學法律系畢業",)
def test_roc_day() -> None:
assert roc_day("民國113年5月20日-") == "2024-05-20"
assert roc_day("民國78年-87年") is None

View File

@ -1,198 +0,0 @@
"""Wikidata 比對、id 與輸出格式、手動 YAML。"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from election_data.config import CONFIG_DIR, PROTOCOL_VERSION
from election_data.people.manual import ManualDataError, load_manual, parse_party_chairs
from election_data.people.model import PersonDraft, PositionRec, Sourced
from election_data.people.output import assign_ids, people_file, referenced_source_ids
from election_data.people.wd_match import match_one, match_wikidata
from election_data.people.wikidata import WdItem, build_query, parse_bindings
from election_data.validate import validate
from .conftest import FIXTURES
pytestmark = pytest.mark.unit
def items() -> list[WdItem]:
return parse_bindings(json.loads((FIXTURES / "wikidata_sample.json").read_text(encoding="utf-8")))
def person(name: str, roles: set[str], **kw: object) -> PersonDraft:
category = "official" if roles <= {"official"} else "politician"
return PersonDraft(name=name, category=category, roles=frozenset(roles), name_sources=("x",), **kw) # type: ignore[arg-type]
def test_parse_bindings_merges_rows_per_qid_and_keeps_precision() -> None:
by_qid = {it.qid: it for it in items()}
assert {"Q124293468", "Q21055059", "Q697458"} <= by_qid.keys() # 多位吳宗憲
assert by_qid["Q116894056"].births == (("1973-01-01", 9),) # 王興煥只有年份
assert by_qid["Q116894056"].day_births() == frozenset()
assert "Q865" in by_qid["Q121904956"].countries
def test_match_uses_official_birth_to_pick_among_namesakes() -> None:
wu = person(
"吳宗憲",
{"legislator"},
districts=frozenset({"全國不分區及僑居國外國民"}),
party=Sourced("中國國民黨", ("ly",)),
birth_date=Sourced("1971-09-27", ("cec-votedata",)),
)
note = match_one(wu, [it for it in items() if "吳宗憲" in it.label_keys])
assert (note.kind, note.qid) == ("matched", "Q124293468")
def test_match_ambiguous_without_birth() -> None:
wu = person("吳宗憲", {"legislator"}, party=Sourced("中國國民黨", ("ly",)))
note = match_one(wu, [it for it in items() if "吳宗憲" in it.label_keys])
assert note.kind == "ambiguous" and note.qid is None
def test_birth_conflict_excludes_item() -> None:
p = person(
"丁學忠",
{"legislator"},
party=Sourced("中國國民黨", ("ly",)),
birth_date=Sourced("1999-01-01", ("cec",)),
)
note = match_one(p, [it for it in items() if "丁學忠" in it.label_keys])
assert note.kind == "unmatched" and "出生日期不符" in note.detail
def test_medium_rule_for_officials() -> None:
item = WdItem(
"Q1", frozenset({"某官員"}), (("1960-01-01", 11),), ("衛生福利部部長",), (), frozenset({"Q865"})
)
official = person(
"某官員", {"official"}, positions=(PositionRec("政務委員", "行政院", None, None, ("ey",)),)
)
assert match_one(official, [item]).kind == "matched_medium"
candidate = person("某官員", {"candidate_2026"}, counties=frozenset({"臺北市"}))
assert match_one(candidate, [item]).kind == "unmatched"
def test_duplicate_qid_is_dropped_and_wikidata_birth_filled() -> None:
item = WdItem("Q9", frozenset({"同名"}), (("1970-05-05", 11),), ("立法委員",), (), frozenset({"Q865"}))
a = person("同名", {"legislator"}, districts=frozenset({"臺北市第1選舉區"}))
out, notes = match_wikidata([a], [item])
assert out[0].wikidata_id == Sourced("Q9", ("wikidata",))
assert out[0].birth_date == Sourced("1970-05-05", ("wikidata",))
_, notes = match_wikidata([a, a], [item])
assert [n.kind for n in notes] == ["duplicate_qid", "duplicate_qid"]
def test_build_query_includes_label_variants_and_escapes() -> None:
q = build_query(["伍麗華Saidhai‧Tahovecahe", 'a"b'])
assert '"伍麗華"@zh-tw' in q and '"a\\"b"@zh' in q
def _draft(name: str, birth: str | None = None, qid: str | None = None) -> PersonDraft:
return PersonDraft(
name=name,
category="politician",
roles=frozenset({"candidate_2026"}),
name_sources=("cec",),
birth_date=Sourced(birth, ("cec",)) if birth else None,
wikidata_id=Sourced(qid, ("wikidata",)) if qid else None,
party=Sourced(None, ("moi",)),
positions=(PositionRec("臺北市長候選人", "115年直轄市長選舉", "2026-10-16", None, ("cec",)),),
)
def test_assign_ids_qid_slug_and_deterministic_suffix() -> None:
a, b, c = _draft("王 某", "1970-01-01"), _draft("王某", "1970-02-02"), _draft("李某", qid="Q42")
ids = assign_ids([a, b, c])
assert ids[2] == "Q42"
assert sorted(ids[:2]) == ["tw-politician-王某-1970", "tw-politician-王某-1970-2"]
assert assign_ids([b, a, c]) == [ids[1], ids[0], ids[2]]
assert assign_ids([_draft("李某")]) == ["tw-politician-李某-x"]
def test_people_file_validates_against_protocol_schema() -> None:
persons = [_draft("王某", "1970-01-01"), _draft("李某", qid="Q42")]
doc = people_file(persons, assign_ids(persons), PROTOCOL_VERSION, "2026-10-25")
validate(doc, "people.schema.json")
first = doc["people"][0]
assert first["stats"] == dict.fromkeys(first["stats"]) and first["scoring"] == []
assert first["fieldSources"]["party"] == ["moi"] # 已查證為無黨籍
assert referenced_source_ids(doc) == {"cec", "moi", "wikidata"}
def test_load_manual_config_files() -> None:
data = load_manual(CONFIG_DIR / "people")
chairs = [c for c in data.claims if c.role == "party_chair"]
assert {c.party.value for c in chairs if c.party} >= {
"民主進步黨",
"中國國民黨",
"台灣民眾黨",
"時代力量",
"台灣基進",
}
assert all(c.positions and c.positions[0].source_ids for c in data.claims)
assert {o.field for o in data.overrides} == {"party"}
assert all(s.retrieved_at and s.url.startswith("https://") for s in data.sources)
assert len({s.id for s in data.sources}) == len(data.sources)
@pytest.mark.parametrize(
"entry",
[
{"name": "某", "party": "某黨", "sources": []},
{
"name": "某",
"party": "某黨",
"sources": [
{
"id": "x",
"title": "t",
"agency": "a",
"url": "http://x",
"license": "l",
"retrievedAt": "2026-10-25",
}
],
},
{
"name": "某",
"party": "某黨",
"sources": [
{
"id": "x",
"title": "t",
"agency": "a",
"url": "https://x",
"license": "l",
"retrievedAt": "2026/10/25",
}
],
},
{
"party": "某黨",
"sources": [
{
"id": "x",
"title": "t",
"agency": "a",
"url": "https://x",
"license": "l",
"retrievedAt": "2026-10-25",
}
],
},
],
)
def test_party_chair_yaml_validation(entry: dict) -> None:
with pytest.raises(ManualDataError):
parse_party_chairs({"chairs": [entry]})
def test_missing_config_dir_is_empty(tmp_path: Path) -> None:
data = load_manual(tmp_path)
assert data.claims == () and data.overrides == () and data.sources == ()

View File

@ -1,206 +0,0 @@
from datetime import date
from pathlib import Path
import pytest
from election_data.scoring.derive import awareness, network
from election_data.scoring.evidence import record_evidence, render_packet, web_evidence
from election_data.scoring.llm import LlmResult, RefusedError
from election_data.scoring.pipeline import (
ScoringStats,
_aggregate,
bias_report,
score_person,
validate_scores,
write_outputs,
)
from election_data.scoring.rubric import AI_STATS, render_rubric
pytestmark = pytest.mark.unit
NULL_STATS = dict.fromkeys(
["awareness", "network", "affinity", "eloquence", "strategy", "online", "image", "wealth", "stamina"]
)
def person(pid: str = "tw-politician-甲-1970", party: str = "某黨", title: str = "立法委員") -> dict:
return {
"id": pid,
"kind": "real",
"category": "politician",
"name": "甲",
"gender": "F",
"birthDate": "1970-01-01",
"party": party,
"wikidataId": None,
"positions": [
{"title": title, "org": "立法院", "from": "2020-02-01", "to": None, "sourceIds": ["ly-id9"]}
],
"education": [{"degree": "碩士", "school": "某大學", "sourceIds": ["ly-id9"]}],
"electionHistory": [
{
"election": "2024 區域立委",
"district": "某選區",
"party": party,
"votes": 120_000,
"share": 0.52,
"elected": True,
"sourceIds": ["cec-votedata"],
}
],
"stats": dict(NULL_STATS),
"scoring": [],
"fieldSources": {"name": ["ly-id9"], "party": ["ly-id9"]},
"asOf": "2026-10-25",
}
def scores(value: int | None, cite: str = "R1", insufficient: bool = False) -> dict:
return {
"scores": [
{
"stat": s.key,
"insufficient": insufficient,
"value": value,
"confidence": "medium",
"rationale": "測試",
"citations": [cite],
}
for s in AI_STATS
]
}
class FakeBackend:
def __init__(self, values: list[int], research_items: list[dict] | None = None, cite: str = "W1") -> None:
self.values = list(values)
self.research_items = research_items or [
{
"claim": "曾於全國辯論中表現受肯定",
"url": "https://example.org/a",
"published": "2024-01",
"stats": [],
}
]
self.cite = cite
self.research_calls = 0
def research(self, person_summary: str, max_searches: int) -> LlmResult:
self.research_calls += 1
return LlmResult({"items": self.research_items}, "fake-model", 100, 50)
def score(self, packet: str) -> LlmResult:
assert "[R1]" in packet
return LlmResult(scores(self.values.pop(0), self.cite), "fake-model", 10, 5)
class TestDerive:
def test_vice_president_is_not_president(self) -> None:
vp = person(title="副總統")
p = person(title="總統")
assert awareness(vp)[0] == 95
assert awareness(p)[0] == 100
def test_votes_raise_awareness(self) -> None:
low = person(title="助理")
low["electionHistory"][0]["votes"] = 5_000_000
assert awareness(low)[0] == 70
def test_network_grows_with_tenure(self) -> None:
score, sources = network(person(), date(2026, 2, 1))
assert score == 30 + 18 # 6 年 × 3
assert sources == ["ly-id9"]
class TestEvidence:
def test_record_ids_and_sources(self) -> None:
items = record_evidence(person())
assert [i.id for i in items] == ["R1", "R2", "R3", "R4"]
assert items[-1].sources == ("cec-votedata",)
def test_packet_order_depends_on_seed(self) -> None:
items = record_evidence(person()) + web_evidence(
[{"claim": "x", "url": "https://e/1", "published": ""}]
)
assert render_packet(person(), items, 1) != render_packet(person(), items, 2)
class TestAggregate:
def test_median_of_cited_runs(self) -> None:
runs = [scores(60), scores(70), scores(64)]
value, method, cited, _, inconsistent = _aggregate("eloquence", runs, {"R1"})
assert (value, method, cited, inconsistent) == (64, "ai", ["R1"], False)
def test_uncited_scores_are_discarded(self) -> None:
runs = [scores(90, cite="X9"), scores(90, cite="X9"), scores(60)]
value, method, *_ = _aggregate("eloquence", runs, {"R1"})
assert (value, method) == (50, "default")
def test_insufficient_falls_back_to_default(self) -> None:
runs = [scores(None, insufficient=True)] * 3
assert _aggregate("image", runs, {"R1"})[:2] == (50, "default")
def test_spread_flags_inconsistency(self) -> None:
runs = [scores(40), scores(55), scores(70)]
assert _aggregate("image", runs, {"R1"})[4] is True
def test_out_of_range_rejected(self) -> None:
runs = [scores(150), scores(140), scores(60)]
assert _aggregate("image", runs, {"R1"})[1] == "default"
def test_rubric_mentions_every_stat() -> None:
text = render_rubric()
assert all(s.name in text for s in AI_STATS)
def test_validate_scores_rejects_bad_shape() -> None:
with pytest.raises(ValueError):
validate_scores({"scores": [{"stat": "eloquence"}]})
def test_score_person_end_to_end(tmp_path: Path) -> None:
backend = FakeBackend([60, 62, 75])
stats = ScoringStats()
out = score_person(person(), backend, stats, tmp_path, date(2026, 10, 25), use_web=True)
by_stat = {r["stat"]: r for r in out["scoring"]}
assert out["stats"]["eloquence"] == 62
assert by_stat["eloquence"]["citations"] == ["https://example.org/a"] # 引用展開成實際出處
assert by_stat["eloquence"]["confidence"] == "medium" # 60–75 差 15 分 → 不一致
assert by_stat["awareness"]["method"] == "derived"
assert by_stat["stamina"]["method"] == "default"
assert (tmp_path / f"{person()['id']}.json").exists() # 研究結果有快取
score_person(person(), FakeBackend([60, 60, 60]), stats, tmp_path, date(2026, 10, 25), use_web=True)
assert stats.people == 2
def test_refusal_is_recorded_not_raised(tmp_path: Path) -> None:
class Refusing(FakeBackend):
def score(self, packet: str) -> LlmResult:
raise RefusedError("cyber")
stats = ScoringStats()
out = score_person(person(), Refusing([]), stats, tmp_path, date(2026, 10, 25), use_web=False)
assert all(r["method"] != "ai" for r in out["scoring"])
assert len(stats.refusals) == 3
def test_bias_report_flags_party_gap() -> None:
people = []
for i in range(6):
for party, value in (("甲黨", 70), ("乙黨", 50)):
p = person(pid=f"{party}-{i}", party=party)
p["scoring"] = [{"stat": s.key, "value": value, "method": "ai"} for s in AI_STATS]
people.append(p)
lines = bias_report(people)
assert lines and all("需要複核" in line for line in lines)
def test_write_outputs_validates_against_protocol(tmp_path: Path) -> None:
backend = FakeBackend([60, 61, 62])
stats = ScoringStats()
scored = [score_person(person(), backend, stats, tmp_path, date(2026, 10, 25), use_web=True)]
out = write_outputs(tmp_path, {"protocolVersion": "1.0.0", "asOf": "2026-10-25"}, scored, stats)
assert out.exists()
assert (tmp_path / "review_sample.csv").exists()
assert "AI 評分報告" in (tmp_path / "scoring_report.md").read_text(encoding="utf-8")

View File

@ -1,9 +1,9 @@
# 10 資料來源與資料管線
> **2026-10-28 現況:** 管線(`data/pipeline`)實際下載與使用的是選舉(中選會)、人口(戶政)、宗教(內政部宮廟教會)、
> 地理(村里界)、社會經濟(主計、財政、客委會)、競選財務(監察院政治獻金)、人物(中選會、立法院、Wikidata)。
> 地理(村里界)、社會經濟(主計、財政、客委會)、競選財務(監察院政治獻金)、歷屆參選人(中選會)。
> 本文件的「氣象」「媒體使用」「政治態度(TEDS)」三節只是研究,管線沒有用到;選民群的年齡與傾向關聯用的是方案 B(生態推論)。
> 人物資料庫(`people.json`)與 AI 評分的產出目前沒有接進遊戲,遊戲用的是 `records.json` 的客觀資歷分數(docs/23)。
> 人物資料庫(Wikidata、立法院、內閣 → `people.json`)與 AI 評分沒有接進遊戲,2026-10-30 依使用者決定刪除;遊戲用的是 `records.json` 的客觀資歷分數(docs/23)。
> 本文件的資料集與法規已於 **2026-10-25** 逐一查證(實際下載或開啟官方頁面)。
> 「授權 1」指「政府資料開放授權條款第 1 版」。狀態欄:**確認**=已實際取得;**部分**=只取得部分或需要申請。
@ -159,15 +159,6 @@
| 民調機構 | 歷屆公開民調的發布者;各機構官網 | 機構效應需要歷屆民調數字,來源與授權要個別確認 |
| 村里長 | 內政部地方公職人員資訊專區(已確認,見上表) | |
### AI 評分的輸入資料
| 資料 | 來源 | 使用方式 |
|---|---|---|
| 結構化經歷 | 上述人物資料 | 直接使用 |
| 立法院質詢、發言紀錄 | 立法院開放資料 | 評估口才、議題 |
| 公開新聞報導 | 各媒體網站 | 只作為評分依據;遊戲內只顯示出處連結與摘要,不轉載全文(14)。擷取前確認各網站的使用條款 |
| 社群公開數據 | 追蹤數、互動數(人工或官方 API) | 評估網路魅力 |
## 代碼與串接
| 來源 | 代碼 | 轉換到主鍵 VILLCODE |
@ -270,7 +261,7 @@
格式見 `packages/protocol/src/area.ts`(`DataPackManifest`、`VillagesFile` 等)。另外產出:
- `people.json`:人物資料庫,每個欄位附出處與擷取日期
- `people/records.json`:歷屆參選人的選舉紀錄與客觀資歷分數(docs/23)
- `sources.json`:所有資料集的名稱、機關、版本、擷取日期、授權,給製作名單與遊戲內的資料來源頁使用
## 更新排程

View File

@ -26,7 +26,7 @@
| 頭像 | 卡通化的向量頭像(部件目錄,docs/24);不使用照片、不描摹單一照片;不用 AI 生成真人肖像 |
| 聲音 | 不合成真人聲音 |
| 客觀資料 | 只收錄可查證的公開資料,每個欄位附出處與擷取日期 |
| 能力分數 | 用客觀資歷(歷次參選、得票、任職)計算,每項附算法與出處(docs/23)。資料管線另有一套 AI 評分(rubric-v1.md),目前沒有接進遊戲 |
| 能力分數 | 用客觀資歷(歷次參選、得票、任職)計算,每項附算法與出處(docs/23)。不用 AI 評分(原本的評分管線 2026-10-30 刪除) |
| 負面事實 | 只收錄有確定判決或官方正式認定的事項 |
| 黑色行動 | 是**玩家的選擇**,不是對真人的描述。AI 控制的真實人物不使用奧步;栽贓、檢舉類新聞不點名真人犯罪 |
| 模擬新聞與民調 | 新聞台用諧音惡搞的台名(中夭、三粒、鄉民直播台),不用真實媒體的台標與商標。畫面上不標「遊戲模擬」(使用者 2026-10-26 決定,docs/18 第 41 項);資料來源寫在遊戲內的設定選單(政府資料開放授權條款要標示來源)、分享圖卡角落寫「選舉小鎮・選戰遊戲」 |
@ -93,7 +93,6 @@
- 個別資料集可能有不同條款,例如學術調查資料可能禁止重新散布原始資料,只能使用彙總結果。
維基百科的文字是姓名標示-相同方式分享授權,不直接複製其文字;結構化資料優先使用授權較寬的來源。
每個資料集的授權標註在 [10](10-data-sources.md)。
- AI 評分的輸入資料(新聞報導)只作為評分依據,遊戲內只顯示出處連結與摘要,不轉載全文。
- 地圖邊界資料同樣要標示來源。
## 遊戲分級

View File

@ -65,7 +65,7 @@
- **隔壁區**:造勢、宣傳車、宣傳車隊長會擴散到相鄰的區。相鄰由地圖拓撲算(共用邊界的區),總統選舉用縣市。
- **幕僚(32 位)**:地區型(客家事務主任、農會總幹事…)、牌型(宮廟通、造勢天王…)、規則型(開場哥:每週第一張牌 +50%;夜貓子:用掉最後一點體力的牌 +50%;行程秘書:體力 +1 但少抽一張;鐵票部隊:插旗的區對手行動減半…)。都是虛構職位,頭像用漫畫產生器。
- **對手性格**:組織戰(佈樁盾 ×1.4)、空戰(廣告 ×1.2)、後發制人(前期 ×0.92、每週成長 9%),依劇本的 AI 風格決定。
- **逆風 0–10**:贏了第 n 級開第 n+1 級。1 對手 +12%、2 起始資金 −40%、3 每週收入 −40%、4 選項只剩 2 個、5 開局多一張人情包袱、6 對手第 4 週起多一個行動、7 對手開局聲勢 2、8 你的牌 −8%、9 黑函加倍且壞事件變多、10 開局落後 3 個百分點。
- **逆風 0–10**(2026-10-30 重排,現行版本見 docs/26 第 4 節):贏了第 n 級開第 n+1 級。1 對手 +12%、2 起始資金 −40%、3 每週收入 −40%、4 選項只剩 2 個、5 開局多一張人情包袱、6 對手第 4 週起多一個行動、7 對手開局聲勢 2、8 你的牌 −8%、9 黑函加倍且壞事件變多、10 開局落後 3 個百分點。
- **成就(22 個)**:凍蒜、壓倒性勝利、驚險過關、逆轉勝、以小搏大、全區插旗、乾淨選戰、辯論三戰全勝、黑函零損失、四連拳、翻轉王、一張定江山、精實牌組、財源滾滾、滿編團隊、物資行常客、逆風高手、逆風傳說、每日一戰、國會新科、地方首長、登上大位。
- **當選判斷**:要贏過對手,也要贏過「其他候選人」裡最強的那一位(不是其他人的票加起來)。

View File

@ -0,0 +1,237 @@
# 26 選戰卡牌第四版:桌遊機制研究與平衡
> 2026-10-30。使用者要求:「研究遊戲機制,有什麼好玩、豐富且重要的基本玩法是一定必要的?現在的遊戲不夠好玩,
> 請仔細研究桌遊有什麼元素、夠不夠明顯;難度差距好像不是很大;每個設定的平衡,各方各面都要研究透徹然後修正。」
> 另外要求「遊戲中要可以存檔,然後回到最外層選單」。本文件記錄量測方法、發現的問題、改了什麼,以及改完的模擬結果。
## 1. 怎麼量
- 模擬玩家(`rogue/src/bots.ts`):「打得好」(greedy,看預估挑每點體力最划算的,會搶戰場、會加開行程)、
「隨手玩」(casual,照手牌順序打在推薦第一名,下一站看到什麼點什麼,錢很多才按加開行程)、只拿某一派牌的玩家。
- 量測腳本(不進 repo):每週領先、領先換手次數、第幾週就定勝負、各來源的票(出牌、對手週末、劇情、下一站)、
剩下的體力與手牌、聲勢、插旗、資金流向、決策接近度(第二好的選項是最好的幾成)、每張牌每點體力的票、每條對手規則的影響。
- **貼近實際的設定**:真實候選人一定有類型(`archetype`),對手的 AI 風格依劇本(全部 1,010 位候選人裡空戰 583、平衡 210、組織 217)。
舊的平衡報告用沒有類型、對手剛好不是空戰的桃園,低估了大多數人實際遇到的難度。第 6 節的數字都是「你和對手的類型隨機、對手風格照實際比例」。
## 2. 好玩的桌遊/牌組構築一定要有的元素
| 元素 | 參考 | 改之前 | 證據 | 改之後 |
|---|---|---|---|---|
| 有意義的取捨(不能只是算數) | 《殺戮尖塔》擋或打 | 弱:每張牌的票數都算好,挑最大的就對 | 「打得好」標準難度勝率 99%;第二好的選項 ≥ 最好的九成只有 31% | 戰場、加開行程、搶版面讓同一點體力有不同用途;難選的比例 38–40% |
| 第二種資源要緊 | 《璀璨寶石》、《小丑牌》的錢 | 沒有:錢花不完 | 起始資金 300 萬和 4,000 萬,勝率幾乎一樣;每局最後剩 1,400–2,900 萬 | 加開行程(錢換體力);起始資金壓到 500–1,000 萬 |
| 地圖上要搶的地方 | 《冷戰熱鬥》關鍵國、《1960》搖擺州、《El Grande》 | 弱:只比總票數,插旗 8 個百分點太遠 | 每局從對手手上翻區 0.1–0.5 次 | 本週戰場:每週一區,週末淨增多的贏,贏了聲勢 +1、多抽一張 |
| 對手會反擊、有互動 | 《殺戮尖塔》的意圖 | 一半:意圖看得到,但電視、網路廣告擋不住 | 空戰風格的對手讓「打得好」從 95–99% 掉到 66% | 打對台可以搶廣告的版面;造勢被打對台壓過一半就冷場(不加聲勢) |
| 緊張到最後 | 各種賽跑遊戲的追趕機制 | 沒有:會打的人第 1 週領先就一路領先 | 「第 3 週就定勝負」99%,領先換手 0.07 次 | 對手落後 3 個百分點以上急起直追;大絕招落後時真的集得滿 |
| 逆轉的工具 | 《黑帝斯》、瑪利歐賽車 | 有做但用不到 | 大絕招每局 0.00 次(落後 1 點每週只集 8%) | 落後 1 點每週集 15%;落後的局平均 0.3–1 次 |
| 一級一級的難度 | 《殺戮尖塔》進階 | 不平均 | 逆風 0–4 會打的人都 96–99%,5、6 級突然掉 | 每一級都看得出差別(見第 6 節) |
| 組成流派會變強 | 《小丑牌》、《怪物火車》 | 空戰派弱 | 只拿空戰牌比混打少 12–15 個百分點 | 聲量也加成地面牌、常用空戰牌 +7%、媒體焦點 |
| 規則看得到 | 所有桌遊 | 部分 | 旗數、聲勢很小;對手的劣勢、規則只寫在小字 | 戰場比數浮在地圖、加開按鈕在體力旁、急起直追寫在對手面板 |
| 隨時能停、下次接著玩 | 手機遊戲 | 進度有存,但遊戲畫面沒有離開的按鈕 | — | 「存檔離開」:等送出中的請求回來再回首頁,首頁「繼續選戰」接著打 |
## 3. 新機制
### 3a 本週戰場(`rogue/src/battle.ts`)
- 每週開始挑一區:至少佔全市 3% 的人、差距在 12 個百分點內的越接近越容易被挑中,不連續兩週同一區(新手教學沒有)。
- 對手第一個在某一區拉票的行動(掃街、到你的票倉拉票)一定打在戰場,×1.5(造勢本來就大,不加倍);行動名稱加「(搶戰場)」。
- 週末對手出手之後,這週雙方在那區淨增的票誰多誰贏:你贏聲勢 +1、下週多抽 1 張;對手贏,對手聲勢 +1。
- 媒體焦點:全市的牌與廣告(雙方都一樣),戰場分到的比例 ×2,空戰牌也能搶戰場。
- 畫面:地圖左下角一直有比數(你淨增 vs 對手預計淨增、還差幾票),地圖標交叉的劍,區列表標「本週戰場」,週末結算寫輸贏。
### 3b 加開行程(`rules.ts rush`、`POST /api/rogue/runs/:id/rush`)
- 每週一次,花 250 萬換 1 點體力(財務型八折;逆風「資金吃緊」貴 100 萬)。按鈕在體力旁邊。
- 起始資金(`setup.ts startingMoney`):真實經費原本從 300 萬到上億都有,現在壓到 500–1,000 萬(經費每多一倍 +120 萬)。
### 3c 對手急起直追(`rival.ts rivalCatchUp`)
第 3 週起,對手落後 3 個百分點以上多 1 個行動,6 個百分點以上多 2 個。寫在對手行動面板最上面。
### 3d 其他規則
- 打對台可以對電視、網路廣告出手(搶版面:廣告剩四成,你全市加票)。
- 對手的造勢被打對台壓到一半以下就冷場,對手聲勢不漲。
- 擴散不看鄰區數:造勢、宣傳車擴散出去的合計固定(平均分給隔壁區),隔壁區不夠的(離島)留在本區當人潮。
原本鄰區越多擴散越多,台南(平均 4.9 個鄰區)比連江(0 個)簡單很多。
- 勢均力敵:其他候選人裡最強的一位最多到你們的八成五(連江縣玩李問時,曹爾元原本比雙方都強)。
- 大絕招:落後 1 個百分點每週集 15%(原本 8%),領先每週 4%。
- 區的大小係數(人多 ×1.4、人少 ×0.6)開局時再除以「依人口加權的平均」:總統(新北 230 萬、連江 8 千)、台南這種大區特別大的地圖,
原本平均每張牌多約兩成(對手的電視、網路廣告沒有這個加成),現在每張地圖平均都是 1 倍。
- 對手規模依區數調整(`rival.ts rivalSize`):區越多你越容易挑到有地區特色加成的區,對手沒有;1 區 ×0.88、2 區 ×0.91、6 區 ×0.97、12 區 ×1、22 區 ×1.04、37 區 ×1.07。
- 只有一區的選區(立委選區有 18 個):整張地圖就是同一區,沒有本命區、沒有本週戰場(原本整張地圖都是你的本命區、每週都贏戰場,隨手玩 60–70%)。
- 總統大選:對手全國動員,強 5%(政治生涯的最後一關原本比縣市長還簡單)。
- **逐張地圖校準**(`rogue/src/calibration.ts`、`apps/sim/src/rogue-calibrate.ts`):上面的規則修掉了有共通原因的差距,剩下的是每張地圖自己的地理
(例如台南偏簡單、台中偏難,區數、特色密度、相鄰都解釋不了)。用「隨手玩」把 219 張勢均力敵地圖、每位主要候選人都跑過,
對手強度乘上每張地圖的係數,讓平均差距接近同一個目標(−0.3 個百分點,勝率四成多)。真實底盤版共用同一個係數。
每張地圖幾十局的雜訊(約 ±0.4)和地圖之間的差距差不多大,所以分兩輪、每輪只修正一部分,最後用沒用來校準的亂數種子驗證。
新增或更新劇本之後重跑:`node src/rogue-calibrate.ts --seeds 30 --shard k/6 --out out/calib-k.jsonl`(六份平行),再 `--write out/calib-*.jsonl`。
- 模擬工具(`apps/sim/src/world.ts`)載入劇本改得和伺服器一樣:總統合成 22 個縣市、立委只取選區內的村里(原本模擬用的是 368 個鄉鎮和整個縣)。
## 4. 逆風階梯(`mechanics.ts ASC_RULES`)
一級加一條,規則裡用 `ascOn(s, id)` 查,不寫死級數:
| 級 | 內容 |
|---|---|
| 1 | 對手強度 +5% |
| 2 | 資金吃緊:起始資金 −40%、每週收入 −40%,加開行程貴 100 萬 |
| 3 | 對手開局多一條規則,後勁更強(每週變強的幅度 ×1.2) |
| 4 | 下一站只有 2 個選項,選牌、選幕僚也只有 2 個 |
| 5 | 對手開局聲勢 2;開局牌組多一張「人情包袱」 |
| 6 | 對手全力搶戰場:在戰場的掃街、拉票 ×1.7 |
| 7 | 最後一週(選前之夜)對手多 1 個行動 |
| 8 | 你的牌效果 −5% |
| 9 | 負面選戰:對手的批評 +30%,黑函危機加倍、沒回應記者追問的掉票加倍,壞事件更常出現 |
| 10 | 開局落後 2.5 個百分點 |
## 5. 各項設定的調整
| 設定 | 問題(量到的) | 改法 |
|---|---|---|
| 對手基礎強度 | 加了加開行程、戰場、擴散之後重新校準 | `RIVAL_POWER` 0.92 → 1.07 |
| 對手風格:空戰 | 最常見,卻最難(擋不住) | 廣告 ×1.2 拿掉、出廣告的比例調低;對手電視 4,830 → 4,140、網路 2,990 → 2,760 |
| 對手規則:大打空戰 | 會打的人勝率 −38 個百分點 | 第 2 週起、多出來的廣告只有一般的四成 |
| 對手規則:地毯式掃街 | −1.5 個百分點 | 擴散合計兩成(不看鄰區數) |
| 對手規則:形象牌 | 反而對玩家有利(辯論贏的回合多 50%) | 改成辯論輸的回合你掉的票多 50% |
| 對手規則:地方大老 | 翻區很少發生,等於沒作用 | 對手插旗的區,對手行動 +15% |
| 對手規則:鐵票區 | 影響很小 | 自動樁腳 ×1.5 |
| 類型:黑馬型 | 戰場讓聲勢變多,太強 | 每點聲勢 +12% → +10% |
| 類型:財務型 | 錢有用之後很強;隨手玩又最弱 | 開局專屬牌從多一張募款餐會改成電視廣告(取代掃街);拿掉「手上的錢自動換票」;加開行程八折 |
| 類型:組織型 | 隨手玩最強(不用想就有效) | 拿掉本命區自動樁腳,保留每週第一張佈樁不花體力 |
| 類型:資深型 | 最弱(開局專屬牌「政策白皮書」只有全市 1,150 票) | 開局專屬牌改成政見發表會;記者會類 +20% → +30%;年輕人多的區 −10% → −5% |
| 類型:清廉型 | 偏弱 | 加「對手的批評 −25%」 |
| 流派:空戰 | 比混打少 12–15 個百分點 | 聲量滾雪球每點也讓其他牌 +3%;媒體企劃改成所有空戰牌 +30%;網路廣告、長輩群組、廣播、政見發表會 +7% |
| 流派:攻防 | 偏弱 | 造勢冷場、打對台搶版面 |
## 6. 改完的結果
(模擬:桃園 2022 勢均力敵,兩位候選人,你和對手的類型隨機、對手風格照實際比例。)
### 逆風階梯(每格 160 局)
| 逆風 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 打得好(改前) | 99% | 98% | 97% | 96% | 97% | 88% | 68% | 64% | 51% | 50% | 27% |
| 打得好(改後) | 95% | 92% | 83% | 76% | 67% | 56% | 41% | 40% | 24% | 21% | 21% |
| 隨手玩(改後) | 43% | 31% | 22% | 12% | 13% | 8% | 8% | 5% | 3% | 1% | 1% |
平均差距(打得好):+3.2、+2.9、+2.1、+1.7、+1.0、+0.3、−0.3、−0.7、−1.4、−1.7、−2.3,每升一級少 0.3–0.9 個百分點。
加上逐張地圖校準、對手照桃園劇本自己的風格(玩家實際遇到的):
| 逆風 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 打得好 | 92% | 91% | 79% | 69% | 64% | 49% | 44% | 34% | 31% | 18% | 22% |
| 隨手玩 | 40% | 26% | 18% | 11% | 12% | 6% | 5% | 3% | 2% | 1% | 0% |
改前的數字是沒有類型、對手不是空戰的舊報告(docs/25);用實際比例算,改前其實更難而且更不平均。
### 緊張度(標準難度)
| | 改前 | 改後 |
|---|---|---|
| 打得好:第 3 週就定勝負 | 99% | 93%(逆風 5:47%) |
| 打得好:最後差距 | +7.9 | +3.2 |
| 打得好、逆風 5:第 4 週落後還逆轉 | — | 29% |
| 隨手玩:領先換手(次/局) | 1.0 | 0.8 |
| 第二好的選項 ≥ 最好的九成(難選) | 31% | 42% |
| 每局出牌 | 25 張 | 32 張(加開行程) |
| 每局最後剩資金 | 1,400–2,900 萬 | 500–900 萬 |
| 本週戰場(贏幾週/8) | — | 打得好 5.8、隨手玩 2.1 |
## 7. 最後一輪驗證(各項設定)
全部用最終版規則;你和對手的類型隨機、對手風格照實際比例。
### 六種類型(每格 80 局)
| 類型 | 打得好 逆風 0 | 打得好 逆風 5 | 隨手玩 逆風 0 | 隨手玩 逆風 5 |
|---|---:|---:|---:|---:|
| 媒體型 | 94% | 54% | 41% | 3% |
| 組織型 | 96% | 60% | 46% | 13% |
| 資深型 | 90% | 46% | 55% | 8% |
| 財務型 | 98% | 50% | 45% | 13% |
| 清廉型 | 94% | 41% | 44% | 6% |
| 黑馬型 | 93% | 55% | 36% | 15% |
改之前(同樣的設定):逆風 5 打得好 43–62%、隨手玩標準難度 22–63%(組織型最強、財務型最弱)。
### 流派(打得好,逆風 5,每格 100 局)
混打 49%、只拿地面牌 48%、只拿攻防牌 45%、只拿空戰牌 38%(第一次量:地面 60%、攻防 46%、空戰 43%、混打 57%;舊報告的空戰比混打少 12–13)。
### 對手
- 風格(桃園,標準難度,打得好/隨手玩):平衡 96%/54%、組織 100%/50%、空戰 93%/31%。改之前空戰是 66%/13%。
- 規則(打得好,逆風 4,和平均的差):原本大打空戰 −3.7、形象牌 +1.7(反而有利);改完後各條在 −1.6~+0.9 個百分點之間。
### 地圖(標準難度,打得好/隨手玩)
所有 `-even` 劇本依區數分布:1 區 18 個、2 區 36 個、3–7 區 77 個、8–13 區 44 個、14 區以上 44 個。每種大小都抽了幾張:
| 地圖(區數、平均鄰區) | 第一次量 | 最終 |
|---|---|---|
| 立委:臺北第 6 區(1) | 80%/70% | 87%/37% |
| 立委:高雄第 7 區(1) | 85%/60% | 90%/45% |
| 立委:新北第 3 區(1) | — | 90%/43% |
| 立委:嘉義市(2) | — | 92%/58% |
| 立委:臺北第 2 區(2) | — | 90%/60% |
| 新竹市(3、2.0) | 63%/17% | 95%/60% |
| 立委:彰化第 2 區(3) | — | 88%/47% |
| 連江縣(4、0) | 39%/11% | 89%/49% |
| 金門縣(6、1.0) | 27%/7% | 97%/47% |
| 澎湖縣(6、1.0) | 82%/27% | 96%/54% |
| 宜蘭縣(12、4.2) | 98%/40% | 90%/46% |
| 臺北市(12、4.0) | 92%/43% | 98%/50% |
| 桃園市(13、3.7) | 92%/41% | 93%/53% |
| 彰化縣(26、4.6) | — | 95%/48% |
| 臺中市(29、4.7) | — | 90%/38% |
| 臺南市(37、4.9) | 98%/57% | 98%/62% |
| 高雄市(38、4.2) | — | 92%/50% |
| 總統 2024(22 縣市、3.0) | 98%/76% | 98%/48% |
(「第一次量」:已經有戰場、加開行程,但還沒修空戰對手、擴散、勢均力敵、區的大小係數與區數;對手風格用劇本自己的。
每格 50–80 局,差 ±7 個百分點以內算雜訊。台南多次量測都在 56–66%,地區特色密度和高雄差不多但高雄是 50%,算是這張地圖本身的地理;台中偏難(38–45%)也是。
3–7 區以上幾格是區數係數最後一次調整之前量的,影響在雜訊內。)
### 逐張地圖校準(全部 219 張勢均力敵地圖)
| 輪 | 亂數種子 | 每張局數 | 隨手玩的平均差距:中位數 | 地圖之間的標準差 | 扣掉雜訊 | 最難~最簡單 |
|---|---|---:|---:|---:|---:|---|
| 校準前 | 9000– | 30 | +0.39 | 0.57 | 約 0.35 | −1.31~+1.69 |
| 第一輪係數之後 | 20000– | 60 | −0.07 | 0.42 | 約 0.27 | −1.64~+0.74 |
| 第二輪係數之後(驗證) | 40000– | 37 | −0.01 | 0.37 | 量不出來(雜訊 0.41) | −1.09~+0.86 |
驗證輪用的是沒用來校準的種子:地圖之間剩下的差距已經比每張地圖自己的雜訊小,219 張裡 212 張在中位數 ±0.8 個百分點內。
之後整張表再乘 1.026,把中位數從 −0.01 移到目標 −0.3(係數 0.94–1.16,平均 1.07)。
校準後抽查(對手照劇本自己的風格,每格 60 局,打得好/隨手玩):
| 地圖 | 校準前(混合對手風格) | 校準後 |
|---|---|---|
| 臺南市(37) | 98%/62% | 90%/42% |
| 臺中市(29) | 90%/38% | 90%/40% |
| 總統 2024 | 98%/48% | 92%/47% |
| 立委:臺北第 6 區(1) | 87%/37% | 83%/47% |
| 連江縣(4) | 89%/49% | 97%/49% |
| 新竹市(3) | 95%/60% | 95%/57% |
| 金門縣(6) | 97%/47% | 87%/43% |
| 立委:嘉義市(2) | 92%/58% | 87%/60% |
隨手玩的平均差距都在 −0.75~+0.08 之間(每格雜訊約 ±0.3)。
### 政治生涯
- 里長、議員(`career-balance`,臺北、高雄、彰化、花蓮 × 三種政黨,隨手玩/打得好):里長 73–93%/100%(docs/23:第一關刻意簡單)、議員 30–57%/85–98%。
- 立委、縣市長(`party-balance`,照真實底盤、最多落後 10 個百分點、逆風 2、能力 Lv 5):打得好平均 64–81%(大黨 81%、民眾黨 71%、小黨與無黨籍 64%;docs/23 原本 55–64%),
隨手玩 4–27%。生涯後段本來就照真實選情、可能落後起跑,維持原設計。
### 新手教學
隨手玩 98%、打得好 99%、亂出牌 69%、什麼都不做 0%(原本 96%/—/75%/0%)。
## 8. 之後可以做
- 平板直放(768 寬)要捲動才看得到手牌;手機橫放時政策島、參選人頁內容區較小。
- 新增或更新劇本、調整規則之後,要重跑逐張地圖校準(第 3d 節的指令),不然各地圖的難度會再散開。
- 戰場目前只用聲勢獎勵;之後可以加「連贏三週」的額外獎勵,讓中段更有起伏。

View File

@ -57,9 +57,10 @@ backend/packages ──► backend/apps/server(Fastify,REST /api)──►
| `rules.ts` | `createRun`、`endWeek`、`choose`、`ultimate`,以及從 `cards.ts` 轉出的 `playCard`:每個動作回傳新的狀態 |
| `state.ts` | `RunState`、`TOTAL_WEEKS = 8`、存檔版本 `SAVE_VERSION` 與 `migrateRun` |
| `data.ts`、`cards.ts` | 牌的資料與效果 |
| `rival.ts` | 對手每週的意圖與行動;每局抽的對手規則(docs/25) |
| `rival.ts` | 對手每週的意圖與行動;每局抽的對手規則(docs/25);落後時急起直追(docs/26) |
| `battle.ts` | 本週戰場:每週要搶的一區(docs/26) |
| `route.ts`、`scenes.ts`、`content.ts` | 每週結束的「下一站」(含地方派系談判、下下週的門)、辯論/民調/黑函週(週次每局隨機)、堵麥與地方抉擇 |
| `advisors.ts`、`feats.ts`、`meta.ts`、`ultimate.ts`、`mechanics.ts` | 幕僚、成就、生涯能力與政策、大絕招、逆風等級 |
| `advisors.ts`、`feats.ts`、`meta.ts`、`ultimate.ts`、`mechanics.ts` | 幕僚、成就、生涯能力與政策、大絕招、逆風等級(`ASC_RULES`,docs/26) |
| `view.ts` | 給前端的玩家視角(含每張手牌打在每一區的預估) |
| `tutorial.ts`、`bots.ts` | 新手教學;模擬玩家(平衡報告用) |
@ -119,7 +120,6 @@ backend/packages ──► backend/apps/server(Fastify,REST /api)──►
| `records` | 歷屆參選人與資歷分數、議員選區 |
| `parties` | 歷屆政黨清單(也寫 `protocol/src/parties.ts`) |
| `python -m election_data.genders` | 候選人性別(給頭像) |
| `python -m election_data.people`、`.scoring` | 人物資料庫與 AI 評分(rubric-v1)。**目前遊戲沒有用到這兩份產出** |
資料來源與授權見 docs/10;每個資料包的 `sources.json` 列出來源、版本與擷取日期。
@ -152,5 +152,5 @@ cd backend/data/pipeline && .venv/bin/pytest && .venv/bin/ruff check src tests
| [23-career-and-meta.md](23-career-and-meta.md) | 政治生涯、政策島、小遊戲、歷屆參選人與資歷分數 |
| [24-avatar-shop-plan.md](24-avatar-shop-plan.md) | 紙娃娃部件目錄、畫風、服裝店;附開放真錢前的法規整理 |
| [25-gameplay-v3.md](25-gameplay-v3.md) | 選戰卡牌第三版:本命區、類型技能、完成度(已做);流派、對手規則、隨機行事曆、難度(規格) |
| [rubric-v1.md](rubric-v1.md) | AI 評分規則(由評分管線產生) |
| [26-gameplay-v4.md](26-gameplay-v4.md) | 選戰卡牌第四版:桌遊機制研究、本週戰場、加開行程、急起直追、逆風階梯重排、各項設定的平衡 |
| [appendix-1994-original.md](appendix-1994-original.md) | 1994 年原作《臺灣模擬選戰》的拆解紀錄 |

View File

@ -1,82 +0,0 @@
# 人物評分規則 v1
## 共通規則
1. 分數以全台灣的政治人物與公眾人物為比較基準,50 分代表一般水準。
2. 每個分數都必須引用證據清單中的編號;沒有證據支持時,回報資料不足(insufficient),不要猜。
3. 只使用與其公開角色相關的公開資訊。不考慮私生活、家人、外貌。
4. 政黨、政治立場不是評分因素;同樣的表現不論政黨都給同樣的分數。
5. 爭議中、尚未定案的指控不能作為扣分依據;只有確定判決或官方正式認定的事項可以。
6. 理由用繁體中文寫一到兩句,直接說明依據,不超過 120 字。
## 親和力(affinity)
與一般民眾互動的溫度與接地氣程度,包括基層走訪、服務案件、與選民面對面的互動。
| 分數 | 描述 |
|---|---|
| 80–100 | 長期以基層經營著稱,親民形象被多家媒體反覆報導 |
| 60–79 | 有穩定、可查的地方走訪或服務紀錄 |
| 40–59 | 一般;公開資料沒有特別突出的正面或負面紀錄 |
| 20–39 | 公開報導多描述其距離感,基層互動紀錄少 |
| 0–19 | 多次因對待民眾的態度引發廣泛的公開批評 |
## 口才(eloquence)
辯論、質詢、受訪、演講的表達能力與臨場反應。
| 分數 | 描述 |
|---|---|
| 80–100 | 在全國性辯論、質詢或重大記者會中的表現被廣泛報導為出色 |
| 60–79 | 公開發言條理清楚,有可查的良好表現紀錄 |
| 40–59 | 一般 |
| 20–39 | 公開發言常被報導為不清楚或失準 |
| 0–19 | 多次重大失言並造成廣泛負面報導 |
## 謀略(strategy)
選戰操盤、議程設定、協商與組織動員的成效。
| 分數 | 描述 |
|---|---|
| 80–100 | 多次在困難選情中勝選,或主導重大政治協商、法案、組織改造成功 |
| 60–79 | 有可查的成功選戰或協商紀錄 |
| 40–59 | 一般 |
| 20–39 | 公開紀錄中策略失誤多於成功 |
| 0–19 | 多次重大策略失誤並被廣泛報導 |
## 網路魅力(online)
社群平台的經營成效與網路聲量,以公開的追蹤數與互動情形為主要依據。
| 分數 | 描述 |
|---|---|
| 80–100 | 主要平台追蹤數居全國政治人物前列,經常產生大量互動 |
| 60–79 | 追蹤數與互動在同層級公職中屬前段 |
| 40–59 | 一般 |
| 20–39 | 社群經營有限 |
| 0–19 | 幾乎沒有經營社群,或網路聲量以負面為主 |
## 形象(image)
公眾對其清廉、專業、可信度的整體觀感,以公開民調的好感度、信任度為主要依據。
| 分數 | 描述 |
|---|---|
| 80–100 | 公開民調的好感或信任度長期居前段 |
| 60–79 | 好感度高於同層級平均 |
| 40–59 | 一般或資料不足以判斷高低 |
| 20–39 | 好感度明顯低於同層級平均 |
| 0–19 | 長期居於各項民調的末段 |
## 財力(wealth)
個人可動用的財務資源,以公開的財產申報與公開報導為依據。
| 分數 | 描述 |
|---|---|
| 80–100 | 公開申報或報導顯示資產規模在政治人物中居前段 |
| 60–79 | 高於同層級平均 |
| 40–59 | 一般或資料不足 |
| 20–39 | 低於同層級平均 |
| 0–19 | 公開資料顯示資源非常有限 |

View File

@ -5,7 +5,7 @@ import { TAOYUAN_2022_FINANCE, financeFromIncome } from "../finance.ts";
* 歷史劇本:2022 桃園市長選舉重演(M1 回測用,docs/13)。
* 資料包只用 2022-11-26 以前的選舉估算政黨傾向,玩家看到的「上一次選舉」是 2020 總統大選,不會先看到答案。
* 號次與政黨取自中選會 votedata(2022-111年地方公職人員選舉/C1)。
* 候選人能力值是遊戲用的初始設定,不是對真人的評價;AI 評分完成後改用評分結果(docs/16)。
* 候選人能力值是遊戲用的初始設定,不是對真人的評價;選戰卡牌的類型改用中選會紀錄算的客觀資歷(docs/23、25)。
*/
const WEEKS = 10;

View File

@ -13,7 +13,6 @@ import {
CreateMatchResponse,
DataPackManifest,
HistoryFile,
PeopleFile,
PlayerView,
ScenarioSummary,
SourceList,
@ -34,7 +33,6 @@ const schemas: Record<string, z.ZodType> = {
"cells.schema.json": CellsFile,
"history.schema.json": HistoryFile,
"sources.schema.json": SourceList,
"people.schema.json": PeopleFile,
"player-view.schema.json": PlayerView,
"turn-submission.schema.json": TurnSubmission,
"scenario-summary.schema.json": ScenarioSummary,

View File

@ -1,6 +1,5 @@
export * from "./common.ts";
export * from "./area.ts";
export * from "./people.ts";
export * from "./game.ts";
export * from "./scenario.ts";
export * from "./rogue.ts";

View File

@ -1,103 +0,0 @@
import { z } from "zod";
import { IsoDate } from "./common.ts";
/** 人物類別:所有具名人物都是真實人物;custom 只來自玩家捏臉(docs/15) */
export const PersonCategory = z.enum([
"politician",
"official",
"business",
"entertainer",
"pundit",
"influencer",
"village_chief",
"custom",
]);
export const STAT_KEYS = [
"awareness",
"network",
"affinity",
"eloquence",
"strategy",
"online",
"image",
"wealth",
"stamina",
] as const;
export const StatKey = z.enum(STAT_KEYS);
export type StatKey = z.infer<typeof StatKey>;
/** 遊戲屬性 0–100;null 代表尚未評分 */
export const Stats = z.object(
Object.fromEntries(STAT_KEYS.map((k) => [k, z.number().int().min(0).max(100).nullable()])) as Record<
StatKey,
z.ZodNullable<z.ZodNumber>
>,
);
export const Position = z.object({
title: z.string().min(1),
org: z.string().min(1),
from: IsoDate.nullable(),
to: IsoDate.nullable(),
sourceIds: z.array(z.string()).min(1),
});
export const Education = z.object({
degree: z.string().min(1),
school: z.string().nullable(),
sourceIds: z.array(z.string()).min(1),
});
export const ElectionRecord = z.object({
election: z.string().min(1),
district: z.string().nullable(),
party: z.string().nullable(),
votes: z.number().int().nonnegative().nullable(),
share: z.number().min(0).max(1).nullable(),
elected: z.boolean(),
sourceIds: z.array(z.string()).min(1),
});
/** 每個屬性的評分紀錄:沒有出處的 AI 分數一律作廢(docs/15) */
export const ScoringRecord = z.object({
stat: StatKey,
value: z.number().int().min(0).max(100),
method: z.enum(["derived", "ai", "manual", "default"]),
rationale: z.string().nullable(),
/** 出處:資料來源 id(見 sources.json)或公開網頁網址 */
citations: z.array(z.string()),
confidence: z.enum(["high", "medium", "low"]),
model: z.string().nullable(),
rubricVersion: z.string(),
scoredAt: z.string().min(1),
reviewed: z.boolean(),
});
export type ScoringRecord = z.infer<typeof ScoringRecord>;
export const Person = z.object({
id: z.string().min(1),
kind: z.enum(["real", "custom"]),
category: PersonCategory,
name: z.string().min(1),
gender: z.enum(["M", "F", "X"]).nullable(),
birthDate: IsoDate.nullable(),
party: z.string().nullable(),
wikidataId: z.string().regex(/^Q\d+$/).nullable(),
positions: z.array(Position),
education: z.array(Education),
electionHistory: z.array(ElectionRecord),
stats: Stats,
scoring: z.array(ScoringRecord),
/** 欄位名稱 → 出處 id;姓名、性別、生日、政黨等純量欄位的出處 */
fieldSources: z.record(z.string(), z.array(z.string()).min(1)),
asOf: IsoDate,
});
export type Person = z.infer<typeof Person>;
export const PeopleFile = z.object({
protocolVersion: z.string(),
asOf: IsoDate,
people: z.array(Person),
});
export type PeopleFile = z.infer<typeof PeopleFile>;

View File

@ -5,7 +5,7 @@ import { CountyCode, IsoDate, Share, TownCode, VillageCode } from "./common.ts";
* 歷屆參選人資料庫(data/build/people/records.json,由 election-data records 產生):
* 縣市長、議員,加上總統副總統、立法委員(區域、原住民、不分區)。
* 只用中選會選舉資料庫的公開紀錄計算資歷分數;分數是遊戲數值,不代表對個人的評價。
* 檔名叫 records 是為了和 people.ts(具名人物名單 people.json)分開。
* 檔名叫 records 是沿用原本和人物資料庫(people.json,2026-10-30 刪除)分開時的命名。
*/
/** mayor:首長(縣市長、直轄市長、臺灣省長);councilor:議員;president:總統、副總統;legislator:立法委員 */

View File

@ -57,6 +57,8 @@ export const RogueIntent = z.object({
cut: z.number().min(0).max(1),
/** 預告過的大型造勢 */
big: z.boolean(),
/** 搶本週戰場的行動(docs/26) */
battle: z.boolean().default(false),
});
export type RogueIntent = z.infer<typeof RogueIntent>;
@ -382,6 +384,15 @@ export const RogueView = z.object({
.default(null),
/** 下下週的門(docs/25:看得到前方):選下一站的時候灰色顯示 */
nextRoute: z.array(z.object({ kind: RogueStopKind, title: z.string() })).nullable().default(null),
/**
* 本週戰場(docs/26):哪一區;you、rival 是這週到目前為止雙方在那區淨增的票,rivalPlan 是對手週末預計在那裡拉的票(被你打對台、樁腳擋掉的已經扣掉)。
* 週末淨增多的一方贏:你贏聲勢 +1、下週多抽 1 張;對手贏對手聲勢 +1。新手教學、舊存檔是 null
*/
battle: z.object({ town: z.string(), name: z.string(), you: z.number().int(), rival: z.number().int(), rivalPlan: z.number().int(), momentum: z.number().int(), draw: z.number().int() }).nullable().default(null),
/** 對手急起直追(docs/26):落後 gap 個百分點,這週多 extra 個行動 */
rivalPush: z.object({ extra: z.number().int(), gap: z.number() }).nullable().default(null),
/** 加開行程(docs/26):花 price 萬換 1 點體力,每週一次;blocked 是現在不能加開的原因(新手教學是 null) */
rush: z.object({ price: z.number().int(), blocked: z.string().nullable() }).nullable().default(null),
/** 地方派系談判(精英站,docs/25):這週在哪一區淨增多少票;progress 是目前淨增 */
contract: z.object({ town: z.string(), name: z.string(), goal: z.number().int(), progress: z.number().int() }).nullable().default(null),
/** 這局對手的規則(docs/25):整局有效 */

View File

@ -6,7 +6,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { CellsFile, DataPackManifest, HistoryFile, PeopleFile, TownsFile, VillagesFile } from "../src/index.ts";
import { CellsFile, DataPackManifest, HistoryFile, TownsFile, VillagesFile } from "../src/index.ts";
const buildDir = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "data", "build");
const packsDir = join(buildDir, "packs");
@ -45,14 +45,3 @@ describe.skipIf(packs.length === 0)("已產出的資料包", () => {
});
}
});
const peopleFiles = ["people.json", "people_scored.json"].map((f) => join(buildDir, "people", f)).filter(existsSync);
describe.skipIf(peopleFiles.length === 0)("已產出的人物資料", () => {
for (const file of peopleFiles) {
it(`${file.split("/").pop()} 符合協定`, () => {
const result = PeopleFile.safeParse(read(file));
expect(result.success, result.success ? "" : JSON.stringify(result.error.issues.slice(0, 3))).toBe(true);
});
}
});

View File

@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { AGE_BANDS, CellsBlock, LEANS, Person, VillageCode, VillageRecord } from "../src/index.ts";
import { AGE_BANDS, CellsBlock, LEANS, VillageCode, VillageRecord } from "../src/index.ts";
const village = {
code: "68000010001",
@ -60,41 +60,3 @@ describe("CellsBlock", () => {
expect(CellsBlock.safeParse(bad).success).toBe(false);
});
});
describe("Person", () => {
const nullStats = {
awareness: null,
network: null,
affinity: null,
eloquence: null,
strategy: null,
online: null,
image: null,
wealth: null,
stamina: null,
};
const person = {
id: "ly-11-001",
kind: "real",
category: "politician",
name: "示例",
gender: "F",
birthDate: null,
party: "某政黨",
wikidataId: null,
positions: [{ title: "立法委員", org: "立法院", from: "2024-02-01", to: null, sourceIds: ["ly-id9"] }],
education: [],
electionHistory: [],
stats: nullStats,
scoring: [],
fieldSources: { name: ["ly-id9"] },
asOf: "2026-10-25",
};
it("接受合法人物", () => {
expect(Person.safeParse(person).success).toBe(true);
});
it("職位必須附出處", () => {
const bad = { ...person, positions: [{ ...person.positions[0], sourceIds: [] }] };
expect(Person.safeParse(bad).success).toBe(false);
});
});

View File

@ -24,10 +24,10 @@ export const ADVISORS: readonly AdvisorDef[] = [
{ id: "meme_editor", name: "懶人包小編", art: "meme_editor", text: "爆紅之後,那張牌回到手上(每週一次)", school: "air" },
{ id: "crisis_flip", name: "危機變轉機", art: "crisis_flip", text: "每擋下對手一個行動(批評、打對台),週末聲勢 +1(最多 +2)", school: "defend" },
{ id: "actuary", name: "精算師", art: "actuary", text: "週末存款每 100 萬多 5 萬利息(最多 +50 萬)", school: "money" },
{ id: "truck_captain", name: "宣傳車隊長", art: "sound_truck", text: "打在某區的地面牌,隔壁每一區也有兩成效果", school: "ground" },
{ id: "truck_captain", name: "宣傳車隊長", art: "sound_truck", text: "打在某區的地面牌,擴散到隔壁區合計四成", school: "ground" },
{ id: "social_editor", name: "網路小編", art: "online_ad", text: "每週第一張網路牌不花體力", school: "air" },
{ id: "ad_planner", name: "媒體企劃", art: "tv_ad", text: "電視、網路廣告效果 +40%,花費打七折", school: "air" },
{ id: "ad_planner", name: "媒體企劃", art: "tv_ad", text: "空戰牌(電視、網路、直播、媒體)效果 +30%;電視、網路廣告打七折", school: "air" },
{ id: "debate_coach", name: "辯論教練", art: "debate_training", text: "辯論時看穿對手的出招;記者會、座談類的牌 +30%", school: "air" },
{ id: "influencer", name: "網紅朋友", art: "influencer_live", text: "直播、短影音爆紅的機率加倍", school: "air" },

View File

@ -32,7 +32,7 @@ export const ARCHETYPES: Record<RogueArchetype, ArchetypeDef> = {
},
organization: {
name: "組織型",
skill: "每週開始,本命區自動有一座樁腳;每週第一張佈樁牌不花體力",
skill: "每週第一張佈樁牌不花體力",
weakness: "空戰牌 −15%",
card: "volunteers",
replaces: "canvass",
@ -41,25 +41,25 @@ export const ARCHETYPES: Record<RogueArchetype, ArchetypeDef> = {
},
eloquence: {
name: "資深型",
skill: "記者會、座談類的牌 +20%;辯論多一張論點;回應記者追問不花體力",
weakness: "年輕人多的區 −10%",
card: "whitepaper",
skill: "記者會、座談類的牌 +30%;辯論多一張論點;回應記者追問不花體力",
weakness: "年輕人多的區 −5%",
card: "policy",
replaces: "canvass",
tags: ["press"],
school: "defend",
},
finance: {
name: "財務型",
skill: "每週資金 +150 萬;競選物資行八折;週末依手上的資金自動加票(最多算 1,000 萬)",
skill: "每週資金 +150 萬;加開行程、競選物資行八折",
weakness: "地面牌 −5%",
card: "dinner",
replaces: null,
card: "tv",
replaces: "canvass",
tags: ["money"],
school: "money",
},
integrity: {
name: "清廉型",
skill: "黑函危機損失減半;記者追問不會被塞進牌組",
skill: "對手的批評 −25%;黑函危機損失減半;記者追問不會被塞進牌組",
weakness: "每週收入 −20%",
card: "origin_clinic",
replaces: "canvass",
@ -68,7 +68,7 @@ export const ARCHETYPES: Record<RogueArchetype, ArchetypeDef> = {
},
newcomer: {
name: "黑馬型",
skill: "每一點聲勢 +12%(一般 +8%);每翻轉一區多抽 1 張牌",
skill: "每一點聲勢 +10%(一般 +8%);每翻轉一區多抽 1 張牌",
weakness: "起始資金 −30%",
card: "walk",
replaces: "canvass",
@ -96,6 +96,8 @@ const HOME_MIN_SHARE = 0.03;
* 回傳區代碼;exclude 是已經被另一方挑走的區
*/
export function homeTowns(towns: readonly TownSetup[], side: "you" | "rival", exclude: ReadonlySet<string> = new Set()): string[] {
// 只有一區的選區(立委選區常見):整張地圖都是同一區,沒有本命區(docs/26)
if (towns.length < 2) return [];
const voters = towns.reduce((a, t) => a + t.voters, 0) || 1;
const mean = towns.reduce((a, t) => a + t.lean[side] * t.voters, 0) / voters;
const n = towns.length >= 20 ? 2 : 1;

View File

@ -0,0 +1,60 @@
import { addMomentum, addRivalMomentum } from "./mechanics.ts";
import { pickWeighted, townLead, type RunState, type TownState } from "./state.ts";
/**
* 本週戰場(docs/26,參考《冷戰熱鬥》的關鍵國家、《1960》的搖擺州):每週開始標出一個選情接近的大區,
* 對手一定在那裡全力搶攻(掃街、到你的票倉拉票 ×BATTLE_PUSH;造勢本來就大,照原本的)。週末對手出手之後,這週在那區淨增的票誰多誰贏:
* 你贏了聲勢 +1、下週多抽 1 張;對手贏了對手聲勢 +1。讓地圖上每週都有一塊要搶的地,不只是比總票數。
*/
/** 對手在戰場的行動倍率 */
export const BATTLE_PUSH = 1.5;
/** 贏下戰場:聲勢 */
export const BATTLE_MOMENTUM = 1;
/** 你贏下戰場:下週多抽幾張 */
export const BATTLE_DRAW = 1;
/** 只挑選舉人數至少佔全區這個比例的區(太小的區搶了也沒感覺) */
const BATTLE_MIN_SHARE = 0.03;
/** 差距在這個範圍內算「選情接近」,越接近越容易被挑中 */
const BATTLE_RANGE = 0.12;
export const battleTown = (s: RunState): TownState | null => (s.battle && s.battle.week === s.week ? (s.towns.find((t) => t.code === s.battle!.town) ?? null) : null);
/** 這週開始:挑戰場(不連續兩週同一區),記下雙方在那區的票。新手教學沒有 */
export function startBattle(s: RunState): void {
// 只有一區的選區:整張地圖就是同一區,沒有要搶的戰場(docs/26)
if (s.options.tutorial || s.towns.length < 2) {
s.battle = null;
return;
}
const voters = s.towns.reduce((a, t) => a + t.voters, 0);
const prev = s.battle?.town;
const big = s.towns.filter((t) => t.voters >= voters * BATTLE_MIN_SHARE && t.code !== prev);
const pool = big.length ? big : s.towns.filter((t) => t.code !== prev);
const t = pickWeighted(s, pool.length ? pool : s.towns, (x) => x.voters * Math.max(0.02, 1 - Math.abs(townLead(x)) / BATTLE_RANGE) ** 3);
s.battle = t ? { town: t.code, week: s.week, startYou: t.you, startRival: t.rival } : null;
}
/** 這週到目前為止雙方在戰場淨增的票 */
export function battleProgress(s: RunState): { town: TownState; you: number; rival: number } | null {
const t = battleTown(s);
if (!t || !s.battle) return null;
return { town: t, you: t.you - s.battle.startYou, rival: t.rival - s.battle.startRival };
}
/** 週末(對手出手之後、聲勢消退之後):淨增多的一方贏下戰場 */
export function settleBattle(s: RunState): void {
const p = battleProgress(s);
if (!p) return;
const fmt = (n: number) => Math.round(n).toLocaleString("en-US");
const score = `你淨增 ${fmt(p.you)}、${s.setup.rival.name} ${fmt(p.rival)}`;
if (p.you > p.rival) {
addMomentum(s, BATTLE_MOMENTUM);
s.battleDraw = BATTLE_DRAW;
s.stats.battles = (s.stats.battles ?? 0) + 1;
s.log.push({ side: "you", text: `本週戰場${p.town.name}:你贏了(${score})!聲勢 +${BATTLE_MOMENTUM},下週多抽 ${BATTLE_DRAW} 張`, town: p.town.code, votes: 0 });
} else if (p.rival > p.you) {
addRivalMomentum(s, BATTLE_MOMENTUM);
s.log.push({ side: "rival", text: `本週戰場${p.town.name}:被${s.setup.rival.name}拿下(${score}),對手聲勢 +${BATTLE_MOMENTUM}`, town: p.town.code, votes: 0 });
}
}

View File

@ -2,8 +2,9 @@ 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 { battleProgress } from "./battle.ts";
import { encounterById } from "./route.ts";
import { choose, createRun, endWeek, ultimate, type CreateOptions } from "./rules.ts";
import { choose, createRun, endWeek, rush, rushBlocked, rushPrice, 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";
@ -90,10 +91,19 @@ function playCasual(s: RunState): RunState {
const CORE_POWERS = new Set(["legwork", "network", "buzz", "wargame"]);
/** 每點體力換多少票;錢不夠時募款牌加分,沒有把柄時打探加分 */
/** 本週戰場還差多少才贏(對手在那區預計淨增 − 你這週已經淨增);沒有戰場是 null */
function battleNeed(s: RunState): { town: string; need: number } | null {
const p = battleProgress(s);
if (!p) return null;
const rival = s.intents.filter((i) => i.town === p.town.code && i.kind !== "stake" && i.kind !== "smear").reduce((a, i) => a + i.amount * i.cut, 0);
return { town: p.town.code, need: rival - Math.min(p.town.shield, rival) + p.rival - p.you };
}
/** 每點體力換多少票;錢不夠時募款牌加分,沒有把柄時打探加分;本週戰場還沒贏就加分 */
function playGreedy(s: RunState): RunState {
for (let k = 0; k < 14; k++) {
const previews = previewsFor(s);
const battle = battleNeed(s);
let best: { uid: string; target: string | null; value: number } | null = null;
for (const c of s.hand) {
const card = defOf(c);
@ -107,6 +117,9 @@ function playGreedy(s: RunState): RunState {
// 能力牌整局有效:越早打越值得(流派核心的能力牌效果大,打得好的人一拿到就先打)
if (kind === "power") value = (s.totalWeeks - s.week + 1) * (CORE_POWERS.has(card.id) ? 2200 : 900) * s.scale;
if (kind === "answer") value = 3000 * s.scale;
// 戰場:打在戰場(或對戰場的行動打對台)、還沒贏,就多算一點(贏了聲勢 +1、下週多抽一張)
const at = card.target === "intent" ? s.intents.find((i) => i.id === p.target)?.town : p.target;
if (battle && battle.need >= 0 && at === battle.town && p.votes > 0) value += 1800 * 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 };
}
@ -257,7 +270,8 @@ 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;
// 隨手玩:看到什麼點什麼(不一定是新牌)
if (bot === "casual") return Math.floor(d.next() * route.length);
const ranked = route.map((k, i) => ({ i, v: routeScore(s, bot, k) })).sort((a, b) => b.v - a.v);
return ranked[0]!.i;
}
@ -339,6 +353,14 @@ export function runBot(setup: RogueSetup, seed: number, bot: BotName, opts: Crea
const r = ultimate(s, "rally", score);
if (!("error" in r)) s = r;
}
// 加開行程:打得好的人手上還有能打的牌、錢夠(留一點給物資行)就加開;隨手玩的人錢很多才按
if (!rushBlocked(s)) {
const spare = smart(bot) ? s.money >= rushPrice(s) + 100 && playable(s).length > s.energy : bot === "casual" && s.money >= rushPrice(s) * 2;
if (spare) {
const r = rush(s);
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);

View File

@ -0,0 +1,229 @@
/**
* 逐張地圖的對手強度校準(docs/26):同樣的規則,不同縣市、選區的地理(區的大小分布、地區特色、相鄰關係、候選人)
* 讓難度差到十幾個百分點。apps/sim 的 rogue-calibrate 用模擬玩家把每張「勢均力敵」地圖都跑過,
* 把對手強度乘上這裡的係數,讓每張地圖的平均差距接近同一個目標。鍵是劇本 id(去掉 -even),真實底盤版共用同一個係數。
* 這個檔案由 `node apps/sim/src/rogue-calibrate.ts --write` 產生;沒有的地圖(新手教學、里長、議員)是 1
*/
export const MAP_CALIBRATION: Readonly<Record<string, number>> = {
"leg2020-09007-01": 1.031,
"leg2020-09020-01": 0.949,
"leg2020-10002-01": 1.068,
"leg2020-10004-01": 1.053,
"leg2020-10004-02": 1.091,
"leg2020-10005-01": 1.119,
"leg2020-10005-02": 1.052,
"leg2020-10007-01": 0.984,
"leg2020-10007-02": 1.079,
"leg2020-10007-03": 1.071,
"leg2020-10007-04": 1.081,
"leg2020-10008-01": 1.068,
"leg2020-10008-02": 1.104,
"leg2020-10009-01": 1.145,
"leg2020-10009-02": 1.095,
"leg2020-10010-01": 1.08,
"leg2020-10010-02": 0.985,
"leg2020-10013-01": 1.142,
"leg2020-10013-02": 1.157,
"leg2020-10014-01": 1.113,
"leg2020-10015-01": 1.042,
"leg2020-10016-01": 1.132,
"leg2020-10017-01": 1.047,
"leg2020-10018-01": 1.064,
"leg2020-10020-01": 1.094,
"leg2020-63000-01": 1.058,
"leg2020-63000-02": 1.062,
"leg2020-63000-03": 1.117,
"leg2020-63000-04": 1.095,
"leg2020-63000-05": 1.088,
"leg2020-63000-06": 1.06,
"leg2020-63000-07": 1.092,
"leg2020-63000-08": 1.087,
"leg2020-64000-01": 1.098,
"leg2020-64000-02": 1.066,
"leg2020-64000-03": 1.095,
"leg2020-64000-04": 1.105,
"leg2020-64000-05": 1.068,
"leg2020-64000-06": 1.023,
"leg2020-64000-07": 1.054,
"leg2020-64000-08": 1.099,
"leg2020-65000-01": 1.05,
"leg2020-65000-02": 1.071,
"leg2020-65000-03": 0.977,
"leg2020-65000-04": 1.029,
"leg2020-65000-05": 1.043,
"leg2020-65000-06": 1.013,
"leg2020-65000-07": 1.053,
"leg2020-65000-08": 1.054,
"leg2020-65000-09": 1.066,
"leg2020-65000-10": 1.101,
"leg2020-65000-11": 1.131,
"leg2020-65000-12": 1.1,
"leg2020-66000-01": 1.022,
"leg2020-66000-02": 1.042,
"leg2020-66000-03": 1.141,
"leg2020-66000-04": 1.095,
"leg2020-66000-05": 1.097,
"leg2020-66000-06": 1.042,
"leg2020-66000-07": 1.077,
"leg2020-66000-08": 1.073,
"leg2020-67000-01": 1.121,
"leg2020-67000-02": 1.106,
"leg2020-67000-03": 1.105,
"leg2020-67000-04": 1.119,
"leg2020-67000-05": 1.063,
"leg2020-67000-06": 1.119,
"leg2020-68000-01": 1.045,
"leg2020-68000-02": 1.099,
"leg2020-68000-03": 1.048,
"leg2020-68000-04": 1.056,
"leg2020-68000-05": 1.079,
"leg2020-68000-06": 0.964,
"leg2024-09007-01": 1.087,
"leg2024-09020-01": 0.968,
"leg2024-10002-01": 1.059,
"leg2024-10004-01": 1.04,
"leg2024-10004-02": 1.137,
"leg2024-10005-01": 1.137,
"leg2024-10005-02": 0.998,
"leg2024-10007-01": 1.015,
"leg2024-10007-02": 1.089,
"leg2024-10007-03": 1.068,
"leg2024-10007-04": 1.106,
"leg2024-10008-01": 1.052,
"leg2024-10008-02": 1.1,
"leg2024-10009-01": 1.109,
"leg2024-10009-02": 1.099,
"leg2024-10010-01": 1.092,
"leg2024-10010-02": 0.984,
"leg2024-10013-01": 1.117,
"leg2024-10013-02": 1.082,
"leg2024-10014-01": 1.081,
"leg2024-10015-01": 1.04,
"leg2024-10016-01": 1.121,
"leg2024-10017-01": 1.035,
"leg2024-10018-01": 1.087,
"leg2024-10020-01": 1.077,
"leg2024-63000-01": 1.054,
"leg2024-63000-02": 1.078,
"leg2024-63000-03": 1.132,
"leg2024-63000-04": 1.102,
"leg2024-63000-05": 1.083,
"leg2024-63000-06": 1.055,
"leg2024-63000-07": 1.084,
"leg2024-63000-08": 1.13,
"leg2024-64000-01": 1.031,
"leg2024-64000-02": 1.036,
"leg2024-64000-03": 1.082,
"leg2024-64000-04": 1.108,
"leg2024-64000-05": 1.058,
"leg2024-64000-06": 1.034,
"leg2024-64000-07": 1.058,
"leg2024-64000-08": 1.087,
"leg2024-65000-01": 1.041,
"leg2024-65000-02": 1.024,
"leg2024-65000-03": 1.061,
"leg2024-65000-04": 1.012,
"leg2024-65000-05": 1.061,
"leg2024-65000-06": 1.064,
"leg2024-65000-07": 1.058,
"leg2024-65000-08": 1.01,
"leg2024-65000-09": 1.077,
"leg2024-65000-10": 1.073,
"leg2024-65000-11": 1.132,
"leg2024-65000-12": 1.091,
"leg2024-66000-01": 0.963,
"leg2024-66000-02": 1.088,
"leg2024-66000-03": 1.064,
"leg2024-66000-04": 1.076,
"leg2024-66000-05": 1.103,
"leg2024-66000-06": 1.066,
"leg2024-66000-07": 1.101,
"leg2024-66000-08": 1.102,
"leg2024-67000-01": 1.124,
"leg2024-67000-02": 1.108,
"leg2024-67000-03": 1.107,
"leg2024-67000-04": 0.976,
"leg2024-67000-05": 1.021,
"leg2024-67000-06": 1.067,
"leg2024-68000-01": 1.06,
"leg2024-68000-02": 1.105,
"leg2024-68000-03": 1.055,
"leg2024-68000-04": 1.048,
"leg2024-68000-05": 1.107,
"leg2024-68000-06": 0.935,
"local2014-09007": 1.075,
"local2014-09020": 1.005,
"local2014-10002": 1.086,
"local2014-10004": 1.026,
"local2014-10005": 1.095,
"local2014-10007": 1.027,
"local2014-10008": 1.021,
"local2014-10009": 1.134,
"local2014-10010": 1.055,
"local2014-10013": 1.08,
"local2014-10014": 1.083,
"local2014-10015": 0.969,
"local2014-10016": 1.122,
"local2014-10017": 1.027,
"local2014-10018": 1.067,
"local2014-10020": 1.09,
"local2014-63000": 0.952,
"local2014-64000": 1.075,
"local2014-65000": 1.054,
"local2014-66000": 1.026,
"local2014-67000": 1.089,
"local2014-68000": 1.062,
"local2018-09007": 1.105,
"local2018-09020": 0.958,
"local2018-10002": 1.109,
"local2018-10004": 1.047,
"local2018-10005": 1.001,
"local2018-10007": 1.063,
"local2018-10008": 1.065,
"local2018-10009": 1.124,
"local2018-10010": 1.057,
"local2018-10013": 1.084,
"local2018-10014": 1.099,
"local2018-10015": 1.062,
"local2018-10016": 1.132,
"local2018-10017": 1.065,
"local2018-10018": 1.072,
"local2018-10020": 1.094,
"local2018-63000": 1.067,
"local2018-64000": 1.102,
"local2018-65000": 1.061,
"local2018-66000": 1.071,
"local2018-67000": 1.078,
"local2018-68000": 1.07,
"local2022-09007": 1.033,
"local2022-09020": 0.973,
"local2022-10002": 1.078,
"local2022-10004": 1.074,
"local2022-10005": 1.03,
"local2022-10007": 1.06,
"local2022-10008": 1.037,
"local2022-10009": 1.148,
"local2022-10010": 1.079,
"local2022-10013": 1.091,
"local2022-10014": 1.104,
"local2022-10015": 1.073,
"local2022-10016": 1.106,
"local2022-10017": 1.066,
"local2022-10018": 1.035,
"local2022-63000": 1.055,
"local2022-64000": 1.093,
"local2022-65000": 1.057,
"local2022-66000": 1.071,
"local2022-67000": 1.098,
"pres1996": 1.061,
"pres2000": 1.048,
"pres2004": 1.045,
"pres2008": 1.091,
"pres2012": 1.066,
"pres2016": 1.081,
"pres2020": 1.113,
"pres2024": 1.079,
"taoyuan-2022-mayor": 1.088,
};
export const mapFactor = (scenarioId: string): number => MAP_CALIBRATION[scenarioId.replace(/-even$/, "")] ?? 1;

View File

@ -2,7 +2,7 @@ import { ADVISOR_BY_ID } from "./advisors.ts";
import { ARCHETYPES, HOME_MULT } from "./archetypes.ts";
import { POWERS, TRAIT_LABELS, cardDef, hasKeyword, type CardDef } from "./data.ts";
import { BUILDING_BY_ID, POLICY_HOME, POLICY_HOME_STEP, policyTargetOf } from "./meta.ts";
import { addMomentum, addRivalMomentum, addStatus, asc, cityVotes, drawCards, eventMult, eventOf, has, isArch, loseVotes, moveVotes, rivalHurtMult, spread, updateFlags } from "./mechanics.ts";
import { addMomentum, addRivalMomentum, addStatus, ascOn, cityVotes, drawCards, eventMult, eventOf, has, isArch, loseVotes, moveVotes, rivalHurtMult, spread, updateFlags } from "./mechanics.ts";
import { addTally, cloneState, newCard, rand, type CardInst, type Intent, type RunState, type TownState } from "./state.ts";
/** 組合拳:同一週同一區打出第 n 種不同的牌,這張牌的加成 */
@ -31,8 +31,8 @@ export function cardCost(s: RunState, card: CardDef): { energy: number; money: n
return { energy: freeOnline ? 0 : card.cost, money: Math.round(card.money * (ads ? 0.7 : 1) * (buzz ? 0.7 : 1)) };
}
/** 對手這週可以打對台的行動:打在某一區、還沒被打對台過 */
export const counterable = (s: RunState): Intent[] => s.intents.filter((i) => i.town !== null && i.cut >= 1 && ["canvass", "rally", "smear", "stake"].includes(i.kind));
/** 對手這週可以打對台的行動:批評以外、還沒被打對台過的(電視、網路廣告也可以搶版面,docs/26) */
export const counterable = (s: RunState): Intent[] => s.intents.filter((i) => i.cut >= 1 && i.kind !== "attack");
/** 對手這週全市的批評(事實查核可以讓它失效) */
export const attackable = (s: RunState): Intent[] => s.intents.filter((i) => i.kind === "attack" && i.cut > 0);
@ -44,7 +44,7 @@ export function blockedReason(s: RunState, card: CardDef): string | null {
if (cost.money > s.money) return "資金不夠";
if (card.effect.kind === "kneel" && s.week !== s.totalWeeks) return "最後一週才能打";
if (card.oncePerWeek && (s.weekCards ?? []).includes(card.id)) return "這週已經打過了";
if (card.target === "intent" && counterable(s).length === 0) return "對手這週沒有區域行動";
if (card.target === "intent" && counterable(s).length === 0) return "對手這週沒有可以打對台的行動";
if (card.target === "attack" && attackable(s).length === 0) return "對手這週沒有批評你";
return null;
}
@ -63,8 +63,9 @@ const TOWN_ADVISORS = [
{ id: "student_leader", trait: "young", m: 1.4 },
] as const;
/** 聲量滾雪球:每點聲量讓空戰牌 +5%;懶人包每點再 +6%(docs/25 第 2 節,依模擬調過) */
/** 聲量滾雪球:每點聲量讓空戰牌 +5%、其他牌 +3%(網路聲量帶動地面行程,docs/26);懶人包每點再 +6%(docs/25 第 2 節,依模擬調過) */
export const BUZZ_STEP = 0.05;
export const BUZZ_OTHER_STEP = 0.03;
export const EXPLAINER_STEP = 0.06;
/** 牌類的幕僚 */
@ -72,7 +73,7 @@ const CARD_ADVISORS = [
{ id: "temple_master", ok: (c: CardDef) => c.tags.includes("temple"), m: 1.6 },
{ id: "market_auntie", ok: (c: CardDef) => c.tags.includes("market"), m: 1.5 },
{ id: "rally_king", ok: (c: CardDef) => c.tags.includes("rally"), m: 1.5 },
{ id: "ad_planner", ok: (c: CardDef) => c.id === "tv" || c.id === "online", m: 1.4 },
{ id: "ad_planner", ok: (c: CardDef) => c.tags.includes("media"), m: 1.3 },
{ id: "debate_coach", ok: (c: CardDef) => c.tags.includes("press"), m: 1.3 },
] as const;
@ -97,7 +98,10 @@ export function boost(s: RunState, card: CardDef, town: TownState | null): Boost
const ground = s.groundPlayed ?? 0;
if (s.powers.includes("legwork") && card.tags.includes("ground") && ground > 0) apply(1 + 0.08 * ground, `走透透 ×${(1 + 0.08 * ground).toFixed(2)}`);
const buzz = s.buzz ?? 0;
if (s.powers.includes("buzz") && card.tags.includes("media") && buzz > 0) apply(1 + BUZZ_STEP * buzz, `聲量 ${buzz} ×${(1 + BUZZ_STEP * buzz).toFixed(2)}`);
if (s.powers.includes("buzz") && buzz > 0) {
const step = card.tags.includes("media") ? BUZZ_STEP : BUZZ_OTHER_STEP;
apply(1 + step * buzz, `聲量 ${buzz} ×${(1 + step * buzz).toFixed(2)}`);
}
if (card.id === "explainer" && buzz > 0) apply(1 + EXPLAINER_STEP * buzz, `懶人包・聲量 ${buzz} ×${(1 + EXPLAINER_STEP * buzz).toFixed(2)}`);
for (const b of s.buffs) if (card.tags.includes(b.tag)) apply(b.mult, `這週加成 ×${b.mult}`);
// 政策島的建築
@ -124,17 +128,17 @@ export function boost(s: RunState, card: CardDef, town: TownState | null): Boost
if (isArch(s, "media") && air) apply(1.15, "媒體型 ×1.15");
if (isArch(s, "media") && air && s.viral?.boost) apply(2, "爆紅加持 ×2");
if (isArch(s, "organization") && air) apply(0.85, "組織型(空戰)×0.85");
if (isArch(s, "eloquence") && card.tags.includes("press")) apply(1.2, "資深型 ×1.2");
if (isArch(s, "eloquence") && town?.traits.includes("young")) apply(0.9, "資深型(年輕人多)×0.9");
if (isArch(s, "eloquence") && card.tags.includes("press")) apply(1.3, "資深型 ×1.3");
if (isArch(s, "eloquence") && town?.traits.includes("young")) apply(0.95, "資深型(年輕人多)×0.95");
if (isArch(s, "finance") && card.tags.includes("ground")) apply(0.95, "財務型(地面)×0.95");
const ev = eventMult(s, card.tags, town);
apply(ev, `${eventOf(s).title} ×${ev}`);
if (s.week === s.totalWeeks && card.tags.includes("rally")) apply(EVE_RALLY, `選前之夜 ×${EVE_RALLY}`);
if (has(s, "opener") && s.playedThisWeek === 0) apply(1.5, "開場哥 ×1.5");
if (has(s, "night_owl") && s.energy === 0 && (s.paying ?? 0) > 0) apply(1.5, "夜貓子 ×1.5");
if (asc(s, 8)) apply(0.92, "逆風 ×0.92");
// 黑馬型:每一點聲勢的效果是一般的 1.5 倍
const step = MOMENTUM_STEP * (isArch(s, "newcomer") ? 1.5 : 1);
if (ascOn(s, "weak")) apply(0.95, "逆風 ×0.95");
// 黑馬型:每一點聲勢的效果是一般的 1.25 倍
const step = MOMENTUM_STEP * (isArch(s, "newcomer") ? 1.25 : 1);
if (s.momentum > 0) apply(1 + step * s.momentum, `聲勢 +${Math.round(step * s.momentum * 100)}%`);
return { mult, notes };
}
@ -152,8 +156,8 @@ interface Played {
back?: boolean;
}
/** 你在某一區加票:先被對手樁腳擋掉一部分。spill 是擴散到隔壁區(不算組合拳) */
function gainAt(s: RunState, card: CardDef, t: TownState, base: number, out: Played, spill = false): number {
/** 你在某一區加票:先被對手樁腳擋掉一部分。spill 是擴散到隔壁區、"crowd" 是擴散不出去留在本區的人潮(都不算組合拳) */
function gainAt(s: RunState, card: CardDef, t: TownState, base: number, out: Played, spill: boolean | "crowd" = false): number {
const b = boost(s, card, t);
const combo = spill ? 0 : comboOf(s, card, t);
if (combo > 0) b.notes.push(`組合拳 +${Math.round(combo * 100)}%`);
@ -163,18 +167,26 @@ function gainAt(s: RunState, card: CardDef, t: TownState, base: number, out: Pla
if (blocked > 0) b.notes.push(`被對手樁腳擋掉 ${Math.round(blocked).toLocaleString("en-US")}`);
const net = moveVotes(t, raw - blocked, "you");
if (!spill) out.notes.push(...b.notes);
out.log.push({ side: "you", text: `${card.name}・${t.name}${spill ? "(擴散)" : ""}`, town: t.code, votes: Math.round(net) });
out.log.push({ side: "you", text: `${card.name}・${t.name}${spill === "crowd" ? "(人潮)" : spill ? "(擴散)" : ""}`, town: t.code, votes: Math.round(net) });
s.stats.bigHit = Math.max(s.stats.bigHit, net / s.scale);
return net;
}
/** 擴散到隔壁每一區 */
/**
* 擴散(docs/26):不管有幾個隔壁區,擴散出去的合計都是 ratio × SPILL_SLOTS,平均分給隔壁區;
* 隔壁區不夠(離島、只有一兩個鄰區)擴散不出去的,留在本區當人潮。這樣每個縣市的造勢、宣傳車一樣值錢
*/
export const SPILL_SLOTS = 2;
export const spillShare = (neighbors: number, ratio: number): { each: number; rest: number } => ({
each: neighbors > 0 ? (ratio * Math.min(neighbors, SPILL_SLOTS)) / neighbors : 0,
rest: ratio * Math.max(0, SPILL_SLOTS - neighbors),
});
function spillTo(s: RunState, card: CardDef, t: TownState, base: number, ratio: number, out: Played): void {
if (ratio <= 0) return;
for (const code of t.neighbors) {
const n = s.towns.find((x) => x.code === code);
if (n) gainAt(s, card, n, base * ratio, out, true);
}
const near = t.neighbors.flatMap((code) => s.towns.find((x) => x.code === code) ?? []);
const { each, rest } = spillShare(near.length, ratio);
for (const n of near) gainAt(s, card, n, base * each, out, true);
if (rest > 0) gainAt(s, card, t, base * rest, out, "crowd");
}
/** 全市加票(空戰不會被樁腳擋) */
@ -269,8 +281,16 @@ function resolve(s: RunState, card: CardDef, town: TownState | null, intent: Int
break;
}
case "counter": {
const t = s.towns.find((x) => x.code === intent!.town)!;
intent!.cut = Math.min(intent!.cut, e.cut);
const t = s.towns.find((x) => x.code === intent!.town);
// 全市的廣告:搶版面,你全市加票
if (!t) {
out.notes.push(`對手的廣告剩 ${Math.round(e.cut * 100)}%`);
const b = boost(s, card, null);
out.notes.push(...b.notes);
gainCity(s, card, e.base * b.mult, undefined, out, `${card.name}(搶版面)`);
break;
}
if (intent!.kind === "stake") t.rivalShield *= e.cut;
out.notes.push(`對手${t.name}的行動剩 ${Math.round(e.cut * 100)}%`);
gainAt(s, card, t, e.base, out);

View File

@ -9,9 +9,9 @@ import { policyCardDef } from "./meta.ts";
export type CardEffect =
/** 該區加票 */
| { kind: "gain"; base: number }
/** 該區加票,聲勢 +momentum;spill 是隔壁區各拿到幾成 */
/** 該區加票,聲勢 +momentum;spill × 2 是擴散到隔壁區合計幾成(cards.ts spillTo) */
| { kind: "rally"; base: number; momentum: number; spill?: number }
/** 該區加票,隔壁區各拿到 spill 成 */
/** 該區加票,擴散到隔壁區合計 spill × 2 */
| { kind: "spread"; base: number; spill: number }
/** 該區這週的樁腳(擋對手),順便加一點票 */
| { kind: "shield"; base: number; gain: number }
@ -119,14 +119,14 @@ export const CARDS: readonly CardDef[] = [
{ id: "legwork", name: "走透透", art: "walk_everywhere", cost: 1, money: 0, rarity: "rare", tags: ["ground"], target: "none", effect: { kind: "power", power: "legwork" }, text: "能力:這週每打過一張地面牌,之後的地面牌 +8%(週末歸零)" },
{ id: "doorstep", name: "遍地開花", art: "blooming_districts", cost: 1, money: 0, rarity: "rare", tags: ["ground"], target: "town", effect: { kind: "breadth", base: 900 }, text: "該區 +{n} × 這週出過牌的區數(最多 5 區)" },
{ id: "network", name: "樁腳網", art: "local_network", cost: 1, money: 0, rarity: "rare", tags: ["org"], target: "none", effect: { kind: "power", power: "network" }, text: "能力:週末每座還沒被用掉的樁腳,三成變成你在那區的票" },
{ id: "buzz", name: "聲量滾雪球", art: "snowball_buzz", cost: 1, money: 0, rarity: "rare", tags: ["media"], target: "none", effect: { kind: "power", power: "buzz" }, text: "能力:空戰牌的花費 −30%;每打一張空戰牌聲量 +1(整局累積,最多 15),空戰牌每點聲量 +5%" },
{ id: "buzz", name: "聲量滾雪球", art: "snowball_buzz", cost: 1, money: 0, rarity: "rare", tags: ["media"], target: "none", effect: { kind: "power", power: "buzz" }, text: "能力:空戰牌的花費 −30%;每打一張空戰牌聲量 +1(整局累積,最多 15);每點聲量讓空戰牌 +5%、其他牌 +3%" },
{ id: "explainer", name: "懶人包", art: "explainer_cards", cost: 1, money: 0, rarity: "rare", tags: ["media", "online"], target: "city", effect: { kind: "city", base: 2300, weight: "young" }, text: "全市 +{n},年輕人多的區分到較多;每點聲量再 +6%" },
{ id: "turntable", name: "反將一軍", art: "turn_the_tables", cost: 1, money: 0, rarity: "rare", tags: ["defend"], target: "none", effect: { kind: "turnaround", cut: 0.5 }, text: "對手這週的批評剩一半;這週你擋下的對手行動,一半變成你的全市票" },
{ id: "wargame", name: "沙盤推演", art: "war_room", cost: 1, money: 0, rarity: "rare", tags: ["defend", "intel"], target: "none", effect: { kind: "power", power: "wargame" }, text: "能力:每週前兩張打對台、澄清、事實查核、反將一軍不花體力" },
{ id: "carpetads", name: "地毯式廣告", art: "ad_blitz", cost: 1, money: 0, rarity: "rare", tags: ["money"], target: "city", effect: { kind: "spend", perHundred: 900 }, text: "花光手上的資金:每 100 萬全市 +{n}" },
{ id: "microdonate", name: "小額募款", art: "donation_box", cost: 1, money: 0, rarity: "rare", tags: ["money"], target: "none", effect: { kind: "flagMoney", base: 120, perFlag: 60 }, text: "資金 +{m} 萬;你每插一面旗再 +{p} 萬" },
{ id: "homecoming", name: "回鄉造勢", art: "homecoming", cost: 1, money: 0, rarity: "basic", tags: ["ground", "rally"], target: "town", homeOnly: true, effect: { kind: "rally", base: 2600, momentum: 1 }, text: "只能打在你的本命區;該區 +{n},聲勢 +1" },
{ id: "rally", name: "造勢晚會", art: "rally", cost: 2, money: 200, rarity: "basic", tags: ["ground", "rally"], target: "town", effect: { kind: "rally", base: 3450, momentum: 2, spill: 0.25 }, plus: { effect: { kind: "rally", base: 4140, momentum: 3, spill: 0.3 } }, text: "該區 +{n}、隔壁區兩成半,聲勢 +2" },
{ id: "rally", name: "造勢晚會", art: "rally", cost: 2, money: 200, rarity: "basic", tags: ["ground", "rally"], target: "town", effect: { kind: "rally", base: 3450, momentum: 2, spill: 0.25 }, plus: { effect: { kind: "rally", base: 4140, momentum: 3, spill: 0.3 }, text: "該區 +{n}、擴散到隔壁區合計六成,聲勢 +3" }, text: "該區 +{n}、擴散到隔壁區合計五成,聲勢 +2" },
// ── 地面戰 ──
{ id: "night", name: "夜市拜票", art: "night_market", cost: 1, money: 0, rarity: "common", tags: ["ground", "market"], target: "town", effect: { kind: "gain", base: 1490 }, bonus: [{ trait: "young", mult: 1.5 }], text: "該區 +{n};年輕人多 ×1.5" },
@ -137,14 +137,14 @@ export const CARDS: readonly CardDef[] = [
{ id: "campus", name: "校園座談", art: "forum", cost: 1, money: 0, rarity: "common", tags: ["ground", "press"], target: "town", effect: { kind: "gain", base: 1380 }, bonus: [{ trait: "young", mult: 1.7 }], text: "該區 +{n};年輕人多 ×1.7" },
{ id: "hakka", name: "客家庄拜會", art: "visit_associations", cost: 1, money: 0, rarity: "common", tags: ["ground"], target: "town", effect: { kind: "gain", base: 1260 }, bonus: [{ trait: "hakka", mult: 2.2 }], text: "該區 +{n};客家庄 ×2.2" },
{ id: "weddings", name: "跑紅白帖", art: "weddings_funerals", cost: 1, money: 30, rarity: "common", tags: ["ground"], target: "town", effect: { kind: "gain", base: 1260 }, bonus: [{ trait: "rural", mult: 1.6 }, { trait: "old", mult: 1.2 }], text: "該區 +{n};地廣人稀 ×1.6、長輩多 ×1.2" },
{ id: "truck", name: "宣傳車遊街", art: "sound_truck", cost: 1, money: 30, rarity: "common", tags: ["ground"], target: "town", effect: { kind: "spread", base: 1150, spill: 0.5 }, text: "該區 +{n},隔壁每一區也有一半" },
{ id: "truck", name: "宣傳車遊街", art: "sound_truck", cost: 1, money: 30, rarity: "common", tags: ["ground"], target: "town", effect: { kind: "spread", base: 1150, spill: 0.5 }, text: "該區 +{n},擴散到隔壁區合計一樣多" },
{ id: "banquet", name: "流水席辦桌", art: "banquet", cost: 2, money: 150, rarity: "common", tags: ["ground", "org"], target: "town", effect: { kind: "shield", base: 1440, gain: 2880 }, text: "該區 +{n},樁腳 {s}" },
{ id: "pilgrimage", name: "跟著遶境", art: "pilgrimage", cost: 2, money: 50, rarity: "rare", tags: ["ground", "temple", "rally"], target: "town", effect: { kind: "rally", base: 2880, momentum: 2 }, bonus: [{ trait: "temples", mult: 2 }], text: "該區 +{n},聲勢 +2;宮廟多 ×2" },
{ id: "celebrity", name: "藝人站台", art: "concert", cost: 2, money: 250, rarity: "rare", tags: ["rally", "media"], target: "town", effect: { kind: "rally", base: 4600, momentum: 2, spill: 0.2 }, bonus: [{ trait: "young", mult: 1.3 }], text: "該區 +{n}、隔壁區兩成,聲勢 +2;年輕人多 ×1.3" },
{ id: "celebrity", name: "藝人站台", art: "concert", cost: 2, money: 250, rarity: "rare", tags: ["rally", "media"], target: "town", effect: { kind: "rally", base: 4600, momentum: 2, spill: 0.2 }, bonus: [{ trait: "young", mult: 1.3 }], text: "該區 +{n}、擴散到隔壁區合計四成,聲勢 +2;年輕人多 ×1.3" },
{ id: "endorse", name: "地方仕紳背書", art: "endorsement", cost: 1, money: 0, rarity: "rare", tags: ["ground", "org"], target: "town", effect: { kind: "gain", base: 2070 }, keywords: ["retain"], text: "保留;該區 +{n}" },
// ── 組織 ──
{ id: "counter", name: "打對台", art: "sound_truck", cost: 1, money: 0, rarity: "common", tags: ["ground", "defend"], target: "intent", effect: { kind: "counter", base: 1720, cut: 0.4 }, plus: { effect: { kind: "counter", base: 2320, cut: 0.2 } }, text: "對手在某區的行動剩四成,你在那區 +{n}" },
{ id: "counter", name: "打對台", art: "sound_truck", cost: 1, money: 0, rarity: "common", tags: ["ground", "defend"], target: "intent", effect: { kind: "counter", base: 1720, cut: 0.4 }, plus: { effect: { kind: "counter", base: 2320, cut: 0.2 } }, text: "對手一個行動(批評以外,廣告也行)剩四成;你在那區 +{n}(廣告是全市)" },
{ id: "office", name: "設競選服務處", art: "open_office", cost: 2, money: 200, rarity: "common", tags: ["org"], target: "town", effect: { kind: "office", perWeek: 920 }, plus: { cost: 1 }, text: "該區現在和之後每週 +{n}" },
{ id: "billboard", name: "插旗看板", art: "flags_billboards", cost: 1, money: 100, rarity: "common", tags: ["org", "media"], target: "town", effect: { kind: "office", perWeek: 520 }, text: "該區現在和之後每週 +{n}" },
{ id: "calls", name: "志工電話催票", art: "volunteer_calls", cost: 1, money: 0, rarity: "common", tags: ["org"], target: "none", effect: { kind: "base", base: 1040, towns: 3 }, text: "你領先最多的 3 區各 +{n}" },
@ -155,14 +155,14 @@ export const CARDS: readonly CardDef[] = [
// ── 空戰 ──
{ id: "tv", name: "電視廣告", art: "tv_ad", cost: 1, money: 300, rarity: "common", tags: ["media", "tv"], target: "city", effect: { kind: "city", base: 5180, weight: "old" }, text: "全市 +{n},長輩多的區分到較多" },
{ id: "online", name: "網路廣告", art: "online_ad", cost: 1, money: 120, rarity: "common", tags: ["media", "online"], target: "city", effect: { kind: "city", base: 3220, weight: "young" }, text: "全市 +{n},年輕人多的區分到較多" },
{ id: "online", name: "網路廣告", art: "online_ad", cost: 1, money: 120, rarity: "common", tags: ["media", "online"], target: "city", effect: { kind: "city", base: 3450, weight: "young" }, text: "全市 +{n},年輕人多的區分到較多" },
{ id: "live", name: "臉書直播", art: "facebook_live", cost: 1, money: 0, rarity: "common", tags: ["media", "online"], target: "city", effect: { kind: "gamble", base: 1380, chance: 0.35, hit: 3, miss: 1 }, text: "全市 +{n};35% 爆紅 ×3" },
{ id: "shorts", name: "短影音", art: "short_video", cost: 1, money: 60, rarity: "common", tags: ["media", "online"], target: "city", effect: { kind: "gamble", base: 1840, chance: 0.25, hit: 3.5, miss: 1 }, text: "全市 +{n};25% 爆紅 ×3.5" },
{ id: "talk", name: "上政論節目", art: "talk_show", cost: 1, money: 0, rarity: "common", tags: ["media"], target: "city", effect: { kind: "gamble", base: 2530, chance: 0.2, hit: -0.7, miss: 1 }, plus: { effect: { kind: "gamble", base: 3220, chance: 0.1, hit: -0.7, miss: 1 }, text: "全市 +{n};10% 失言倒扣" }, text: "全市 +{n};20% 失言倒扣" },
{ id: "line", name: "長輩群組", art: "line_groups", cost: 1, money: 40, rarity: "common", tags: ["media", "online"], target: "city", effect: { kind: "city", base: 2990, weight: "old" }, text: "全市 +{n},長輩多的區分到較多" },
{ id: "radio", name: "廣播專訪", art: "radio_ad", cost: 1, money: 0, rarity: "common", tags: ["media", "press"], target: "city", effect: { kind: "city", base: 2070, weight: "rural" }, text: "全市 +{n},地廣人稀的區分到較多" },
{ id: "line", name: "長輩群組", art: "line_groups", cost: 1, money: 40, rarity: "common", tags: ["media", "online"], target: "city", effect: { kind: "city", base: 3220, weight: "old" }, text: "全市 +{n},長輩多的區分到較多" },
{ id: "radio", name: "廣播專訪", art: "radio_ad", cost: 1, money: 0, rarity: "common", tags: ["media", "press"], target: "city", effect: { kind: "city", base: 2230, weight: "rural" }, text: "全市 +{n},地廣人稀的區分到較多" },
{ id: "flyers", name: "印文宣", art: "print_flyers", cost: 0, money: 50, rarity: "common", tags: ["media"], target: "city", effect: { kind: "city", base: 1150 }, text: "不花體力;全市 +{n}" },
{ id: "policy", name: "政見發表會", art: "announce_policy", cost: 1, money: 0, rarity: "common", tags: ["press", "media"], target: "city", effect: { kind: "city", base: 1610, momentum: 1 }, text: "全市 +{n},聲勢 +1" },
{ id: "policy", name: "政見發表會", art: "announce_policy", cost: 1, money: 0, rarity: "common", tags: ["press", "media"], target: "city", effect: { kind: "city", base: 1720, momentum: 1 }, text: "全市 +{n},聲勢 +1" },
{ id: "whitepaper", name: "政策白皮書", art: "white_paper", cost: 1, money: 0, rarity: "rare", tags: ["press"], target: "none", effect: { kind: "buff", tag: "media", mult: 1.5, base: 1150 }, text: "全市 +{n};這週之後的媒體牌 ×1.5" },
{ id: "mediatraining", name: "媒體訓練", art: "media_training", cost: 1, money: 100, rarity: "rare", tags: ["press"], target: "none", effect: { kind: "power", power: "media" }, keywords: ["exhaust"], plus: { cost: 0 }, text: "能力:這局之後的媒體牌 +25%" },
{ id: "fieldwork", name: "蹲點研究", art: "study", cost: 1, money: 0, rarity: "rare", tags: ["ground"], target: "none", effect: { kind: "power", power: "ground" }, keywords: ["exhaust"], plus: { cost: 0 }, text: "能力:這局之後的地面牌 +15%" },
@ -188,13 +188,13 @@ export const CARDS: readonly CardDef[] = [
{ id: "origin_clinic", name: "巡迴義診", art: "visit_associations", cost: 1, money: 0, rarity: "rare", tags: ["ground", "origin"], target: "town", effect: { kind: "gain", base: 1500 }, bonus: [{ trait: "old", mult: 2 }], text: "該區 +{n};長輩多 ×2" },
{ id: "origin_legal", name: "法律諮詢站", art: "open_office", cost: 1, money: 0, rarity: "rare", tags: ["defend", "press", "origin"], target: "none", effect: { kind: "clarify", cut: 0.4, base: 1380, momentum: 0 }, text: "對手這週的批評剩四成;全市 +{n}" },
{ id: "origin_lecture", name: "公共政策講座", art: "forum", cost: 1, money: 0, rarity: "rare", tags: ["press", "media", "origin"], target: "city", effect: { kind: "city", base: 1840, momentum: 1 }, text: "全市 +{n},聲勢 +1" },
{ id: "origin_fanmeet", name: "粉絲見面會", art: "concert", cost: 1, money: 100, rarity: "rare", tags: ["rally", "media", "origin"], target: "town", effect: { kind: "rally", base: 2300, momentum: 1, spill: 0.2 }, bonus: [{ trait: "young", mult: 1.3 }], text: "該區 +{n},聲勢 +1;年輕人多 ×1.3" },
{ id: "origin_fanmeet", name: "粉絲見面會", art: "concert", cost: 1, money: 100, rarity: "rare", tags: ["rally", "media", "origin"], target: "town", effect: { kind: "rally", base: 2300, momentum: 1, spill: 0.2 }, bonus: [{ trait: "young", mult: 1.3 }], text: "該區 +{n}、擴散到隔壁區合計四成,聲勢 +1;年輕人多 ×1.3" },
{ id: "origin_stream", name: "直播開箱", art: "facebook_live", cost: 1, money: 0, rarity: "rare", tags: ["media", "online", "origin"], target: "city", effect: { kind: "gamble", base: 1840, chance: 0.4, hit: 3, miss: 1 }, text: "全市 +{n};40% 爆紅 ×3" },
{ id: "origin_clan", name: "家族老樁腳", art: "recruit_machine", cost: 1, money: 0, rarity: "rare", tags: ["org", "origin"], target: "none", effect: { kind: "base", base: 1380, towns: 3 }, text: "你領先最多的 3 區各 +{n}" },
{ id: "origin_assembly", name: "里民大會", art: "door_to_door", cost: 1, money: 0, rarity: "rare", tags: ["ground", "origin"], target: "town", effect: { kind: "gain", base: 1840 }, bonus: [{ trait: "rural", mult: 1.3 }], text: "該區 +{n};地廣人稀 ×1.3" },
{ id: "origin_donors", name: "企業募款餐會", art: "big_donor", cost: 1, money: 0, rarity: "rare", tags: ["money", "origin"], target: "none", effect: { kind: "money", base: 450, perMomentum: 20 }, text: "資金 +{m} 萬;聲勢越高募越多" },
{ id: "origin_record", name: "施政成績單", art: "announce_policy", cost: 1, money: 0, rarity: "rare", tags: ["press", "media", "origin"], target: "city", effect: { kind: "city", base: 2530 }, text: "全市 +{n}" },
{ id: "origin_petition", name: "街頭連署", art: "grassroots_walk", cost: 1, money: 0, rarity: "rare", tags: ["ground", "origin"], target: "town", effect: { kind: "spread", base: 1380, spill: 0.5 }, text: "該區 +{n},隔壁每一區也有一半" },
{ id: "origin_petition", name: "街頭連署", art: "grassroots_walk", cost: 1, money: 0, rarity: "rare", tags: ["ground", "origin"], target: "town", effect: { kind: "spread", base: 1380, spill: 0.5 }, text: "該區 +{n},擴散到隔壁區合計一樣多" },
// ── 劇情給的牌(不會出現在獎勵裡) ──
{ id: "sympathy", name: "悲情催票", art: "live_pledge", cost: 1, money: 0, rarity: "status", tags: ["rally"], target: "none", effect: { kind: "city", base: 2300, momentum: 1 }, keywords: ["exhaust"], text: "消耗;全市 +{n},聲勢 +1" },
@ -356,8 +356,9 @@ export const EVENT_BY_ID = new Map(EVENTS.map((e) => [e.id, e]));
export const INTENT_BASE = {
canvass: 1720,
rally: 3450,
tv: 4830,
online: 2990,
// 全市的廣告擋不住(只能打對台搶版面),比你的同類牌小一點(docs/26)
tv: 4140,
online: 2760,
attack: 2880,
smear: 2070,
stake: 2880,

View File

@ -14,3 +14,5 @@ export * from "./view.ts";
export * from "./bots.ts";
export * from "./tutorial.ts";
export * from "./ultimate.ts";
export * from "./battle.ts";
export * from "./calibration.ts";

View File

@ -18,23 +18,30 @@ export function addStatus(s: RunState, id: string): boolean {
}
export const momentumMax = (s: RunState): number => MOMENTUM_MAX + (has(s, "rally_king") ? 2 : 0);
export const eventOf = (s: RunState): EventDef => EVENT_BY_ID.get(s.event) ?? EVENTS[0]!;
/** 逆風難度達到第 n 級 */
export const asc = (s: RunState, n: number): boolean => s.options.ascension >= n;
/** 逆風難度每一級多的不利條件(docs/22) */
export const ASCENSION: readonly string[] = [
"標準難度",
"對手強度 +12%",
"起始資金 −40%",
"每週收入 −40%",
"下一站只有 2 個選項,選牌、選幕僚也只有 2 個",
"開局牌組多一張「人情包袱」",
"對手從第 4 週起每週多 1 個行動",
"對手開局聲勢 2",
"你的牌效果 −8%",
"黑函危機加倍,壞事件更常出現",
"開局落後 3 個百分點",
];
/**
* 逆風難度(docs/22、26):照這個順序一級加一條,每一級都要感覺得到(依模擬排過,「打得好」每一級少約 5–7 個百分點的勝率)。
* 規則裡用 ascOn(s, id) 查這一條開了沒,不寫死第幾級
*/
export const ASC_RULES = [
{ id: "rival", text: "對手強度 +5%" },
{ id: "money", text: "資金吃緊:起始資金 −40%、每週收入 −40%,加開行程貴 100 萬" },
{ id: "rules", text: "對手開局多一條規則,後勁更強(每週變強的幅度 ×1.2)" },
{ id: "options", text: "下一站只有 2 個選項,選牌、選幕僚也只有 2 個" },
{ id: "momentum", text: "對手開局聲勢 2;開局牌組多一張「人情包袱」" },
{ id: "battle", text: "對手全力搶戰場:在戰場的掃街、拉票 ×1.7(一般 ×1.5)" },
{ id: "late", text: "最後一週(選前之夜)對手多 1 個行動" },
{ id: "weak", text: "你的牌效果 −5%" },
{ id: "crisis", text: "負面選戰:對手的批評 +30%,黑函危機加倍、沒回應記者追問的掉票加倍,壞事件更常出現" },
{ id: "gap", text: "開局落後 2.5 個百分點" },
] as const;
export type AscRule = (typeof ASC_RULES)[number]["id"];
/** 這一條在第幾級開始 */
const ASC_LEVEL = new Map<AscRule, number>(ASC_RULES.map((r, i) => [r.id, i + 1]));
/** 逆風 ascension 級有沒有這一條(開局還沒有狀態時用) */
export const ascAt = (ascension: number, id: AscRule): boolean => ascension >= ASC_LEVEL.get(id)!;
export const ascOn = (s: RunState, id: AscRule): boolean => ascAt(s.options.ascension, id);
export const ASCENSION: readonly string[] = ["標準難度", ...ASC_RULES.map((r) => r.text)];
export const MAX_ASCENSION = ASCENSION.length - 1;
/** 每週事件對這些標籤的倍率(雙方都適用);地方事件週只算打在有那個特色的區 */
@ -76,10 +83,15 @@ export function spread(towns: readonly TownState[], total: number, weight: (t: T
return w.map((x) => (total * x) / sum);
}
/** 全市加票(正)或掉票(負),依人口分配;回傳實際變化 */
/** 媒體焦點(docs/26):全市的牌、廣告,本週戰場分到的比例 ×BATTLE_FOCUS(雙方都一樣),空戰也能搶戰場 */
export const BATTLE_FOCUS = 2;
export const battleFocus = (s: RunState, t: TownState): number => (s.battle && s.battle.week === s.week && s.battle.town === t.code ? BATTLE_FOCUS : 1);
/** 全市加票(正)或掉票(負),依人口分配(本週戰場多分一些);回傳實際變化 */
export function cityVotes(s: RunState, total: number, side: "you" | "rival" = "you", weight?: (t: TownState) => number): number {
if (total >= 0) {
const parts = spread(s.towns, total, weight ?? ((t) => t.voters));
const w = weight ?? ((t: TownState) => t.voters);
const parts = spread(s.towns, total, (t) => w(t) * battleFocus(s, t));
return s.towns.reduce((a, t, i) => a + moveVotes(t, parts[i]!, side), 0);
}
const parts = spread(s.towns, -total, (t) => t[side]);

View File

@ -1,8 +1,14 @@
import type { RogueArchetype, RogueIntentKind } from "@election2026/protocol";
import { RIVAL_HOME_MULT } from "./archetypes.ts";
import { INTENT_BASE, INTENT_LABELS, INTENT_TAGS } from "./data.ts";
import { addRivalMomentum, addStatus, asc, cityVotes, eventMult, eventOf, has, isArch, loseVotes, moveVotes, spread } from "./mechanics.ts";
import { pickWeighted, round10, type Intent, type RivalStyle, type RunState, type TownState } from "./state.ts";
import { addRivalMomentum, addStatus, battleFocus, ascOn, cityVotes, eventMult, eventOf, has, isArch, loseVotes, moveVotes, spread } from "./mechanics.ts";
import { BATTLE_PUSH, battleTown } from "./battle.ts";
import { spillShare } from "./cards.ts";
import { mapFactor } from "./calibration.ts";
/** 對手在戰場的行動倍率:逆風「全力搶戰場」×1.7;造勢本來就大,不再加倍(不然第一週就搶不下來) */
const battlePush = (s: RunState, kind: RogueIntentKind): number => (kind === "rally" ? 1 : ascOn(s, "battle") ? 1.7 : BATTLE_PUSH);
import { pickWeighted, round10, totals, type Intent, type RivalStyle, type RunState, type TownState } from "./state.ts";
/**
* 對手 AI(docs/21、22):每週一開始就把要做的事亮在地圖上(像《殺戮尖塔》的敵人意圖),週末才執行。
@ -11,7 +17,7 @@ import { pickWeighted, round10, type Intent, type RivalStyle, type RunState, typ
*/
/** 對手整體強度(平衡報告調整用) */
export const RIVAL_POWER = 0.92;
export const RIVAL_POWER = 1.07;
/** 每週變強多少 */
export const RIVAL_GROWTH = 0.035;
/** 第 5 週預告、第 7 週執行的大型造勢 */
@ -22,13 +28,13 @@ export const BIG_RALLY_MULT = 2;
export const RIVAL_TRAITS: Record<RivalStyle, { name: string; text: string }> = {
balanced: { name: "後發制人", text: "前期比較弱,每週變強的幅度比較大" },
ground: { name: "組織戰", text: "佈樁的盾 ×1.4,常常跑基層" },
air: { name: "空戰", text: "電視、網路廣告效果 ×1.2" },
air: { name: "空戰", text: "常打電視、網路廣告(全市的,樁腳擋不住;打對台可以搶版面)" },
};
const STYLE_WEIGHTS: Record<RivalStyle, Record<RogueIntentKind, number>> = {
balanced: { canvass: 3, rally: 1.5, tv: 1.5, online: 1.2, attack: 1, smear: 0.8, stake: 1 },
ground: { canvass: 4, rally: 2, tv: 0.8, online: 0.6, attack: 0.8, smear: 1, stake: 1.5 },
air: { canvass: 2, rally: 1, tv: 2.5, online: 2, attack: 1.2, smear: 0.6, stake: 0.6 },
air: { canvass: 2.8, rally: 1.3, tv: 1.4, online: 1.2, attack: 1.2, smear: 0.7, stake: 0.7 },
};
/**
@ -73,12 +79,12 @@ function rivalTypeMult(s: RunState, kind: RogueIntentKind, town: TownState | nul
*/
export const RIVAL_RULES: Record<string, { name: string; text: string; weight: Record<RivalStyle, number> }> = {
pundit: { name: "名嘴加持", text: "對手的批評 ×1.5;你澄清、事實查核的時候,對手聲勢 −1", weight: { balanced: 1, ground: 0.6, air: 1.5 } },
elder: { name: "地方大老", text: "對手插旗的區,你要領先 12 個百分點(一般 8)才翻得過來", weight: { balanced: 1, ground: 1.5, air: 0.6 } },
airwar: { name: "大打空戰", text: "對手每週多一個電視或網路廣告", weight: { balanced: 1, ground: 0.5, air: 1.5 } },
stronghold: { name: "鐵票區", text: "對手的本命區每週自動有一座樁腳", weight: { balanced: 1, ground: 1.5, air: 0.8 } },
elder: { name: "地方大老", text: "對手插旗的區:對手的行動 +15%,你要領先 12 個百分點(一般 8)才翻得過來", weight: { balanced: 1, ground: 1.5, air: 0.6 } },
airwar: { name: "大打空戰", text: "第 2 週起,對手每週多一個小型電視或網路廣告(一般的四成)", weight: { balanced: 1, ground: 0.5, air: 1.5 } },
stronghold: { name: "鐵票區", text: "對手的本命區每週自動有一座大樁腳(佈樁的 1.5 倍)", weight: { balanced: 1, ground: 1.5, air: 0.8 } },
rumor: { name: "網路謠言", text: "每週末隨機一區你的支持者被拉走一點;那週打探過對手就沒事", weight: { balanced: 1, ground: 0.8, air: 1.3 } },
carpet: { name: "地毯式掃街", text: "對手的掃街會擴散到隔壁區兩成", weight: { balanced: 1, ground: 1.5, air: 0.5 } },
image: { name: "形象牌", text: "你的爆料、比較文宣效果只剩一半;電視辯論贏的回合多 50%", weight: { balanced: 1, ground: 1, air: 1 } },
carpet: { name: "地毯式掃街", text: "對手的掃街會擴散到隔壁區,合計兩成", weight: { balanced: 1, ground: 1.5, air: 0.5 } },
image: { name: "形象牌", text: "你的爆料、比較文宣效果只剩一半;電視辯論輸的回合,你掉的票多 50%", weight: { balanced: 1, ground: 1, air: 1 } },
};
/** 網路謠言:每週被拉走的票(以全市 100 萬人為基準) */
const RUMOR_BASE = 900;
@ -88,7 +94,7 @@ export const hasRule = (s: RunState, id: string): boolean => (s.rivalRules ?? []
/** 開局抽對手規則(新手教學沒有) */
export function drawRivalRules(s: RunState): string[] {
if (s.options.tutorial) return [];
const n = asc(s, 5) ? 2 : 1;
const n = ascOn(s, "rules") ? 2 : 1;
const out: string[] = [];
for (let k = 0; k < n; k++) {
const id = pickWeighted(
@ -105,7 +111,7 @@ export function drawRivalRules(s: RunState): string[] {
export function applyRivalRules(s: RunState): void {
if (!hasRule(s, "stronghold")) return;
for (const t of s.towns.filter((x) => x.home === "rival")) {
t.rivalShield += intentAmount(s, "stake", t);
t.rivalShield += intentAmount(s, "stake", t) * 1.5;
s.log.push({ side: "rival", text: `鐵票區:${s.setup.rival.name}的本命區${t.name}樁腳到位`, town: t.code, votes: 0 });
}
}
@ -125,22 +131,51 @@ export function rumorAtWeekend(s: RunState, probed: boolean): void {
/** 每週最多幾個同一類的行動 */
const LIMITS: Partial<Record<RogueIntentKind, number>> = { rally: 1, tv: 1, online: 1, attack: 1, smear: 1, stake: 1 };
export const intentsThisWeek = (s: RunState): number => (s.week <= 2 ? 2 : s.week < s.totalWeeks ? 3 : 4) + (asc(s, 6) && s.week >= 4 ? 1 : 0);
export const intentsThisWeek = (s: RunState): number => (s.week <= 2 ? 2 : s.week < s.totalWeeks ? 3 : 4) + (ascOn(s, "late") && s.week === s.totalWeeks ? 1 : 0) + (s.rivalPush?.extra ?? 0);
/**
* 對手急起直追(docs/26):第 PUSH_FROM 週起,對手落後 PUSH_GAP 個百分點以上,砸更多資源,這週多 1 個行動(落後兩倍再多 1 個)。
* 領先的人會被追著打,選情才會一路緊張到最後;畫面上寫出來(對手意圖的面板)
*/
export const PUSH_FROM = 3;
export const PUSH_GAP = 3;
export function rivalCatchUp(s: RunState): void {
if (s.options.tutorial || s.week < PUSH_FROM) {
s.rivalPush = null;
return;
}
const t = totals(s.towns);
const cast = t.you + t.rival + t.others || 1;
const gap = ((t.you - t.rival) / cast) * 100;
const extra = gap >= PUSH_GAP * 2 ? 2 : gap >= PUSH_GAP ? 1 : 0;
s.rivalPush = extra ? { extra, gap: Math.round(gap * 10) / 10 } : null;
}
/**
* 對手的規模依區數調整(docs/26):區越多,你越容易挑到有地區特色加成的區(對手的行動沒有特色加成),
* 所以區多的地圖(台南 37 區、總統 22 縣市)對手組織大一點、區少的(新竹市 3 區、立委選區)小一點。以 12 區為準:1 區 ×0.88、2 區 ×0.91、6 區 ×0.97、22 區 ×1.04、37 區 ×1.07
*/
export const rivalSize = (towns: number): number => {
const x = Math.log(Math.max(1, towns) / 12);
return x < 0 ? Math.max(0.88, 1 + 0.05 * x) : Math.min(1.08, 1 + 0.06 * x);
};
/** 總統大選:對手全國動員(政治生涯的最後一關,比縣市長難一點) */
export const PRESIDENT_POWER = 1.05;
export function rivalPower(s: RunState): number {
const style = s.setup.rivalStyle;
const growth = (style === "balanced" ? 0.05 : RIVAL_GROWTH) + (s.options.rivalArchetype === "newcomer" ? 0.005 : 0);
const growth = ((style === "balanced" ? 0.05 : RIVAL_GROWTH) + (s.options.rivalArchetype === "newcomer" ? 0.005 : 0)) * (ascOn(s, "rules") ? 1.2 : 1);
const start = style === "balanced" ? 0.92 : 1;
// 新手教學的老里長比較弱,照提示打就會贏
const tutorial = s.options.tutorial ? 0.4 : 1;
return RIVAL_POWER * start * tutorial * s.scale * (1 + growth * (s.week - 1)) * (1 + 0.08 * s.rivalMomentum) * (eventOf(s).rival ?? 1) * (asc(s, 1) ? 1.12 : 1);
const national = s.setup.countyCode === "00000" ? PRESIDENT_POWER : 1;
return RIVAL_POWER * start * tutorial * national * rivalSize(s.towns.length) * mapFactor(s.setup.scenarioId) * s.scale * (1 + growth * (s.week - 1)) * (1 + 0.08 * s.rivalMomentum) * (eventOf(s).rival ?? 1) * (ascOn(s, "rival") ? 1.05 : 1);
}
/** 對手性格帶來的倍率 */
const styleMult = (s: RunState, kind: RogueIntentKind): number => {
const style = s.setup.rivalStyle;
if (style === "ground" && kind === "stake") return 1.4;
if (style === "air" && (kind === "tv" || kind === "online")) return 1.2;
return 1;
};
@ -163,9 +198,12 @@ function intentAmount(s: RunState, kind: RogueIntentKind, town: TownState | null
const reach = town && kind !== "stake" ? town.reach : 1;
// 對手在自己的本命區比較強;媒體型被批評損失比較大(docs/25)
const home = town?.home === "rival" ? RIVAL_HOME_MULT : 1;
const weak = kind === "attack" && isArch(s, "media") ? 1.2 : 1;
const weak = kind === "attack" ? (isArch(s, "media") ? 1.2 : isArch(s, "integrity") ? 0.75 : 1) : 1;
const pundit = kind === "attack" && hasRule(s, "pundit") ? 1.5 : 1;
return round10(INTENT_BASE[kind] * rivalPower(s) * reach * eventMult(s, INTENT_TAGS[kind], town) * styleMult(s, kind) * rivalTypeMult(s, kind, town) * home * weak * pundit);
const negative = kind === "attack" && ascOn(s, "crisis") ? 1.3 : 1;
// 地方大老:對手插旗的區,對手的行動比較強
const elder = town?.flag === "rival" && hasRule(s, "elder") ? 1.15 : 1;
return round10(INTENT_BASE[kind] * rivalPower(s) * reach * eventMult(s, INTENT_TAGS[kind], town) * styleMult(s, kind) * rivalTypeMult(s, kind, town) * home * weak * pundit * negative * elder);
}
export function planIntents(s: RunState): Intent[] {
@ -186,6 +224,9 @@ export function planIntents(s: RunState): Intent[] {
// 你上週攻下對手的本命區:對手這週少一個行動(至少留一個)
const n = Math.max(1, intentsThisWeek(s) - (s.rivalStun ?? 0));
s.rivalStun = 0;
// 本週戰場:對手第一個在某一區拉票的行動(掃街、造勢、到你的票倉拉票)一定打在戰場,全力搶攻
const battle = battleTown(s);
let pushed = !battle || out.some((i) => i.town === battle.code);
for (let k = out.length; k < n; k++) {
const kinds = (Object.keys(style) as RogueIntentKind[]).filter((kind) => {
if ((count.get(kind) ?? 0) >= (LIMITS[kind] ?? 9)) return false;
@ -196,14 +237,18 @@ export function planIntents(s: RunState): Intent[] {
const kind = pickWeighted(s, kinds, weights)!;
count.set(kind, (count.get(kind) ?? 0) + 1);
const city = kind === "tv" || kind === "online" || kind === "attack";
const town = city ? null : chooseTown(s, kind, used);
const toBattle = !pushed && !city && kind !== "stake";
const town = city ? null : toBattle ? battle : chooseTown(s, kind, used);
if (town) used.add(town.code);
out.push({ id: `i${s.week}-${k}`, kind, town: town?.code ?? null, amount: intentAmount(s, kind, town), cut: 1 });
if (toBattle) pushed = true;
out.push({ id: `i${s.week}-${k}`, kind, town: town?.code ?? null, amount: round10(intentAmount(s, kind, town) * (toBattle ? battlePush(s, kind) : 1)), cut: 1, ...(toBattle ? { battle: true } : {}) });
}
// 這週剛好都是全市的行動:另外到戰場掃街
if (!pushed && battle) out.push({ id: `i${s.week}-battle`, kind: "canvass", town: battle.code, amount: round10(intentAmount(s, "canvass", battle) * battlePush(s, "canvass")), cut: 1, battle: true });
// 大打空戰:每週多一個電視或網路廣告(這週還沒排的那一種)
if (hasRule(s, "airwar")) {
if (hasRule(s, "airwar") && s.week >= 2) {
const kind = !count.get("tv") ? "tv" : !count.get("online") ? "online" : null;
if (kind) out.push({ id: `i${s.week}-air`, kind, town: null, amount: intentAmount(s, kind, null), cut: 1 });
if (kind) out.push({ id: `i${s.week}-air`, kind, town: null, amount: round10(intentAmount(s, kind, null) * 0.4), cut: 1 });
}
return out;
}
@ -226,7 +271,7 @@ export function applyRivalShields(s: RunState): void {
export const intentLabel = (s: RunState, i: Intent): string => {
const town = s.towns.find((t) => t.code === i.town)?.name;
return `${i.big ? "大型" : ""}${INTENT_LABELS[i.kind]}${town ? `・${town}` : "・全市"}`;
return `${i.big ? "大型" : ""}${INTENT_LABELS[i.kind]}${town ? `・${town}` : "・全市"}${i.battle ? "(搶戰場)" : ""}`;
};
/** 幕僚讓對手這個行動打折的倍率:批評遇到公關高手減半、你插旗的區有鐵票部隊減半 */
@ -255,7 +300,7 @@ export function executeIntent(s: RunState, i: Intent): void {
}
}
if (i.kind === "tv" || i.kind === "online") {
const parts = spread(s.towns, amount, (x) => x.voters * (x.traits.includes(i.kind === "tv" ? "old" : "young") ? 1.5 : 1));
const parts = spread(s.towns, amount, (x) => x.voters * (x.traits.includes(i.kind === "tv" ? "old" : "young") ? 1.5 : 1) * battleFocus(s, x));
const net = s.towns.reduce((a, x, k) => a + moveVotes(x, parts[k]!, "rival"), 0);
s.log.push({ side: "rival", text: `${name}${label}`, town: null, votes: -Math.round(net) });
return;
@ -290,13 +335,14 @@ export function executeIntent(s: RunState, i: Intent): void {
}
const net = moveVotes(t, rest, "rival");
s.log.push({ side: "rival", text: `${name}${label}`, town: t.code, votes: -Math.round(net) });
if (i.kind === "rally") addRivalMomentum(s, i.big ? 3 : 2);
// 地毯式掃街:擴散到隔壁區兩成(隔壁區的樁腳照樣先擋)
// 造勢被打對台壓到一半以下就冷場,對手不加聲勢(docs/26:擋對手不只是少掉票)
if (i.kind === "rally" && i.cut >= 0.5) addRivalMomentum(s, i.big ? 3 : 2);
if (i.kind === "rally" && i.cut < 0.5) s.log.push({ side: "you", text: `${name}的造勢被你打對台,現場冷清,對手聲勢沒漲`, town: t.code, votes: 0 });
// 地毯式掃街:擴散到隔壁區合計兩成(和你的擴散一樣不看鄰區數;隔壁區的樁腳照樣先擋)
if (i.kind === "canvass" && hasRule(s, "carpet")) {
for (const code of t.neighbors) {
const n = s.towns.find((x) => x.code === code);
if (!n) continue;
const spill = amount * 0.2;
const near = t.neighbors.flatMap((code) => s.towns.find((x) => x.code === code) ?? []);
for (const n of near) {
const spill = amount * spillShare(near.length, 0.1).each;
const stop = Math.min(n.shield, spill);
n.shield -= stop;
const got = moveVotes(n, spill - stop, "rival");

View File

@ -5,7 +5,7 @@ import { AFFINITY_WEIGHT, ARCHETYPES } from "./archetypes.ts";
import { STOP_EVENTS, STOP_EVENT_BY_ID } from "./content.ts";
import { REWARD_CARDS, cardDef, upgradable } from "./data.ts";
import { isLocked, UNLOCKS } from "./unlocks.ts";
import { addMomentum, asc, cityVotes, has, isArch, moveVotes } from "./mechanics.ts";
import { addMomentum, ascOn, cityVotes, has, isArch, moveVotes } from "./mechanics.ts";
import { applyOutcome, choiceBlocked, rollChoice } from "./scenes.ts";
import type { MiniGameKind } from "@election2026/protocol";
import { MAX_ADVISORS, TOTAL_WEEKS, gainCard, newCard, pickWeighted, rand, round10, shuffle, type RunState, type ShopItem, type Stop, type StopKind } from "./state.ts";
@ -48,7 +48,7 @@ export const STOP_LABELS: Record<StopKind, { title: string; text: string }> = {
export const ELITE_GOAL = 3000;
const deckOf = (s: RunState) => [...s.draw, ...s.discard, ...s.hand];
const optionCount = (s: RunState) => (asc(s, 4) ? 2 : 3);
const optionCount = (s: RunState) => (ascOn(s, "options") ? 2 : 3);
const advisorOpen = (s: RunState) => s.advisors.length < MAX_ADVISORS;
/** 這週結束後可以去的下一站 */

View File

@ -5,10 +5,11 @@ import type { IslandPerk, PolicySpec } from "@election2026/protocol";
import { MINOR_REPORTER_MULT, ORIGINS, PARTY_LEAN_SHIFT, type Background } from "@election2026/protocol";
import { CARD_BY_ID, cardDef, EVENTS, findCard, hasKeyword, REPORTER_PENALTY, STARTER_DECK, upgradable } from "./data.ts";
import { perkLevels, policyCardId, policySlots } from "./meta.ts";
import { addMomentum, asc, cityVotes, drawCards, eventOf, flagOwner, has, isArch, moveVotes, updateFlags } from "./mechanics.ts";
import { addMomentum, ascAt, ascOn, cityVotes, drawCards, eventOf, flagOwner, has, isArch, moveVotes, updateFlags } from "./mechanics.ts";
import { featsOf } from "./feats.ts";
import { isLocked } from "./unlocks.ts";
import { announceBigRally, applyRivalRules, applyRivalShields, drawRivalRules, executeIntent, planIntents, rumorAtWeekend } from "./rival.ts";
import { announceBigRally, applyRivalRules, applyRivalShields, drawRivalRules, executeIntent, planIntents, rivalCatchUp, rumorAtWeekend } from "./rival.ts";
import { settleBattle, startBattle } from "./battle.ts";
import { pickRoute, pickStop, prepareRoute } from "./route.ts";
import { applyUltimate, chargeUltimate, secondChance } from "./ultimate.ts";
import { committedShares, makeSchedule, resolveScene, sceneFor } from "./scenes.ts";
@ -42,20 +43,18 @@ export { blockedReason, cardCost, comboBonus, COMBO_MAX, COMBO_STEP, counterable
export { committedShares } from "./scenes.ts";
export { SKIP_MONEY } from "./route.ts";
/** 組織型本命區每週自動的樁腳(和「拜託里長佈樁」的基礎值一樣) */
const STAKE_SHIELD = 2880;
/** 開票時,每一點聲勢讓還沒表態的人有 1.5% 投給該陣營 */
export const MOMENTUM_TURNOUT = 0.015;
/** 逆風 10 級:開局落後幾個百分點 */
const ASC10_GAP = 0.03;
/** 逆風最高級:開局落後幾個百分點 */
const ASC10_GAP = 0.025;
function pickEvent(s: RunState): string {
if (s.week === 1 || s.options.tutorial) return "calm";
// 行事曆上的地方事件週
const local = s.schedule?.local?.find((l) => l.week === s.week);
if (local) return local.event;
const badBoost = asc(s, 9) ? 2 : 1;
const badBoost = ascOn(s, "crisis") ? 2 : 1;
return pickWeighted(
s,
EVENTS.filter((e) => !e.local && e.id !== s.event),
@ -85,6 +84,7 @@ function startWeek(s: RunState): void {
s.energyNext = 0;
s.buffs = [];
s.flipDraws = 0;
s.rushed = false;
s.groundPlayed = 0;
s.turnaround = false;
s.memeUsed = false;
@ -95,7 +95,8 @@ function startWeek(s: RunState): void {
const start = committedShares(s);
s.tally = { gained: 0, lost: 0, blocked: 0, startYou: start.you, startRival: start.rival };
const volunteers = s.week === 1 ? (s.options.perks?.volunteer ?? 0) : 0;
drawCards(s, HAND_SIZE + (has(s, "youth_corps") ? 1 : 0) - (has(s, "scheduler") ? 1 : 0) + volunteers);
drawCards(s, HAND_SIZE + (has(s, "youth_corps") ? 1 : 0) - (has(s, "scheduler") ? 1 : 0) + volunteers + (s.battleDraw ?? 0));
s.battleDraw = 0;
if (has(s, "party_org")) s.hand.push(newCard(s, "walkx"));
if (s.partyStorm === s.week) {
s.hand.push(newCard(s, "storm"));
@ -103,6 +104,8 @@ function startWeek(s: RunState): void {
}
if (has(s, "mascot") && s.momentum < 1) s.momentum = 1;
announceBigRally(s);
rivalCatchUp(s);
startBattle(s);
s.intents = planIntents(s);
applyRivalShields(s);
applyRivalRules(s);
@ -112,14 +115,6 @@ function startWeek(s: RunState): void {
const t = s.towns.find((x) => x.code === deal.town);
if (t) deal.start = t.you - t.rival;
}
// 組織型:本命區每週自動有一座樁腳(和「拜託里長佈樁」一樣大)
if (isArch(s, "organization")) {
for (const t of s.towns.filter((x) => x.home === "you")) {
const shield = STAKE_SHIELD * s.scale * (1 + 0.1 * (s.options.abilities?.organization ?? 0));
t.shield += shield;
s.log.push({ side: "you", text: `組織型:本命區${t.name}的樁腳自動到位`, town: t.code, votes: 0 });
}
}
s.scene = sceneFor(s, prev);
// 記者堵麥不擋出牌:變成這週要處理的事件,結束這週前回答就好;辯論、黑函是大場面,先處理
s.phase = s.scene && s.scene.kind !== "press" ? "scene" : "plan";
@ -149,7 +144,7 @@ function starterDeck(options: RunOptions, home: boolean): string[] {
else deck.push(arch.card);
}
if (home) deck.push("homecoming");
if (options.ascension >= 5) deck.push("favor");
if (ascAt(options.ascension, "momentum")) deck.push("favor");
return deck;
}
@ -174,7 +169,9 @@ export function createRun(setup: RogueSetup, runId: string, seed: number, opts:
};
const voters = setup.towns.reduce((a, t) => a + t.voters, 0);
const meanVoters = voters / (setup.towns.length || 1);
const gap = options.ascension >= 10 ? ASC10_GAP / 2 : 0;
// 區的大小係數再除以「依人口加權的平均」(docs/26):大區特別大的地圖(總統、台南)不會因為大家都打大區而整體變強
const reachNorm = setup.towns.reduce((a, t) => a + t.voters * townReach(t.voters, meanVoters), 0) / (voters || 1) || 1;
const gap = ascAt(options.ascension, "gap") ? ASC10_GAP / 2 : 0;
const { towns, ...rest } = setup;
// 本命區(docs/25):雙方各自底盤最強的區;新手教學沒有
const youHome = options.tutorial ? [] : homeTowns(towns, "you");
@ -193,9 +190,9 @@ export function createRun(setup: RogueSetup, runId: string, seed: number, opts:
energy: BASE_ENERGY,
energyMax: BASE_ENERGY,
energyNext: 0,
money: Math.round(setup.money * (options.ascension >= 2 ? 0.6 : 1) * (options.archetype === "newcomer" ? 0.7 : 1)),
money: Math.round(setup.money * (ascAt(options.ascension, "money") ? 0.6 : 1) * (options.archetype === "newcomer" ? 0.7 : 1)),
momentum: 0,
rivalMomentum: options.ascension >= 7 ? 2 : 0,
rivalMomentum: ascAt(options.ascension, "momentum") ? 2 : 0,
leverage: 0,
towns: towns.map((t) => {
const committed = t.voters * (1 - UNDECIDED_START);
@ -217,7 +214,7 @@ export function createRun(setup: RogueSetup, runId: string, seed: number, opts:
rivalShield: 0,
office: 0,
played: [],
reach: townReach(t.voters, meanVoters),
reach: townReach(t.voters, meanVoters) / reachNorm,
flag: null,
was: null,
home: youHome.includes(t.code) ? "you" : rivalHome.includes(t.code) ? "rival" : null,
@ -389,10 +386,6 @@ function settleContract(s: RunState): void {
s.log.push({ side: "you", text: `地方派系談判成功:升級 ${ups.length} 張牌`, town: t.code, votes: 0 });
}
/** 財務型:週末手上每 100 萬資金全市加幾票(最多算 FINANCE_CAP 萬) */
export const FINANCE_PER_100 = 150;
export const FINANCE_CAP = 1000;
/** 樁腳網:週末還沒被用掉的樁腳,這麼多變成你的票 */
export const NETWORK_SHARE = 0.3;
@ -444,15 +437,16 @@ export function endWeek(state: RunState): RunState | { error: string } {
if (reporters > 0 && !has(s, "crisis_team")) {
const integrity = 1 - 0.15 * (s.options.abilities?.integrity ?? 0);
const fresh = s.options.origin?.kind === "minor" ? MINOR_REPORTER_MULT : 1;
const lost = cityVotes(s, -REPORTER_PENALTY * s.scale * reporters * integrity * fresh);
const lost = cityVotes(s, -REPORTER_PENALTY * s.scale * reporters * integrity * fresh * (ascOn(s, "crisis") ? 2 : 1));
s.log.push({ side: "rival", text: `沒回應記者追問 ×${reporters}`, town: null, votes: Math.round(lost) });
}
s.momentum = Math.max(0, s.momentum - 1);
s.rivalMomentum = Math.max(0, s.rivalMomentum - 1);
settleBattle(s);
updateFlags(s);
const flags = s.towns.filter((t) => t.flag === "you").length;
const income = Math.round(
WEEKLY_INCOME * (eventOf(s).income ?? 1) * (asc(s, 3) ? 0.6 : 1) +
WEEKLY_INCOME * (eventOf(s).income ?? 1) * (ascOn(s, "money") ? 0.6 : 1) +
(has(s, "tycoon") ? 150 : 0) +
flags * FLAG_INCOME +
(has(s, "cfo") ? 60 * s.energy : 0) +
@ -461,11 +455,6 @@ export function endWeek(state: RunState): RunState | { error: string } {
) * (isArch(s, "integrity") ? 0.8 : 1);
s.money += income;
s.log.push({ side: "system", text: `本週收入 ${income} 萬${flags ? `(含 ${flags} 面旗的小額捐款)` : ""}`, town: null, votes: 0 });
// 財務型:錢多好辦事,週末依手上的資金自動加票(花不掉的錢也有用)
if (isArch(s, "finance") && s.money >= 100) {
const got = cityVotes(s, (Math.min(s.money, FINANCE_CAP) / 100) * FINANCE_PER_100 * s.scale, "you");
s.log.push({ side: "you", text: "財務型:手上的資金換成廣告曝光", town: null, votes: Math.round(got) });
}
// 精算師:存款利息
if (has(s, "actuary")) {
const interest = Math.min(50, Math.floor(s.money / 100) * 5);
@ -499,6 +488,30 @@ export function endWeek(state: RunState): RunState | { error: string } {
return s;
}
/** 加開行程(docs/26):每週一次,花資金換 1 點體力;錢才有地方用 */
export const RUSH_PRICE = 250;
/** 逆風「資金吃緊」貴 100 萬;財務型八折 */
export const rushPrice = (s: RunState): number => Math.round((RUSH_PRICE + (ascOn(s, "money") ? 100 : 0)) * (isArch(s, "finance") ? 0.8 : 1));
export function rushBlocked(s: RunState): string | null {
if (s.phase !== "plan") return "現在不能加開行程";
if (s.options.tutorial) return "新手教學不能加開行程";
if (s.rushed) return "這週已經加開過了";
if (s.money < rushPrice(s)) return "資金不夠";
return null;
}
export function rush(state: RunState): RunState | { error: string } {
const reason = rushBlocked(state);
if (reason) return { error: reason };
const s = cloneState(state);
s.log = [];
const price = rushPrice(s);
s.money -= price;
s.energy += 1;
s.rushed = true;
s.log.push({ side: "you", text: `加開行程:花 ${price} 萬,體力 +1`, town: null, votes: 0 });
return s;
}
/** 放大絕招(ultimate.ts):kind 是哪一招,score 是小遊戲分數,towns 是掃街馬拉松挑的區 */
export function ultimate(state: RunState, kind: MiniGameKind, score: number, towns?: readonly string[]): RunState | { error: string } {
const s = cloneState(state);

View File

@ -16,7 +16,7 @@ import {
type PressTrigger,
} from "./content.ts";
import { EVENTS, REWARD_CARDS, findCard, upgradable } from "./data.ts";
import { addMomentum, addRivalMomentum, addStatus, asc, cityVotes, has, isArch, loseVotes, spread } from "./mechanics.ts";
import { addMomentum, addRivalMomentum, addStatus, ascOn, cityVotes, has, isArch, loseVotes, spread } from "./mechanics.ts";
import { BIG_RALLY_WEEK } from "./rival.ts";
import { isLocked } from "./unlocks.ts";
import { MAX_ADVISORS, TOTAL_WEEKS, addTally, gainCard, newCard, pickWeighted, rand, shuffle, totals, type DebateArg, type DebateMove, type RunState, type Scene, type Schedule } from "./state.ts";
@ -262,7 +262,7 @@ function publishPoll(s: RunState): void {
}
function crisisScene(s: RunState): Scene {
const amount = CRISIS_BASE * s.scale * (asc(s, 9) ? 2 : 1) * (has(s, "lawyer") ? 0.5 : 1) * (1 - 0.12 * (s.options.abilities?.integrity ?? 0)) * (isArch(s, "integrity") ? 0.5 : 1);
const amount = CRISIS_BASE * s.scale * (ascOn(s, "crisis") ? 2 : 1) * (has(s, "lawyer") ? 0.5 : 1) * (1 - 0.12 * (s.options.abilities?.integrity ?? 0)) * (isArch(s, "integrity") ? 0.5 : 1);
s.crisisDone = true;
return { kind: "crisis", amount };
}
@ -324,15 +324,15 @@ function resolveSceneInner(s: RunState, pick: number): string | null {
scene.combo += 1;
addMomentum(s, 1);
const mult = DEBATE_COMBO[Math.min(scene.combo, DEBATE_COMBO.length) - 1]! * (arg.policy ? DEBATE_POLICY_BONUS : 1);
// 對手規則「形象牌」:辯論贏的回合多 50%
const image = (s.rivalRules ?? []).includes("image") ? 1.5 : 1;
votes = Math.round(cityVotes(s, DEBATE_WIN * mult * image * s.scale));
votes = Math.round(cityVotes(s, DEBATE_WIN * mult * s.scale));
s.log.push({ side: "you", text: `${head},說服了觀眾!${scene.combo > 1 ? `${scene.combo} 連擊 ×${DEBATE_COMBO[Math.min(scene.combo, DEBATE_COMBO.length) - 1]},` : ""}聲勢 +1`, town: null, votes });
} else if (result === "lose") {
scene.losses += 1;
scene.combo = 0;
addRivalMomentum(s, 1);
votes = Math.round(cityVotes(s, -DEBATE_LOSS * s.scale));
// 對手規則「形象牌」:辯論輸的回合掉得比較多
const image = (s.rivalRules ?? []).includes("image") ? 1.5 : 1;
votes = Math.round(cityVotes(s, -DEBATE_LOSS * image * s.scale));
s.log.push({ side: "rival", text: `${head},答非所問,對手佔上風`, town: null, votes });
} else {
scene.combo = 0;

View File

@ -47,6 +47,22 @@ function townStats(world: World): TownStats[] {
}
/** 和全縣市平均比,明顯偏高(或偏低)才算這區的特色 */
/**
* 起始資金(萬元):劇本的真實經費(元)壓縮到 MONEY_BASE~MONEY_BASE+MONEY_SPREAD(docs/26)。
* 真實經費從 300 萬到上億都有,直接用的話有錢的人每週都能加開行程,平衡會被縣市、候選人決定;
* 現在經費每多一倍多 MONEY_STEP 萬,有錢還是比較寬裕,但差距有上限
*/
/** 勢均力敵:其他候選人最強的一位最多是你們的幾成 */
export const OTHERS_CAP = 0.85;
export const MONEY_BASE = 500;
export const MONEY_STEP = 120;
export const MONEY_SPREAD = 500;
export function startingMoney(real: number): number {
const wan = Math.max(1, real / 10_000);
return MONEY_BASE + Math.round(Math.min(MONEY_SPREAD, Math.max(0, MONEY_STEP * Math.log2(wan / 300))) / 10) * 10;
}
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 }), {
@ -134,10 +150,14 @@ export function buildSetup(world: World, candidateId: string, opts: SetupOptions
: capped
? { you: capped.you / youAll, rival: capped.rival / rivalAll }
: { you: 1, rival: 1 };
// 勢均力敵:其他候選人裡最強的一位,最多只到你們拉平後的 OTHERS_CAP(三強鼎立的選區,玩第三名的人也有得打)
const otherTop = Math.max(0, ...agg.votes.map((v, i) => (i === ci || i === ri ? 0 : v)));
const level = (youAll + rivalAll) / 2;
const shrink = even && otherTop > level * OTHERS_CAP ? (level * OTHERS_CAP) / otherTop : 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 others = (shrink * Math.max(0, cast - row[ci]! - row[ri]!)) / cast;
const you = (row[ci]! * fix.you) / cast;
const rival = (row[ri]! * fix.rival) / cast;
// 拉平後各區比例可能不再加總 1,依比例縮回去
@ -166,8 +186,7 @@ export function buildSetup(world: World, candidateId: string, opts: SetupOptions
rival: people[ri]!,
others: people.filter((_, i) => i !== ci && i !== ri),
towns,
// 劇本的起始資金(元)換成萬元;遊戲裡的花費也是萬元
money: Math.max(300, Math.round(scenario.candidates[ci]!.startingMoney / 10_000)),
money: startingMoney(scenario.candidates[ci]!.startingMoney),
rivalStyle: style === "ground" || style === "air" ? style : "balanced",
// 自創角色以外都是真實人物
rivalReal: scenario.candidates[ri]!.id !== "custom",

View File

@ -99,7 +99,7 @@ export interface TownState {
rivalShield: number;
office: number;
played: string[];
/** 區的大小係數:人越多,同一個行程接觸到的人越多(見 townReach) */
/** 區的大小係數:人越多,同一個行程接觸到的人越多(見 townReach;開局時除以依人口加權的平均,全市平均是 1) */
reach: number;
/** 插旗:已表態的票裡領先 FLAG_LEAD 以上 */
flag: Owner;
@ -124,6 +124,8 @@ export interface Intent {
cut: number;
/** 預告過的大型行動 */
big?: boolean;
/** 本週戰場的搶攻(docs/26) */
battle?: boolean;
}
/** 電視辯論的三種論點:拿數據、講故事、反問對手 */
@ -200,6 +202,8 @@ export interface RunStats {
bought: number;
removed: number;
upgraded: number;
/** 贏下幾次本週戰場(舊存檔沒有) */
battles?: number;
}
export interface RunState {
@ -294,6 +298,14 @@ export interface RunState {
groundPlayed?: number;
turnaround?: boolean;
memeUsed?: boolean;
/** 本週戰場(docs/26):哪一區、這週開始時雙方在那區的票;舊存檔、新手教學沒有 */
battle?: { town: string; week: number; startYou: number; startRival: number } | null;
/** 上週贏下戰場:這週多抽幾張 */
battleDraw?: number;
/** 對手急起直追(docs/26):這週多幾個行動、開始時落後幾個百分點 */
rivalPush?: { extra: number; gap: number } | null;
/** 這週加開過行程了(花資金換體力,每週一次) */
rushed?: boolean;
stats: RunStats;
result: RogueResult | null;
}

View File

@ -5,16 +5,16 @@ import type { RunState, TownState } from "./state.ts";
/**
* 大絕招(18 第 57 項):落後很多也有機會翻盤,但要靠玩小遊戲玩得好。
* - 集氣:每週結算時,落後 1 個百分點集 8%(落後 10 點一週就集八成);領先時每週只集 2%;這週翻轉一區再 +10%。
* - 集氣:每週結算時,落後 1 個百分點集 15%(落後 7 點一週就集滿);領先時每週只集 4%;這週翻轉一區再 +10%。
* - 次數:基本 1 次;倒數第 3 週(8 週選戰的第 6 週)開始時,如果已經放過、還落後超過 8 個百分點,可以再放 1 次(直接集滿)。
* - 放招:挑一招、玩那個小遊戲(0–100 分)。威力=分數 × 落後倍率(落後 0 點 ×1、10 點 ×2、15 點以上 ×2.5)。
*/
export const ULT = {
/** 每落後 1 個百分點,每週集幾 % */
perPoint: 8,
perPoint: 15,
/** 領先或平手時每週集幾 % */
ahead: 2,
ahead: 4,
/** 這週翻轉一區(插旗換成你)多集幾 % */
flip: 10,
/** 第二次大絕招:落後超過幾個百分點(比例) */

View File

@ -13,7 +13,8 @@ import { ASCENSION, eventOf, has, momentumMax } from "./mechanics.ts";
import { BIG_RALLY_WEEK, RIVAL_RULES, RIVAL_TRAITS, RIVAL_TYPES, intentDamp, intentLabel } from "./rival.ts";
import { encounterById, fillVars, MINIGAME_INFO, pickInDoor, PRICES, SKIP_MONEY, STOP_LABELS } from "./route.ts";
import { bestArg, choiceBlocked, debateSure, scheduleOf } from "./scenes.ts";
import { electionForecast } from "./rules.ts";
import { electionForecast, rushBlocked, rushPrice } from "./rules.ts";
import { BATTLE_DRAW, BATTLE_MOMENTUM, battleProgress } from "./battle.ts";
import { MAX_ADVISORS, round10, totals, type CardInst, type RunState, type ShopItem, type Stop } from "./state.ts";
const fmt = (n: number): string => round10(n).toLocaleString("en-US");
@ -298,6 +299,16 @@ function contractOf(s: RunState): RogueView["contract"] {
return { town: t.code, name: t.name, goal: deal.goal, progress: Math.round(t.you - t.rival - (deal.start ?? 0)) };
}
/** 本週戰場的進度:雙方這週在那區淨增的票、對手週末預計在那裡拉的票(docs/26) */
function battleOf(s: RunState): RogueView["battle"] {
const p = battleProgress(s);
if (!p) return null;
const t = p.town;
// 對手週末在戰場預計拉的票:被打對台剩下的、你的樁腳先擋(到你的票倉拉票是讓你掉票,也算進去)
const plan = s.intents.filter((i) => i.town === t.code && i.kind !== "stake").reduce((a, i) => a + i.amount * i.cut * intentDamp(s, i), 0);
return { town: t.code, name: t.name, you: Math.round(p.you), rival: Math.round(p.rival), rivalPlan: Math.round(Math.max(0, plan - t.shield)), momentum: BATTLE_MOMENTUM, draw: BATTLE_DRAW };
}
/** 你的候選人特色:類型、技能、弱點、本命區(docs/25);新手教學、舊存檔是 null */
function identityOf(s: RunState): RogueView["identity"] {
const arch = s.options.archetype;
@ -379,7 +390,7 @@ export function toView(s: RunState): RogueView {
flag: t.flag,
home: t.home ?? null,
})),
intents: s.intents.map((i) => ({ id: i.id, kind: i.kind, label: intentLabel(s, i), town: i.town, amount: Math.round(i.amount), cut: i.cut, big: !!i.big })),
intents: s.intents.map((i) => ({ id: i.id, kind: i.kind, label: intentLabel(s, i), town: i.town, amount: Math.round(i.amount), cut: i.cut, big: !!i.big, battle: !!i.battle })),
nextBig: big && big.town ? { week: BIG_RALLY_WEEK, town: big.town, label: intentLabel(s, big), amount: Math.round(big.amount) } : null,
event: { id: ev.id, title: ev.title, text: ev.local ? `${ev.text}這週在:${s.towns.filter((t) => t.traits.includes(ev.local!)).map((t) => t.name).join("、")}` : ev.text },
hand: s.hand.map((c) => cardView(s, c)),
@ -398,6 +409,9 @@ export function toView(s: RunState): RogueView {
// 門上直接攤開內容(拜會地方的三張牌、幕僚、地方抉擇的選項),一次點選就拿到
route: s.route ? s.route.map((kind, i) => ({ kind, ...STOP_LABELS[kind], ...eliteText(s, s.routeStops?.[i]), preview: pickInDoor(kind) && s.routeStops?.[i] ? stopViewOf(s, s.routeStops[i]!) : null })) : null,
contract: contractOf(s),
battle: battleOf(s),
rivalPush: s.phase === "plan" || s.phase === "scene" ? (s.rivalPush ?? null) : null,
rush: s.options.tutorial ? null : { price: rushPrice(s), blocked: rushBlocked(s) },
nextRoute: s.route && s.nextRoute ? s.nextRoute.map((kind) => ({ kind, title: STOP_LABELS[kind].title })) : null,
poll: s.poll ?? null,
ultimate: s.options.tutorial

View File

@ -0,0 +1,244 @@
import { describe, expect, it } from "vitest";
import { BATTLE_PUSH, battleTown, settleBattle } from "../src/battle.ts";
import { createRun, endWeek, rush, RUSH_PRICE } from "../src/rules.ts";
import { PRESIDENT_POWER, PUSH_GAP, executeIntent, planIntents, rivalCatchUp, rivalPower, rivalSize } from "../src/rival.ts";
import { BUZZ_OTHER_STEP, BUZZ_STEP, boost, spillShare } from "../src/cards.ts";
import { cardDef } from "../src/data.ts";
import { cityVotes } from "../src/mechanics.ts";
import { MAP_CALIBRATION, mapFactor } from "../src/calibration.ts";
import { MONEY_BASE, MONEY_SPREAD, startingMoney } from "../src/setup.ts";
import { HAND_SIZE, type RunState } from "../src/state.ts";
import { tutorialSetup } from "../src/tutorial.ts";
import { toView } from "../src/view.ts";
import { SETUP, advance, must, toPlan } from "./fixtures.ts";
/** docs/26:本週戰場、對手急起直追、加開行程、起始資金 */
describe("本週戰場", () => {
it("每週標一個大區,對手一定在那裡全力搶攻", () => {
for (let seed = 1; seed <= 20; seed++) {
const s = createRun(SETUP, "r", seed);
const t = battleTown(s)!;
expect(t).toBeTruthy();
// 太小的區不會被挑(丙區只佔 7%,還是夠大;四區都有可能)
const push = s.intents.filter((i) => i.battle);
expect(push).toHaveLength(1);
expect(push[0]!.town).toBe(t.code);
expect(push[0]!.kind).not.toBe("stake");
expect(toView(s).battle?.town).toBe(t.code);
expect(toView(s).intents.find((i) => i.battle)?.label).toContain("搶戰場");
}
});
it("不會連續兩週同一區", () => {
let s = createRun(SETUP, "r", 3);
for (let w = 1; w < 5; w++) {
const before = battleTown(s)!.code;
s = advance(s, s.week + 1);
expect(battleTown(s)!.code).not.toBe(before);
}
});
it("淨增比對手多:聲勢 +1、下週多抽 1 張;比對手少:對手聲勢 +1", () => {
const s = toPlan(createRun(SETUP, "r", 7));
const t = battleTown(s)!;
const win = structuredClone(s) as RunState;
win.towns.find((x) => x.code === t.code)!.you += 50_000;
const m = win.momentum;
settleBattle(win);
expect(win.momentum).toBe(m + 1);
expect(win.battleDraw).toBe(1);
expect(win.stats.battles).toBe(1);
const lose = structuredClone(s) as RunState;
lose.towns.find((x) => x.code === t.code)!.rival += 50_000;
const r = lose.rivalMomentum;
settleBattle(lose);
expect(lose.rivalMomentum).toBe(r + 1);
expect(lose.battleDraw ?? 0).toBe(0);
});
it("贏了戰場,下週手牌多一張", () => {
let s = toPlan(createRun(SETUP, "r", 9));
s.towns.find((x) => x.code === battleTown(s)!.code)!.you += 80_000;
s = toPlan(must(endWeek(s)));
expect(s.week).toBe(2);
expect(s.hand.length).toBeGreaterThanOrEqual(HAND_SIZE + 1);
});
it("對手在戰場的行動比一般大", () => {
const s = createRun(SETUP, "r", 11);
const push = s.intents.find((i) => i.battle)!;
const same = s.intents.find((i) => !i.battle && i.kind === push.kind && i.town);
if (same) expect(push.amount).toBeGreaterThan(same.amount);
expect(BATTLE_PUSH).toBeGreaterThan(1);
});
it("新手教學沒有戰場、沒有加開行程", () => {
const s = createRun(tutorialSetup(), "t", 1, { tutorial: true, weeks: 3 });
expect(battleTown(s)).toBeNull();
expect(s.intents.some((i) => i.battle)).toBe(false);
expect(toView(s).battle).toBeNull();
expect(toView(s).rush).toBeNull();
expect("error" in rush(s)).toBe(true);
});
});
describe("對手急起直追", () => {
it(`第 3 週起落後 ${PUSH_GAP} 個百分點以上多 1 個行動,兩倍多 2 個`, () => {
let s = advance(createRun(SETUP, "r", 5), 3);
const base = s.intents.length;
const lead = (pp: number) => {
const x = structuredClone(s) as RunState;
// 每一區都拉成你領先 pp(已表態的票裡)
for (const t of x.towns) {
const both = t.you + t.rival;
const cast = both + t.others;
t.you = both / 2 + (cast * pp) / 2;
t.rival = both / 2 - (cast * pp) / 2;
}
rivalCatchUp(x);
return x.rivalPush;
};
expect(lead(0)).toBeNull();
expect(lead(0.04)?.extra).toBe(1);
expect(lead(0.08)?.extra).toBe(2);
s = toPlan(s);
expect(s.intents.length).toBeGreaterThanOrEqual(base);
});
it("前兩週不會", () => {
const s = createRun(SETUP, "r", 5);
for (const t of s.towns) {
t.you += t.rival * 0.5;
t.rival *= 0.5;
}
rivalCatchUp(s);
expect(s.rivalPush).toBeNull();
});
});
describe("加開行程", () => {
it("花資金換 1 點體力,每週一次", () => {
const s = toPlan(createRun(SETUP, "r", 2));
const r = must(rush(s));
expect(r.energy).toBe(s.energy + 1);
expect(r.money).toBe(s.money - RUSH_PRICE);
expect(rush(r)).toEqual({ error: "這週已經加開過了" });
expect(toView(r).rush?.blocked).toBe("這週已經加開過了");
// 下週又可以
const next = advance(must(endWeek(r)), 2);
expect(next.rushed).toBe(false);
});
it("錢不夠不行", () => {
const s = toPlan(createRun(SETUP, "r", 2));
s.money = RUSH_PRICE - 1;
expect(rush(s)).toEqual({ error: "資金不夠" });
});
});
describe("起始資金", () => {
it("真實經費壓縮到固定範圍,有錢的人還是比較多", () => {
expect(startingMoney(0)).toBe(MONEY_BASE);
expect(startingMoney(3_000_000)).toBe(MONEY_BASE);
expect(startingMoney(12_000_000)).toBeGreaterThan(startingMoney(6_000_000));
expect(startingMoney(2_000_000_000)).toBe(MONEY_BASE + MONEY_SPREAD);
});
});
describe("其他 docs/26 的規則", () => {
it("媒體焦點:全市加票時,本週戰場分到的比例加倍", () => {
const s = toPlan(createRun(SETUP, "r", 4));
const t = battleTown(s)!;
const share = (x: RunState) => {
const before = x.towns.map((y) => y.you);
cityVotes(x, 10_000);
return (x.towns.find((y) => y.code === t.code)!.you - before[x.towns.findIndex((y) => y.code === t.code)]!) / 10_000;
};
const focus = share(structuredClone(s) as RunState);
const plain = share({ ...(structuredClone(s) as RunState), battle: null });
expect(focus).toBeGreaterThan(plain * 1.5);
});
it("造勢被打對台壓到一半以下:對手聲勢不漲", () => {
const s = toPlan(createRun(SETUP, "r", 6));
const rally = { id: "x", kind: "rally" as const, town: "A", amount: 3000, cut: 1 };
const full = structuredClone(s) as RunState;
executeIntent(full, rally);
expect(full.rivalMomentum).toBe(s.rivalMomentum + 2);
const cold = structuredClone(s) as RunState;
executeIntent(cold, { ...rally, cut: 0.4 });
expect(cold.rivalMomentum).toBe(s.rivalMomentum);
});
it("聲量滾雪球:空戰牌每點 +5%,其他牌每點 +3%", () => {
const s = toPlan(createRun(SETUP, "r", 6));
const boosted = { ...(structuredClone(s) as RunState), powers: ["buzz"], buzz: 4 };
const canvass = cardDef("canvass")!;
const tv = cardDef("tv")!;
const town = s.towns[0]!;
expect(boost(boosted, canvass, town).mult / boost(s, canvass, town).mult).toBeCloseTo(1 + 4 * BUZZ_OTHER_STEP);
expect(boost(boosted, tv, null).mult / boost(s, tv, null).mult).toBeCloseTo(1 + 4 * BUZZ_STEP);
});
it("地方大老:對手插旗的區,對手的行動 +15%", () => {
const s = toPlan(createRun(SETUP, "r", 6));
for (const t of s.towns) t.flag = "rival";
const plain = planIntents({ ...(structuredClone(s) as RunState), rivalRules: [] });
const elder = planIntents({ ...(structuredClone(s) as RunState), rivalRules: ["elder"] });
const a = plain.find((i) => i.town && i.kind === "canvass" && !i.battle);
const b = elder.find((i) => i.id === a?.id);
if (a && b && b.kind === a.kind && b.town === a.town) expect(b.amount / a.amount).toBeCloseTo(1.15, 1);
});
});
describe("擴散不看鄰區數(docs/26)", () => {
it("擴散出去的合計固定;隔壁區不夠的留在本區", () => {
expect(spillShare(0, 0.25)).toEqual({ each: 0, rest: 0.5 });
expect(spillShare(1, 0.25)).toEqual({ each: 0.25, rest: 0.25 });
expect(spillShare(2, 0.25)).toEqual({ each: 0.25, rest: 0 });
const four = spillShare(4, 0.25);
expect(four.each * 4 + four.rest).toBeCloseTo(0.5);
});
});
describe("地圖大小(docs/26)", () => {
it("只有一區的選區:沒有本命區、沒有戰場", () => {
const one = { ...SETUP, towns: [SETUP.towns[0]!] };
const s = createRun(one, "r", 3);
expect(s.towns.every((t) => !t.home)).toBe(true);
expect(battleTown(s)).toBeNull();
expect(s.intents.some((i) => i.battle)).toBe(false);
});
it("對手規模依區數調整,總統大選全國動員", () => {
expect(rivalSize(12)).toBe(1);
expect(rivalSize(1)).toBeLessThan(rivalSize(3));
expect(rivalSize(37)).toBeGreaterThan(rivalSize(22));
expect(rivalSize(1)).toBeGreaterThanOrEqual(0.88);
expect(rivalSize(500)).toBeLessThanOrEqual(1.08);
// 測試用的假城市代碼剛好是 00000(全國),改成一般縣市比較
const city = createRun({ ...SETUP, countyCode: "10007" }, "r", 3);
const nation = createRun({ ...SETUP, countyCode: "00000" }, "r", 3);
expect(rivalPower(nation) / rivalPower(city)).toBeCloseTo(PRESIDENT_POWER);
});
it("區的大小係數:依人口加權的平均是 1", () => {
const s = createRun(SETUP, "r", 3);
const v = s.towns.reduce((a, t) => a + t.voters, 0);
expect(s.towns.reduce((a, t) => a + t.voters * t.reach, 0) / v).toBeCloseTo(1);
});
});
describe("逐張地圖校準(docs/26)", () => {
it("沒有校準的地圖是 1;勢均力敵和真實底盤共用同一個係數", () => {
expect(mapFactor("test")).toBe(1);
for (const [id, f] of Object.entries(MAP_CALIBRATION)) {
expect(mapFactor(`${id}-even`)).toBe(f);
expect(mapFactor(id)).toBe(f);
expect(f).toBeGreaterThanOrEqual(0.85);
expect(f).toBeLessThanOrEqual(1.2);
}
});
});

View File

@ -100,7 +100,7 @@ describe("本命區", () => {
});
describe("候選人類型", () => {
it("每種類型:專屬開局牌取代一張掃街(財務型多一張募款餐會),畫面有技能、弱點與依據", () => {
it("每種類型:專屬開局牌取代一張掃街(財務型是電視廣告),畫面有技能、弱點與依據", () => {
for (const [id, def] of Object.entries(ARCHETYPES)) {
const s = createRun(LEANED, "r", 1, { archetype: id as keyof typeof ARCHETYPES, archetypeBasis: "測試" });
const deck = deckIds(s);
@ -138,9 +138,9 @@ describe("候選人類型", () => {
if (a && b) expect(a.amount / b.amount).toBeCloseTo(1.2, 1);
});
it("組織型:本命區每週自動有樁腳;每週第一張佈樁不花體力;空戰牌 ×0.85", () => {
it("組織型:每週第一張佈樁不花體力;空戰牌 ×0.85(本命區自動樁腳依模擬拿掉,docs/26)", () => {
const s = createRun(LEANED, "r", 1, { archetype: "organization" });
expect(town(s, "C").shield).toBeGreaterThan(0);
expect(town(s, "C").shield).toBe(0);
const h = withHand(s, ["stake", "stake"]);
const one = ok(playCard(h, "t0", "A"));
expect(one.energy).toBe(9);
@ -148,12 +148,12 @@ describe("候選人類型", () => {
expect(two.energy).toBe(8);
});
it("資深型:辯論多一張論點、回應記者追問不花體力;年輕人多的區 ×0.9", () => {
it("資深型:辯論多一張論點、回應記者追問不花體力;年輕人多的區 ×0.95", () => {
const s = withHand(createRun(LEANED, "r", 1, { archetype: "eloquence" }), ["reporter", "canvass"]);
expect(ok(playCard(s, "t0", null)).energy).toBe(9);
const plain = withHand(createRun(LEANED, "r", 1), ["canvass"]);
const young = (x: RunState) => town(ok(playCard(x, x.hand.find((c) => c.id === "canvass")!.uid, "A")), "A").you - town(x, "A").you;
expect(young(s)).toBeCloseTo(young(plain) * 0.9);
expect(young(s)).toBeCloseTo(young(plain) * 0.95);
});
it("財務型:每週多 150 萬;清廉型:收入 −20%、記者追問不會被塞進牌組", () => {
@ -170,13 +170,13 @@ describe("候選人類型", () => {
expect([...attacked.draw, ...attacked.discard, ...attacked.hand].some((c) => c.id === "reporter")).toBe(false);
});
it("黑馬型:起始資金 −30%、每點聲勢 +12%、翻區多抽一張", () => {
it("黑馬型:起始資金 −30%、每點聲勢 +10%、翻區多抽一張", () => {
expect(createRun(LEANED, "r", 1, { archetype: "newcomer" }).money).toBe(Math.round(createRun(LEANED, "r", 1).money * 0.7));
const gain = (arch?: "newcomer") => {
const s = { ...withHand(createRun(LEANED, "r", 1, arch ? { archetype: arch } : {}), ["canvass"]), momentum: 2 };
return town(ok(playCard(s, "t0", "D")), "D").you - town(s, "D").you;
};
expect(gain("newcomer") / gain()).toBeCloseTo(1.24 / 1.16, 2);
expect(gain("newcomer") / gain()).toBeCloseTo(1.2 / 1.16, 2);
const s = withHand(createRun(LEANED, "r", 1, { archetype: "newcomer" }), []);
s.draw = [{ uid: "x1", id: "canvass" }];
takeLead(town(s, "B"), "you");

View File

@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import { runBot, type BotName } from "../src/bots.ts";
import { PRESS, STOP_EVENTS } from "../src/content.ts";
import { CARD_BY_ID, cardDef, PLUS_MULT, REPORTER_PENALTY } from "../src/data.ts";
import { ASC_RULES, ASCENSION } from "../src/mechanics.ts";
import { choose, COMBO_STEP, createRun, endWeek, playCard } from "../src/rules.ts";
import { townNeighbors } from "../src/setup.ts";
import { FLAG_LEAD, totals, UNDECIDED_START, type Intent, type RunState } from "../src/state.ts";
@ -56,9 +57,19 @@ describe("開局", () => {
expect([...hard.draw, ...hard.hand].some((c) => c.id === "favor")).toBe(true);
expect(hard.rivalMomentum).toBe(2);
const gap = (s: RunState) => (totals(s.towns).you - totals(s.towns).rival) / (totals(s.towns).voters * (1 - UNDECIDED_START));
expect(gap(easy) - gap(hard)).toBeCloseTo(0.03, 3);
expect(gap(easy) - gap(hard)).toBeCloseTo(0.025, 3);
expect(hard.startGap).toBeLessThan(easy.startGap);
});
it("逆風難度一級一條,文字和規則對得上", () => {
expect(ASCENSION).toHaveLength(11);
expect(ASC_RULES.map((r) => r.id)).toEqual(["rival", "money", "rules", "options", "momentum", "battle", "late", "weak", "crisis", "gap"]);
expect(createRun(SETUP, "r", 5, { ascension: 2 }).money).toBe(Math.round(createRun(SETUP, "r", 5).money * 0.6));
expect(createRun(SETUP, "r", 5, { ascension: 2 }).rivalRules).toHaveLength(1);
expect(createRun(SETUP, "r", 5, { ascension: 3 }).rivalRules).toHaveLength(2);
expect(createRun(SETUP, "r", 5, { ascension: 4 }).rivalMomentum).toBe(0);
expect(createRun(SETUP, "r", 5, { ascension: 5 }).rivalMomentum).toBe(2);
});
});
describe("出牌", () => {

View File

@ -3,7 +3,7 @@ import { BUZZ_STEP, EXPLAINER_STEP } from "../src/cards.ts";
import { cardDef, REWARD_CARDS } from "../src/data.ts";
import { executeIntent } from "../src/rival.ts";
import { prepareRoute } from "../src/route.ts";
import { createRun, endWeek, FINANCE_CAP, playCard } from "../src/rules.ts";
import { createRun, endWeek, playCard } from "../src/rules.ts";
import type { Stop } from "../src/state.ts";
import { FLAG_LEAD, type Intent, type RunState, type TownState } from "../src/state.ts";
import { isLocked, UNLOCKS } from "../src/unlocks.ts";
@ -219,15 +219,8 @@ describe("流派傾向", () => {
});
describe("財務型:錢多好辦事", () => {
it("週末依手上的資金加票,最多算 1,000 萬", () => {
const votes = (money: number) => {
const s = { ...bare([]), money, options: { ...bare([]).options, archetype: "finance" as const } };
return must(endWeek(s)).log.find((l) => l.text === "財務型:手上的資金換成廣告曝光")?.votes ?? 0;
};
// 收入進帳之後才算(收入也算進去);不是財務型沒有
expect(must(endWeek({ ...bare([]), money: 1000 })).log.some((l) => l.text.startsWith("財務型"))).toBe(false);
expect(votes(500)).toBeGreaterThan(0);
expect(votes(FINANCE_CAP * 3)).toBeCloseTo(votes(FINANCE_CAP), -1);
expect(votes(FINANCE_CAP)).toBeGreaterThan(votes(100) * 1.5);
it("錢用在加開行程、電視廣告;手上的錢不再自動換票(docs/26)", () => {
const s = { ...bare([]), money: 1000, options: { ...bare([]).options, archetype: "finance" as const } };
expect(must(endWeek(s)).log.some((l) => l.text.startsWith("財務型"))).toBe(false);
});
});

View File

@ -212,11 +212,11 @@ describe("對手規則", () => {
expect(run(["probe"]).votes).toBe(0);
});
it("地毯式掃街:對手掃街擴散到隔壁區兩成", () => {
it("地毯式掃街:對手掃街擴散到隔壁區一成", () => {
const s = bare(createRun(LEANED, "r", 1), ["carpet"]);
const before = town(s, "B").rival;
executeIntent(s, { id: "x", kind: "canvass", town: "A", amount: 1000, cut: 1 });
expect(town(s, "B").rival - before).toBeCloseTo(200, 0);
expect(town(s, "B").rival - before).toBeCloseTo(100, 0);
});
it("形象牌:你的比較文宣只剩一半", () => {

View File

@ -69,6 +69,7 @@ export const rogueApi = {
villages: (scenarioId: string) => request(`/api/rogue/villages/${encodeURIComponent(scenarioId)}`, RogueVillageList),
play: (id: string, uid: string, target: string | null) => request(`/api/rogue/runs/${encodeURIComponent(id)}/play`, RogueView, { uid, target }),
endWeek: (id: string) => request(`/api/rogue/runs/${encodeURIComponent(id)}/end-week`, RogueView, {}),
rush: (id: string) => request(`/api/rogue/runs/${encodeURIComponent(id)}/rush`, RogueView, {}),
/** 放大絕招:玩完小遊戲把分數送出(掃街馬拉松帶挑的區) */
ultimate: (id: string, kind: MiniGameKind, score: number, towns?: string[]) => request(`/api/rogue/runs/${encodeURIComponent(id)}/ultimate`, RogueView, { kind, score, towns }),
/** 劇情、下一站、站內的選擇;target 是要升級或拿掉的牌;option 是門上直接選的選項(選門+選項一次完成) */

View File

@ -403,7 +403,8 @@
.tm-next { justify-self: center; }
/* ── 預覽頁 ── */
.tm-preview-stages { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
.tm-preview-stages { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(120px, 100%), 1fr)); gap: 8px; }
.tm-preview-stages .tm-choice { min-width: 0; }
.tm-preview-stages .tm-choice { text-align: center; justify-items: center; }
.tm-preview-name { display: grid; gap: 4px; font-weight: 700; }
.tm-preview-name input { min-height: 44px; padding: 0 12px; border: 2px solid var(--ink); border-radius: 10px; font: inherit; font-size: 16px; background: var(--surface); color: var(--ink); }

View File

@ -382,6 +382,12 @@
@media (max-width: 820px) and (min-height: 960px) {
.cr-room { grid-template-rows: minmax(200px, 46fr) minmax(0, 54fr) auto; }
}
/* 橫放的手機:人物在左、衣櫃在右,按鈕在人物下面 */
@media (max-width: 820px) and (orientation: landscape) and (max-height: 500px) {
.cr-room { grid-template-columns: minmax(0, 0.85fr) minmax(0, 1.15fr); grid-template-rows: minmax(0, 1fr) auto; grid-template-areas: "stage panel" "cta panel"; }
.cr-save, .cr-go { min-height: 46px; }
.cr-go small { display: none; }
}
@media (max-width: 380px) {
.cr-origins { grid-template-columns: minmax(0, 1fr); }
}

View File

@ -7,8 +7,8 @@ import type { HeroCheer } from "../start/HeroDiorama.tsx";
/** 首頁示範用的五張牌(數字是牌的基準值,真正開局會依縣市大小調整) */
const DEMO: (FaceData & { id: string; cheer: Parameters<HeroCheer>[0]; votes: number })[] = [
{ id: "canvass", name: "掃街拜票", art: "street_canvass", cost: 1, money: null, rarity: "basic", value: "+1,720", text: "該區 +1,720;人口密集 ×1.3", tags: ["ground"], cheer: "crowd", votes: 1720 },
{ id: "rally", name: "造勢晚會", art: "rally", cost: 2, money: 200, rarity: "basic", value: "+3,450", text: "該區 +3,450、隔壁區兩成半,聲勢 +2", tags: ["rally"], cheer: "rally", votes: 3450 },
{ id: "truck", name: "宣傳車遊街", art: "sound_truck", cost: 1, money: 30, rarity: "common", value: "+1,150", text: "該區 +1,150,隔壁每一區也有一半", tags: ["ground"], cheer: "truck", votes: 1150 },
{ id: "rally", name: "造勢晚會", art: "rally", cost: 2, money: 200, rarity: "basic", value: "+3,450", text: "該區 +3,450、擴散到隔壁區合計五成,聲勢 +2", tags: ["rally"], cheer: "rally", votes: 3450 },
{ id: "truck", name: "宣傳車遊街", art: "sound_truck", cost: 1, money: 30, rarity: "common", value: "+1,150", text: "該區 +1,150,擴散到隔壁區合計一樣多", tags: ["ground"], cheer: "truck", votes: 1150 },
{ id: "temple", name: "宮廟參拜", art: "temple_visit", cost: 1, money: null, rarity: "basic", value: "+1,260", text: "該區 +1,260;宮廟多 ×2", tags: ["ground", "temple"], cheer: "crowd", votes: 2520 },
{ id: "tv", name: "電視廣告", art: "tv_ad", cost: 1, money: 300, rarity: "common", value: "+5,180", text: "全市 +5,180,長輩多的區分到較多", tags: ["media"], cheer: "crowd", votes: 5180 },
];

View File

@ -114,8 +114,9 @@
.tmenu-item b { font-size: 18px; }
.tmenu-item.is-primary b { font-size: 22px; }
.tmenu-item.is-primary > svg { width: 42px; height: 42px; }
.home-dock { justify-content: space-between; gap: 4px; }
.home-dock a { width: 52px; }
/* 六個圖示排成一列(不換行) */
.home-dock { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 4px; }
.home-dock a { width: auto; min-width: 0; }
.home-dock-ic { width: 44px; height: 44px; }
.home .hero3d-game { display: none; }
.home-hand { display: none; }
@ -125,6 +126,33 @@
.tmenu-item > svg { width: 36px; height: 36px; padding: 7px; }
.home-logo .hero3d-title { font-size: 56px; }
}
/* 橫放的手機:左邊標題和圖示列,右邊選單(放不下可以捲),不會疊在一起 */
@media (orientation: landscape) and (max-height: 500px) {
.home .hero3d::before { background: linear-gradient(90deg, rgb(17 20 25 / 0.8) 0%, rgb(17 20 25 / 0.35) 45%, rgb(17 20 25 / 0.75) 100%); }
.home .hero3d-stage { bottom: 0; }
.home .home-copy {
width: 100%; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr); grid-template-rows: auto minmax(0, 1fr) auto;
grid-template-areas: "logo menu" ". menu" "dock menu"; gap: 8px 20px;
padding: max(12px, env(safe-area-inset-top, 0px)) max(16px, env(safe-area-inset-right, 0px)) max(10px, env(safe-area-inset-bottom, 0px)) max(16px, env(safe-area-inset-left, 0px));
}
.home-logo { position: static; grid-area: logo; gap: 4px; }
.home-logo .hero3d-kicker { display: none; }
.home-logo .hero3d-title { font-size: 40px; }
.home-logo .hero3d-slogan { font-size: 16px; }
.home .tmenu { grid-area: menu; min-height: 0; overflow-y: auto; overscroll-behavior: contain; pointer-events: auto; align-content: start; padding: 2px 6px 6px 2px; }
.tmenu-list { gap: 8px; }
.tmenu-item { padding: 6px 12px 6px 6px; }
.tmenu-item > svg { width: 36px; height: 36px; padding: 7px; }
.tmenu-item b { font-size: 18px; }
.tmenu-item.is-primary b { font-size: 22px; }
.tmenu-item.is-primary > svg { width: 42px; height: 42px; }
.home-dock { grid-area: dock; display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 4px; }
.home-dock a { width: auto; min-width: 0; }
.home-dock-ic { width: 40px; height: 40px; }
.home .hero3d-music { top: max(12px, env(safe-area-inset-top, 0px)); bottom: auto; right: calc(53.5% + 4px); }
.home .hero3d-game { display: none; }
.home-hand { display: none; }
}
@media (prefers-reduced-motion: reduce) {
.tmenu-item { animation: hero-fade 300ms ease both; }
.home-hand-card { animation: none; transition: opacity 160ms ease-out; }

View File

@ -108,11 +108,11 @@
.isl-step-nav { display: flex; justify-content: space-between; gap: 8px; }
.isl-step-nav .btn { min-height: 48px; border: 2px solid var(--ink); }
.isl-ws-preview { grid-area: preview; position: sticky; top: 12px; display: grid; justify-items: center; gap: 12px; padding: 18px 16px; background: color-mix(in srgb, var(--signal) 22%, var(--surface)); border: 3px solid var(--ink); border-radius: 18px; box-shadow: 5px 5px 0 var(--shadow-ink); }
.isl-ws-preview { grid-area: preview; position: sticky; top: 12px; display: grid; grid-template-columns: minmax(0, 1fr); justify-items: center; gap: 12px; padding: 18px 16px; background: color-mix(in srgb, var(--signal) 22%, var(--surface)); border: 3px solid var(--ink); border-radius: 18px; box-shadow: 5px 5px 0 var(--shadow-ink); }
.isl-preview-card { --rg-card-w: 190px; padding: 6px 0 4px; }
.isl-preview-card .rgc.is-big { --rgc-w: var(--rg-card-w); transform: rotate(-2deg); }
.isl-name { width: 100%; display: grid; gap: 4px; font-weight: 800; }
.isl-name input { min-height: 48px; padding: 6px 12px; border: 3px solid var(--ink); border-radius: 12px; background: var(--surface); color: var(--ink); font: inherit; font-size: 18px; font-weight: 700; }
.isl-name input { width: 100%; min-height: 48px; padding: 6px 12px; border: 3px solid var(--ink); border-radius: 12px; background: var(--surface); color: var(--ink); font: inherit; font-size: 18px; font-weight: 700; }
.isl-name input:focus-visible { outline: 3px solid var(--stamp); outline-offset: 2px; }
.isl-name small { color: var(--muted); font-weight: 700; }
.isl-save { width: 100%; min-height: 56px; font-family: var(--font-serif); font-size: 22px; background: var(--stamp); color: #fff; border: 3px solid var(--ink); box-shadow: 4px 4px 0 var(--shadow-ink); }

View File

@ -368,6 +368,60 @@
}
}
/* 手機橫放:格子在左(跟著高度縮),右邊放看板和工具,「完成」才按得到 */
@container (max-width: 759px) and (orientation: landscape) {
.mg-bb {
grid-template-columns: auto minmax(0, 230px);
grid-template-rows: auto minmax(0, 1fr);
gap: 4px 16px;
justify-content: center;
align-items: center;
padding-block: 4px;
}
.mg-status {
grid-column: 1;
grid-row: 1;
min-height: 0;
padding: 0 10px;
font-size: 13px;
}
.mg-gridwrap {
--gw: min(calc(100cqh - 44px), calc(100cqw - 270px));
grid-column: 1;
grid-row: 2;
width: var(--gw);
}
.mg-side {
grid-column: 2;
grid-row: 1 / span 2;
gap: 8px;
}
.mg-tray {
gap: 6px;
}
.mg-piece {
width: 66px;
height: 66px;
}
.mg-legend {
display: none;
}
.mg-tools {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
width: 100%;
}
.mg-tools .gs-btn {
min-height: 40px;
padding: 4px 8px;
font-size: 14px;
}
.mg-tools .gs-btn:last-child {
grid-column: 1 / -1;
}
}
@keyframes mg-drop {
0% {
transform: scale(1.25);

View File

@ -259,6 +259,16 @@
}
}
/* 橫放的手機:三張卡左右並排(上下排太擠),插圖裁成矮橫幅 */
@media (max-width: 720px) and (orientation: landscape) and (max-height: 500px) {
.mgl-lead { display: none; }
.mgl-cards { grid-template-columns: repeat(3, minmax(0, 1fr)); grid-auto-rows: auto; align-items: stretch; gap: 10px; }
.mgl-art { min-height: 0; height: 64px; }
.mgl-pitch { white-space: normal; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
.mgl-tiers { grid-template-columns: minmax(0, 1fr); gap: 4px; }
.mgl-tier { min-height: 28px; }
.mgl-go { top: 6px; right: 6px; min-height: 36px; font-size: 14px; }
}
@keyframes mgl-in {
from {
opacity: 0;

View File

@ -790,6 +790,22 @@
display: none;
}
}
/* 窄手機:右邊有三個數字時,遊戲名稱還是放得下(看板卡位) */
@media (max-width: 400px) {
.mg-top {
gap: 6px;
}
.mg-plate {
padding-inline: 8px 12px;
}
.mg-plate h2 {
font-size: 17px;
}
.mg-pill {
min-width: 46px;
padding-inline: 6px;
}
}
/* ── 動畫(只動 transform/opacity) ── */
@keyframes mg-fade {

View File

@ -14,6 +14,24 @@
cursor: pointer;
border-top: 3px solid var(--mg-k);
}
/* 手機橫放:舞台、判定圈、群眾都縮小,「凍蒜!」按鈕才在畫面裡 */
@media (orientation: landscape) and (max-height: 500px) {
.mg-rally {
grid-template-rows: minmax(56px, 0.55fr) minmax(96px, 1fr) auto auto;
padding-bottom: max(8px, env(safe-area-inset-bottom, 0px));
}
.mg-rally .mg-target {
--tz: clamp(88px, 30cqh, 150px);
}
.mg-rally .mg-fans {
height: 34px;
margin-bottom: 4px;
}
.mg-rally .mg-shout {
min-height: 46px;
font-size: 24px;
}
}
.mg-backdrop {
position: relative;
grid-row: 1;

View File

@ -474,6 +474,14 @@
.ppl-cred-stamp { width: 54px; height: 54px; font-size: 15px; }
.ppl-year { min-width: 56px; font-size: 18px; }
}
/* 橫放的手機:縣市、年份、搜尋排成一列,檔案櫃才有高度 */
@media (max-width: 720px) and (orientation: landscape) and (max-height: 500px) {
.ppl-index-row { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1.4fr) auto; }
.ppl-labeler { grid-column: auto; grid-row: auto; min-height: 44px; }
.ppl-sticker, .ppl-clear { min-height: 44px; }
.ppl-index { padding: 6px 8px; }
.ppl-tab { padding-block: 4px 8px; }
}
@media (max-width: 400px) {
/* 兩欄的檔案夾很窄:「玩過 N 次・最佳 A」縮小一點,維持一行 */
.ppl-file-played { gap: 3px; padding: 2px 6px; font-size: 11px; }

View File

@ -20,7 +20,7 @@ import { sfx } from "../audio/sfx.ts";
import { GameScene, SceneStat } from "../ui/GameScene.tsx";
import { AdvisorFace, OfferFace, cardKind } from "./cards.tsx";
import { CompletionPanel } from "./Completion.tsx";
import { loadProgress, reputation, type Progress } from "./progress.ts";
import { completion, loadProgress, reputation, type Progress } from "./progress.ts";
import "./collection.css";
/**
@ -182,7 +182,7 @@ interface BookLayout {
function fitBook(w: number, h: number): BookLayout {
const small = w < 440;
const pages = w >= 860 ? 2 : 1;
const m = small ? { gap: 6, pad: 4, cap: 30, pagePad: 2, minW: 84 } : { gap: 14, pad: 8, cap: 36, pagePad: 12, minW: 100 };
const m = small ? { gap: 6, pad: 4, cap: 34, pagePad: 2, minW: 84 } : { gap: 14, pad: 8, cap: 36, pagePad: 12, minW: 100 };
const spine = pages === 2 ? 40 : 0;
const pageW = (w - spine) / pages - m.pagePad * 2;
const pageH = h - m.pagePad * 2;
@ -280,6 +280,8 @@ export function RogueCollection() {
const [anchors, setAnchors] = useState<Record<Tab, number>>({ cards: 0, advisors: 0, events: 0, feats: 0 });
const [motion, setMotion] = useState<"next" | "prev" | "tab">("tab");
const [open, setOpen] = useState<number | null>(null);
/** 手機的完成度視窗(大廳的完成度那一條連到 #/rogue/collection?cmp,手機直接打開) */
const [cmpOpen, setCmpOpen] = useState(() => location.hash.includes("?cmp") && matchMedia("(max-width: 720px), (orientation: landscape) and (max-height: 500px)").matches);
const [spreadEl, setSpreadEl] = useState<HTMLDivElement | null>(null);
const dragRef = useRef<HTMLDivElement>(null);
const focusAfterFlip = useRef(false);
@ -344,6 +346,10 @@ export function RogueCollection() {
if (e.altKey || e.ctrlKey || e.metaKey) return;
const t = e.target as HTMLElement | null;
if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;
if (cmpOpen) {
if (e.key === "Escape") setCmpOpen(false);
return;
}
if (open !== null) {
if (e.key === "Escape") close();
else if (e.key === "ArrowLeft") step(-1);
@ -392,7 +398,14 @@ export function RogueCollection() {
<span className="col-hud-wide">
<SceneStat icon={<Flame size={18} />} value={`${progress.ascension} 級`} label="逆風解鎖" />
</span>
<SceneStat icon={<BookOpen size={18} />} value={total ? `${Math.round(ratio(totalGot, total) * 100)}%` : "—"} label="卡冊收錄" />
<span className="col-hud-wide">
<SceneStat icon={<BookOpen size={18} />} value={total ? `${Math.round(ratio(totalGot, total) * 100)}%` : "—"} label="卡冊收錄" />
</span>
{catalog && (
<button type="button" className="col-cmp-btn" onClick={() => setCmpOpen(true)} aria-haspopup="dialog">
<SceneStat icon={<Trophy size={18} />} value={`${Math.round(completion(progress, catalog).percent * 100)}%`} label="完成度" />
</button>
)}
</>
);
@ -442,6 +455,7 @@ export function RogueCollection() {
</div>
{catalog && <CompletionPanel progress={progress} catalog={catalog} />}
{cmpOpen && catalog && <CompletionModal progress={progress} catalog={catalog} onClose={() => setCmpOpen(false)} />}
<section className="col-book" aria-label="選戰卡冊">
<div className="col-sheet" role="tabpanel" id="col-panel" aria-labelledby={`col-tab-${tab}`}>
<header className="col-head">
@ -667,3 +681,25 @@ function Detail({ entry, index, total, note, onClose, onStep }: { entry: Entry;
document.body,
);
}
/** 手機的完成度:卡冊頁不捲動、放不下,收成右上角的按鈕,點開是可以捲的視窗 */
function CompletionModal({ progress, catalog, onClose }: { progress: Progress; catalog: RogueCatalog; onClose: () => void }) {
const closeRef = useRef<HTMLButtonElement>(null);
useEffect(() => closeRef.current?.focus({ preventScroll: true }), []);
return createPortal(
<div
className="col-modal-back"
onClick={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
<div className="col-cmp-modal" role="dialog" aria-modal="true" aria-label="完成度">
<button ref={closeRef} type="button" className="col-btn col-modal-x" onClick={onClose} aria-label="關閉">
<X size={22} aria-hidden />
</button>
<CompletionPanel progress={progress} catalog={catalog} />
</div>
</div>,
document.body,
);
}

Some files were not shown because too many files have changed in this diff Show More