import type { MiniGameKind, RogueArea, RogueLog, RogueView } from "@election2026/protocol"; import { AlertTriangle, Flag, House, List, Map as MapIcon, PanelRightClose, PanelRightOpen, Swords, ThumbsUp } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { Topology } from "topojson-specification"; import { api, rogueApi } from "../api.ts"; import { actionIcon } from "../art/actionIcons.ts"; import { CandidateBadge } from "../art/Badge.tsx"; import { setMusic } from "../audio/music.ts"; import { sfx } from "../audio/sfx.ts"; import { BoardStage } from "../board3d/BoardStage.tsx"; import { SettingsMenu } from "../hud/SettingsMenu.tsx"; import { Loader } from "../ui/Loader.tsx"; import { buildGeometry, type StageGeometry } from "../stage/geometry.ts"; import { loadContext } from "../stage/loadMap.ts"; import { MapStage, type FloatText, type StageMarker } from "../stage/MapStage.tsx"; import { NewsTicker, WeekBrief } from "./brief.tsx"; import { CoachBubble, useCoach } from "./coach.tsx"; import { Finale } from "./finale.tsx"; import { RouteOverlay, SceneOverlay } from "./flow.tsx"; import { ScorePop, flyCard, useShake, type Score } from "./juice.tsx"; import { INTENT_ICONS, overall, raceLabel, signed, weekLabel } from "./labels.ts"; import { DeckDrawer, HelpModal } from "./overlays.tsx"; import { AdvisorRow, BattleStrip, EVENT_UID, Hand, IntentList, RogueHud, TownList } from "./parts.tsx"; import { UltimateButton, UltimateOverlay } from "./Ultimate.tsx"; import { WeekEnd } from "./weekend.tsx"; import { LAST_RUN_KEY, markSeen } from "./progress.ts"; import "./rogue.css"; const HELPED_KEY = "tongsuan.rogue.helped"; const WIDE_KEY = "tongsuan.rogue.wide"; const storage = { get(key: string): string | null { try { return localStorage.getItem(key); } catch { return null; } }, set(key: string, value: string): void { try { localStorage.setItem(key, value); } catch { // 私密模式存不了,只是少了「繼續上一局」 } }, }; const SCENE_TITLE: Record = { press: "記者堵麥", crisis: "匿名黑函", poll: "民調公布", debate: "電視辯論" }; /** * 選戰卡牌(新玩法,docs/21–23):地圖+各區支持度+對手意圖+手牌。 * 一週只剩三步(docs/23 流程整合):看對手 → 出牌 → 拿獎勵。 * - 快報在地圖上方跑馬燈(第一週開場才自動播電視);記者堵麥是手牌裡的事件牌;民調自動公布。 * - 辯論、黑函(週次每局不同,docs/25)是大場面,全畫面;選完的結果用提示和地圖跳字顯示,不另外跳視窗。 * - 結束這週:結算在地圖上播,旁邊同一個面板選下一站(門上直接攤開內容)。 * 規則都在伺服器;每個動作拿回新的狀態,畫面只負責演出。 */ export function RogueScreen({ runId }: { runId: string }) { const [view, setView] = useState(null); const [geometry, setGeometry] = useState(null); const [loadError, setLoadError] = useState(null); const [error, setError] = useState(null); const [selected, setSelected] = useState(null); const [busy, setBusy] = useState(false); /** 存檔離開:每一步都已經存在伺服器,等送出中的請求回來再回主選單(之後按「繼續選戰」接著打) */ const [leaving, setLeaving] = useState(false); const [floats, setFloats] = useState([]); const [effects, setEffects] = useState<{ key: string; townCode: string; actionId: string }[]>([]); /** 這週結算的紀錄(週末面板用);開始下一週就清掉 */ const [weekLog, setWeekLog] = useState(null); const [lastResolution, setLastResolution] = useState(null); const [brief, setBrief] = useState(false); const [score, setScore] = useState(null); const [toast, setToast] = useState(null); /** 大絕招面板 */ const [ultOpen, setUltOpen] = useState(false); const [help, setHelp] = useState(false); const [deck, setDeck] = useState(false); const [focus, setFocus] = useState(null); const [lastTown, setLastTown] = useState(null); const [mobileTab, setMobileTab] = useState<"map" | "list">("map"); // 電腦版:右邊的「各區列表」可以收起來,地圖變全寬;對手這週要做的事改浮在地圖右上角(記在這台瀏覽器) const [wide, setWide] = useState(() => storage.get(WIDE_KEY) === "1"); const toggleWide = () => { sfx.click(); setWide((w) => { storage.set(WIDE_KEY, w ? "0" : "1"); return !w; }); }; const [shakeClass, shake] = useShake(); const mapRef = useRef(null); const coach = useCoach(view, selected); useEffect(() => { let alive = true; rogueApi .get(runId) .then(async (v) => { if (!alive) return; setView(v); storage.set(LAST_RUN_KEY, runId); // 第一週還沒出牌:先看開場電視;第一次玩新玩法、又不是教學關卡時打開說明 if (v.week === 1 && v.phase === "plan" && v.towns.every((t) => t.played.length === 0)) setBrief(true); if (!storage.get(HELPED_KEY) && !v.options.tutorial) { setHelp(true); storage.set(HELPED_KEY, "1"); } if (!v.packId) return; // 立委選區只畫選區內的村里,地圖放大到選區;選區外的區淡淡地畫在旁邊 const [topology, context, area] = await Promise.all([api.topology(v.packId), loadContext(), rogueApi.area(runId).catch((): RogueArea => ({ villages: null, groups: null }))]); if (!alive) return; // 總統選舉以縣市為單位 const level = v.countyCode === "00000" ? "county" : "town"; setGeometry( buildGeometry(topology as Topology, context, { county: v.countyCode, level, villages: area.villages ? new Set(area.villages) : null, groups: area.groups ? new Map(Object.entries(area.groups)) : null, names: new Map(v.towns.map((t) => [t.code, t.name])), }), ); }) .catch((e: unknown) => alive && setLoadError(e instanceof Error ? e.message : String(e))); setMusic("planning-loop"); return () => { alive = false; }; }, [runId]); useEffect(() => { if (view) markSeen(view); }, [view]); useEffect(() => { if (leaving && !busy) location.hash = "#/"; }, [leaving, busy]); // 換週的轉場:新的一週開始時,「第 N 週」橫幅從地圖上掃過去(不擋操作) const [banner, setBanner] = useState<{ week: number; title: string } | null>(null); const shownWeek = useRef(null); useEffect(() => { if (!view || view.phase === "finished") return; if (shownWeek.current === view.week) return; const first = shownWeek.current === null; shownWeek.current = view.week; // 第一次進來(含重新整理)有開場電視,不另外掃橫幅 if (first) return; setBanner({ week: view.week, title: view.event.title }); sfx.flip(); const t = setTimeout(() => setBanner(null), 1600); return () => clearTimeout(t); }, [view?.week, view?.phase]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (!toast) return; // 字多的提示留久一點 const t = setTimeout(() => setToast(null), Math.min(7000, 2400 + toast.length * 45)); return () => clearTimeout(t); }, [toast]); const showFloats = useCallback((items: FloatText[]) => { setFloats(items); setTimeout(() => setFloats((now) => (now === items ? [] : now)), 1800); }, []); /** 大幅拉票的門檻:約全市投票人數的 0.4% */ const bigSwing = useMemo(() => (view ? overall(view.towns).voters * 0.004 : Infinity), [view?.runId]); // eslint-disable-line react-hooks/exhaustive-deps const onResolveStep = useCallback( (entry: RogueLog, i: number) => { if (entry.town && entry.votes !== 0) showFloats([{ key: `r-${i}-${entry.town}`, townCode: entry.town, text: signed(entry.votes), tone: entry.votes > 0 ? "good" : "bad" }]); if (entry.text.includes("翻")) shake("large"); else if (entry.side === "rival" && Math.abs(entry.votes) >= bigSwing) shake("small"); }, [showFloats, shake, bigSwing], ); const closeBrief = useCallback(() => setBrief(false), []); const closeScore = useCallback(() => setScore(null), []); const townAdults = useMemo(() => (view ? new Map(view.towns.map((t) => [t.code, t.voters])) : null), [view?.runId]); // eslint-disable-line react-hooks/exhaustive-deps if (loadError) { return (

{loadError}

重新開一局
); } if (!view) return
; const card = view.hand.find((c) => c.uid === selected) ?? null; const list = card ? (view.previews[card.uid] ?? []) : []; const previews = new Map(list.map((p) => [p.target, p])); const best = new Set(card?.target === "town" ? [...list].sort((a, b) => b.votes - a.votes).slice(0, 3).map((p) => p.target) : []); const cityPreview = card && (card.target === "city" || card.target === "none") ? (previews.get("city") ?? null) : null; const targeting = card?.target === "intent" ? "intent" : card?.target === "attack" ? "attack" : null; /** 請求失敗後重新拿一次這局的狀態(伺服器可能已經做完了,只是回應沒收到) */ const recover = (e: unknown) => { setError(e instanceof Error ? e.message : String(e)); rogueApi .get(runId) .then(setView) .catch(() => undefined); }; const play = async (target: string | null) => { if (!card || busy) return; setBusy(true); setError(null); const preview = previews.get(target ?? "city"); const el = document.querySelector(`.rg-hand-card[data-uid="${card.uid}"]`); // 出牌不等伺服器(docs/25 第 7 節):牌先飛出去、手牌和體力先扣,伺服器回來再用它的結算校正(出錯時 recover 重新讀) flyCard(el, mapRef.current); if (card.tags.includes("rally")) sfx.cheer(); else if (card.tags.includes("money")) sfx.coin(); else if (card.tags.includes("attack")) sfx.alert(); else sfx.place(); setView((v) => (v ? { ...v, hand: v.hand.filter((c) => c.uid !== card.uid), energy: Math.max(0, v.energy - card.cost), money: Math.max(0, v.money - card.money) } : v)); setSelected(null); try { const next = await rogueApi.play(runId, card.uid, target); const votes = next.log.reduce((a, e) => a + e.votes, 0); const flipped = next.log.some((e) => e.text.startsWith("翻轉")); // 加成說明用伺服器實際結算的(機率牌會寫爆紅或失言),舊版伺服器沒有就用預估的 const notes = next.notes.length ? next.notes : (preview?.note ?? "").split("・").filter(Boolean); // 打對台、澄清、事實查核:對手的行動被削弱的部分(週末才會少拉,先在這裡讓你看到) const blocked = next.intents.filter((i) => i.kind !== "stake").reduce((a, i) => a + i.amount * Math.max(0, (view.intents.find((x) => x.id === i.id)?.cut ?? i.cut) - i.cut), 0); if (votes !== 0 || notes.length || blocked > 0) setScore({ key: `${card.uid}`, title: card.name, notes, votes, blocked }); if (flipped) { sfx.flag(); shake("large"); } else if (Math.abs(votes) >= bigSwing * 1.5) shake("small"); showFloats(next.log.filter((e) => e.town && e.votes !== 0).map((e, i) => ({ key: `${card.uid}-${i}`, townCode: e.town!, text: signed(e.votes), tone: e.votes >= 0 ? "good" : "bad" }))); const city = next.log.filter((e) => !e.town || e.text.startsWith("翻轉")); if (city.length) setToast(city.map((e) => `${e.text}${e.votes ? ` ${signed(e.votes)} 票` : ""}`).join(";")); const town = card.target === "town" ? target : card.target === "intent" ? (view.intents.find((i) => i.id === target)?.town ?? null) : null; if (town) { setEffects([{ key: card.uid, townCode: town, actionId: card.art }]); setLastTown(town); } setView(next); } catch (e) { recover(e); } finally { setBusy(false); } }; /** 大絕招:小遊戲玩完把分數送出,地圖跳字、提示、震動 */ /** 加開行程(docs/26):花資金換 1 點體力 */ const doRush = async () => { if (busy || !view.rush || view.rush.blocked) return; setBusy(true); setError(null); try { const next = await rogueApi.rush(runId); sfx.coin(); setToast(`加開行程:花 ${view.rush.price} 萬,體力 +1`); setView(next); } catch (e) { recover(e); } finally { setBusy(false); } }; const fireUltimate = async (kind: MiniGameKind, score: number, towns?: string[]) => { if (busy) return; setBusy(true); setError(null); try { const next = await rogueApi.ultimate(runId, kind, score, towns); setUltOpen(false); sfx.applause(); shake("large"); const votes = next.log.reduce((a, e) => a + e.votes, 0); const title = view.ultimate?.options.find((o) => o.kind === kind)?.name ?? "大絕招"; setScore({ key: `ult-${next.week}-${kind}-${score}`, title: `大絕招・${title}`, notes: [`小遊戲 ${Math.round(score)} 分`, `落後倍率 ×${(view.ultimate?.mult ?? 1).toFixed(1)}`], votes, blocked: 0 }); showFloats(next.log.filter((e) => e.town && e.votes !== 0).map((e, i) => ({ key: `ult-${i}-${e.town}`, townCode: e.town!, text: signed(e.votes), tone: "good" }))); setToast(next.log.map((e) => `${e.text}${e.votes ? ` ${signed(e.votes)} 票` : ""}`).join(";")); setView(next); } catch (e) { setUltOpen(false); recover(e); } finally { setBusy(false); } }; const endWeek = async () => { if (busy) return; setBusy(true); setError(null); try { sfx.stamp(); const next = await rogueApi.endWeek(runId); setSelected(null); setView(next); setWeekLog(next.log); setLastResolution(next.log); } catch (e) { recover(e); } finally { setBusy(false); } }; /** 選完的結果:地圖上跳字+一條提示(不另外跳視窗) */ const announce = (title: string | null, log: readonly RogueLog[]) => { const lines = log.filter((e) => e.text); if (!lines.length) return; showFloats(log.filter((e) => e.town && e.votes !== 0).map((e, i) => ({ key: `a-${i}-${e.town}`, townCode: e.town!, text: signed(e.votes), tone: e.votes >= 0 ? "good" : "bad" }))); setToast(`${title ? `${title}:` : ""}${lines.map((e) => `${e.text}${e.votes ? ` ${signed(e.votes)} 票` : ""}`).join(";")}`); }; const choose = async (pick: number | "skip", target: string | null = null, option?: number) => { if (busy) return; setBusy(true); setError(null); const before = view; try { const next = await rogueApi.choose(runId, pick, target, option); setView(next); const sceneKind = before.scene && (before.phase === "scene" || before.phase === "plan") ? before.scene.kind : null; // 堵麥、黑函、地方抉擇、拿到牌或幕僚:結果用提示和跳字(辯論、深入基層在自己的畫面裡顯示) if (sceneKind === "press" || sceneKind === "crisis") announce(SCENE_TITLE[sceneKind]!, next.log); else if (before.phase === "route" || (before.phase === "stop" && before.stop?.kind === "event")) announce(null, next.log); if (pick !== "skip" && (before.phase === "route" || (before.phase === "stop" && (before.stop?.kind === "card" || before.stop?.kind === "advisor" || before.stop?.kind === "upgrade")))) sfx.good(); if (sceneKind === "crisis" && next.log.some((e) => e.votes < 0)) shake("small"); if (sceneKind === "press") setSelected(null); if (next.week > before.week) { setWeekLog(null); setFocus(null); // 民調公布那週:提示一下(不用點) if (next.poll?.week === next.week) setToast(`民調公布:${next.you.name} ${(next.poll.you * 100).toFixed(1)}%、${next.rival.name} ${(next.poll.rival * 100).toFixed(1)}%${next.poll.lead ? ",領先:聲勢 +1" : ",落後:手上多一張「悲情催票」"}`); } } catch (e) { recover(e); } finally { setBusy(false); } }; const again = async (ascension?: number) => { setBusy(true); try { const { runId: next } = view.options.tutorial ? await rogueApi.tutorial() : await rogueApi.create(view.scenarioId, view.you.id, { ascension: ascension ?? view.options.ascension, even: view.options.even }); location.hash = `#/rogue/${next}`; } catch (e) { setError(e instanceof Error ? e.message : String(e)); setBusy(false); } }; const onMapSelect = (code: string) => { if (card?.target === "town") { void play(code); return; } setFocus(code); document.getElementById(`rg-town-${code}`)?.scrollIntoView({ block: "nearest", behavior: "smooth" }); }; const fills = new Map( view.towns.map((t) => { const lead = t.you - t.rival; const color = lead >= 0 ? view.colors.you : view.colors.rival; const strength = Math.round(18 + Math.min(1, Math.abs(lead) / (t.voters * 0.12 || 1)) * 62); return [t.code, `color-mix(in srgb, ${color} ${strength}%, var(--map-base, #e8e4da))`]; }), ); const markers: StageMarker[] = [ ...(view.battle && view.phase === "plan" ? [{ key: "battle", townCode: view.battle.town, icon: Swords, color: "var(--stamp)", label: `本週戰場:${view.battle.name}` }] : []), ...view.towns.filter((t) => t.home).map((t) => ({ key: `home-${t.code}`, townCode: t.code, icon: House, color: t.home === "you" ? view.colors.you : view.colors.rival, label: `${t.home === "you" ? "你" : view.rival.name}的本命區:${t.name}` })), ...view.towns.filter((t) => t.flag).map((t) => ({ key: `flag-${t.code}`, townCode: t.code, icon: Flag, color: t.flag === "you" ? view.colors.you : view.colors.rival, label: `${t.flag === "you" ? "你" : view.rival.name}插旗:${t.name}` })), ...view.intents .filter((i) => i.town) .map((i) => ({ key: `intent-${i.id}`, townCode: i.town!, icon: INTENT_ICONS[i.kind], color: view.colors.rival, label: `${view.rival.name}:${i.label}` })), ...(view.nextBig ? [{ key: "next-big", townCode: view.nextBig.town, icon: AlertTriangle, color: "var(--stamp)", label: `預告:${view.nextBig.label}` }] : []), ...view.towns.flatMap((t) => t.played.map((p) => ({ key: `played-${t.code}-${p.id}`, townCode: t.code, icon: actionIcon(p.art), color: view.colors.you, label: `你:${p.name}` }))), ]; const offices = new Set(view.towns.filter((t) => t.office).map((t) => t.code)); const rivalTown = view.intents.find((i) => i.big)?.town ?? view.intents.find((i) => i.kind === "rally" && i.town)?.town ?? view.intents.find((i) => i.town)?.town ?? null; const tokens = [ ...(lastTown ? [{ key: "me", townCode: lastTown, node: , label: view.you.name, color: view.colors.you }] : []), ...(rivalTown ? [{ key: "rival", townCode: rivalTown, node: , label: view.rival.name, color: view.colors.rival }] : []), ]; // 開票夜的地圖:還沒開票的區是灰的;開了的區塗上目前領先的顏色,開得越多、差距越大越深;剛開完的那一區框起來、冒出差距 const voteMap = geometry && view.result ? (counts: ReadonlyMap, latest: string | null) => { const final = new Map(view.result!.byTown.map((t) => [t.code, t])); const fillsNow = new Map( view.towns.map((t) => { const c = counts.get(t.code); if (!c || c.f <= 0) return [t.code, "#8a919c"]; const total = c.you + c.rival + c.others || 1; const margin = (c.you - c.rival) / total; const color = margin >= 0 ? view.colors.you : view.colors.rival; const strength = (0.35 + 0.65 * c.f) * (45 + Math.min(1, Math.abs(margin) / 0.15) * 55); return [t.code, `color-mix(in srgb, ${color} ${Math.round(strength)}%, ${c.f >= 1 ? "#ffffff" : "#8a919c"})`]; }), ); const r = latest ? final.get(latest) : undefined; const floatsNow: FloatText[] = r && latest ? [{ key: `vote-${latest}`, townCode: latest, text: signed(r.you - r.rival), tone: r.you >= r.rival ? "good" : "bad" }] : []; return ; } : undefined; // 疊在上面的畫面一次只開一個,照這個順序(週末面板不擋地圖,結算的跳字看得到) const finale = view.phase === "finished" && view.result && !weekLog; const exitButton = ( ); const overlay = finale ? "finale" : brief ? "brief" : view.phase === "scene" ? "scene" : view.phase === "route" || (view.phase === "finished" && weekLog) ? "weekend" : view.phase === "stop" ? "stop" : null; // 記者堵麥:這週要回答的事件牌 const press = view.phase === "plan" && view.scene?.kind === "press" ? view.scene : null; const answering = !!press && selected === EVENT_UID; return (
setDeck(true)} onHelp={() => setHelp(true)} onRush={() => void doRush()} />
{geometry ? ( ) : view.packId ? ( ) : ( )} {view.phase !== "finished" && setBrief(true)} />} {banner && (
{banner.week >= view.totalWeeks ? "最後一週" : `第 ${banner.week} 週`} {banner.title}
)} {score && } {toast && (

{toast}

)} {wide && (
void play(id)} />
)}
{view.phase !== "finished" && exitButton}
{error ? (

{error}

) : answering && press ? (

記者問: {press.question}

{press.choices.map((c, i) => ( ))}
) : !card ? (

{press ? ( <> 記者堵麥:點最左邊的事件牌回答(這週內回答就好)。 ) : ( <> 挑一張牌{view.week <= 2 && ( <> 。同一區打不同的牌是組合拳;對手要在某區行動時可以打對台或先佈樁擋下來 )} 。 )}

) : card.blocked ? (

{card.name}:{card.blocked}

) : card.target === "town" ? (

{card.name}:點一區打出, 是最划算的三區。

) : card.target === "intent" ? (

{card.name}:點對手在某一區的行動來打對台。

) : card.target === "attack" ? (

{card.name}:點對手的「批評你的政見」讓它失效。

) : (

{card.name}: {cityPreview && cityPreview.votes !== 0 ? `預估 ${signed(cityPreview.votes)} 票${cityPreview.note ? `(${cityPreview.note})` : ""}` : (cityPreview?.note ?? card.text)} 再點一次這張牌也會打出

)}
{ // 全市的牌:再點一次就打出(不用再按「打出這張牌」) if (uid === null && card && !card.blocked && (card.target === "city" || card.target === "none")) { void play(null); return; } if (uid) sfx.flip(); setSelected(uid); setError(null); const next = view.hand.find((c) => c.uid === uid); // 要選區的牌在手機上切到地圖;打對台、事實查核切到列表 if (next?.target === "town") setMobileTab("map"); else if (next?.target === "intent" || next?.target === "attack") setMobileTab("list"); // 各區重新依預估排序,捲回最上面看最划算的區 document.querySelector(".rg-side")?.scrollTo({ top: 0, behavior: "smooth" }); }} />
{view.ultimate && view.phase === "plan" && setUltOpen(true)} />}
{coach.step && !overlay && } {overlay === "finale" && void again(asc)} onHome={() => (location.hash = "#/")} />} {/* 第一次玩會先開說明:看完再播開場電視,兩個視窗不疊在一起 */} {overlay === "brief" && !help && } {(overlay === "scene" || overlay === "stop" || (overlay === "weekend" && view.phase === "route")) &&
{exitButton}
} {overlay === "scene" && void choose(p)} />} {overlay === "weekend" && void choose(p, null, option)} onFinale={() => setWeekLog(null)} />} {overlay === "stop" && void choose(p, t ?? null)} />} {coach.step && (overlay === "weekend" || overlay === "stop") && } {ultOpen && view.ultimate && view.phase === "plan" && void fireUltimate(k, score, towns)} onClose={() => setUltOpen(false)} />} {help && setHelp(false)} />} {deck && setDeck(false)} />}
); } /** 新手教學沒有真實地圖:三個里畫成三塊並排的地 */ function TutorialMap({ view, best, onSelect }: { view: RogueView; best: ReadonlySet; onSelect?: (code: string) => void }) { return (
{view.towns.map((t) => { const lead = t.you - t.rival; const color = lead >= 0 ? view.colors.you : view.colors.rival; const strength = Math.round(18 + Math.min(1, Math.abs(lead) / (t.voters * 0.12 || 1)) * 62); const intents = view.intents.filter((i) => i.town === t.code); return ( ); })}
); }