import type { RogueResult, RogueView } from "@election2026/protocol"; import { ArrowRight, Coins, Flame, Home, Landmark, RotateCcw, Share2, SkipForward, Swords, Trophy } from "lucide-react"; import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { rogueApi } from "../api.ts"; import { CandidateBadge } from "../art/Badge.tsx"; import { BallotStamp } from "../art/BallotStamp.tsx"; import { setMusic } from "../audio/music.ts"; import { sfx } from "../audio/sfx.ts"; import { num, pct, raceLabel, signed } from "./labels.ts"; import { pointsForRun } from "../island/data.ts"; import { addPoints } from "../island/store.ts"; import { coinsForRun, earnCoins } from "../shop/wardrobe.ts"; import { recordRun, todayKey, type RunRecord } from "./progress.ts"; import "./rogue-finale.css"; /** * 選戰卡牌的最後一幕(docs/22):開票夜一區一區開出來,然後是結果、成就、分享圖卡。 * view.phase === "finished" 時由 RogueScreen 蓋在地圖上面。 */ export const GRADE_TEXT: Record = { S: "壓倒性勝利", A: "穩穩當選", B: "險勝凍蒜", C: "飲恨落選", D: "大敗" }; type TownResult = RogueResult["byTown"][number]; const townTotal = (t: Pick) => t.you + t.rival + t.others; /** 同一局只記一次(重新整理、React 開發模式重跑都不會重複算) */ const records = new Map(); function recordOnce(view: RogueView): RunRecord { const hit = records.get(view.runId); if (hit) return hit; const r = recordRun(view); records.set(view.runId, r); return r; } /** 選完拿政績點(政策島蓋建築用);同一局只算一次,教學不算 */ function islandOnce(view: RogueView, record: RunRecord): { points: number; reason: string } | null { if (!view.result || view.options.tutorial) return null; const earned = pointsForRun({ won: view.result.won, grade: view.result.grade, newFeats: record.newFeats.length }); return addPoints(earned.points, earned.reason, view.runId) ? earned : null; } /** 選完發小鎮幣(服裝店買外觀用,docs/24);同一局只發一次,教學不發 */ function coinsOnce(view: RogueView, record: RunRecord): { coins: number; reason: string } | null { if (!view.result || view.options.tutorial) return null; const earned = coinsForRun({ won: view.result.won, grade: view.result.grade, newFeats: record.newFeats.length, daily: Boolean(view.options.daily), career: Boolean(view.options.career) }); return earnCoins(earned.coins, earned.reason, view.runId) ? earned : null; } let featNames: Promise> | null = null; function loadFeatNames() { featNames ??= rogueApi .catalog() .then((c) => new Map(c.feats.map((f) => [f.id, { name: f.name, text: f.text }]))) .catch(() => { featNames = null; return new Map(); }); return featNames; } function useReducedMotion(): boolean { const [reduce, setReduce] = useState(() => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches); useEffect(() => { if (typeof matchMedia !== "function") return; const m = matchMedia("(prefers-reduced-motion: reduce)"); const on = () => setReduce(m.matches); m.addEventListener("change", on); return () => m.removeEventListener("change", on); }, []); return reduce; } /** 數字從目前的值跳到 target(ease-out);減少動態時直接顯示 */ function useCountUp(target: number, reduce: boolean, ms = 520): number { const [value, setValue] = useState(target); const from = useRef(target); useEffect(() => { if (reduce) { from.current = target; setValue(target); return; } const start = performance.now(); const begin = from.current; let frame = 0; const tick = (now: number) => { const t = Math.min(1, (now - start) / ms); const eased = 1 - (1 - t) ** 3; const v = begin + (target - begin) * eased; from.current = v; setValue(v); if (t < 1) frame = requestAnimationFrame(tick); }; frame = requestAnimationFrame(tick); return () => cancelAnimationFrame(frame); }, [target, reduce, ms]); return value; } /** * 開票的節奏:像電視開票,各區同時一點一點開,不是一次開完一區。 * 每一區有自己的開始、開完時間(小區通常先開完);早開出來的票會稍微偏向某一邊,越開越接近最後結果。 * 一共 TICKS 格,最後幾格放慢;全部用這一局的 runId 當種子,重看一次節奏一樣。 */ const TICKS = 30; const tickDelay = (t: number): number => (t === 0 ? 900 : t >= TICKS - 2 ? 1100 : t >= TICKS - 5 ? 700 : 380); interface TownCount { you: number; rival: number; others: number; /** 這一區開了幾成(0–1) */ f: number; } function seeded(text: string): () => number { let a = 2166136261; for (let i = 0; i < text.length; i++) a = Math.imul(a ^ text.charCodeAt(i), 16777619); return () => { a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), a | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } /** 每一區的開票曲線:開始、開完(0–1 的時間),早開票的偏向 */ function countPlan(runId: string, byTown: readonly TownResult[]) { const rand = seeded(runId); const biggest = Math.max(1, ...byTown.map(townTotal)); const plans = byTown.map((t) => { const size = townTotal(t) / biggest; const start = rand() * 0.25; // 大區開得久;最慢的那一區剛好在最後一格開完 const end = Math.min(1, 0.45 + 0.35 * size + rand() * 0.2); return { code: t.code, start, end, swing: (rand() - 0.5) * 0.08 }; }); const last = plans.reduce((a, p) => (p.end > a.end ? p : a), plans[0]!); if (last) last.end = 1; return plans; } const smooth = (x: number) => x * x * (3 - 2 * x); /** 第 tick 格時各區開出來的票 */ function countsAt(tick: number, plans: ReturnType, byTown: readonly TownResult[]): Map { const time = tick / TICKS; return new Map( byTown.map((t, i) => { const p = plans[i]!; const f = time >= p.end ? 1 : time <= p.start ? 0 : smooth((time - p.start) / (p.end - p.start)); const total = townTotal(t) || 1; if (f >= 1) return [t.code, { you: t.you, rival: t.rival, others: t.others, f: 1 }]; // 早開出來的票偏向某一邊,越開越接近最後結果 const lean = p.swing * (1 - f); const youShare = Math.min(1, Math.max(0, t.you / total + lean)); const rivalShare = Math.min(1 - youShare, Math.max(0, t.rival / total - lean)); const counted = total * f; return [t.code, { you: counted * youShare, rival: counted * rivalShare, others: Math.max(0, counted * (1 - youShare - rivalShare)), f }]; }), ); } /** 開票夜的地圖:各區開了幾成、目前誰領先;latest 是剛開完的那一區 */ export type VoteMap = (counts: ReadonlyMap, latest: string | null) => ReactNode; export function Finale({ view, onAgain, onHome, map }: { view: RogueView; onAgain: (ascension?: number) => void; onHome: () => void; map?: VoteMap }) { const [stage, setStage] = useState<"count" | "result">("count"); const [record] = useState(() => recordOnce(view)); const [island] = useState(() => islandOnce(view, record)); const [coins] = useState(() => coinsOnce(view, record)); if (!view.result) return null; return stage === "count" ? setStage("result")} /> : ; } /** 開票夜:各區一點一點開,地圖跟著上色,兩邊的票數往上跳 */ function VoteNight({ view, onDone, map }: { view: RogueView; onDone: () => void; map?: VoteMap }) { const r = view.result!; const reduce = useReducedMotion(); const names = useMemo(() => new Map(view.towns.map((t) => [t.code, t.name])), [view.towns]); const plans = useMemo(() => countPlan(view.runId, r.byTown), [view.runId, r.byTown]); const [tick, setTick] = useState(0); const [flash, setFlash] = useState(0); const [final, setFinal] = useState(false); const started = useRef(false); const leader = useRef<"you" | "rival" | null>(null); const doneBefore = useRef(new Set()); useEffect(() => { if (started.current) return; started.current = true; setMusic("election-night-tension"); sfx.drumroll(); }, []); useEffect(() => { if (tick >= TICKS) return; const t = setTimeout(() => setTick((x) => x + 1), tickDelay(tick)); return () => clearTimeout(t); }, [tick]); const counts = useMemo(() => countsAt(tick, plans, r.byTown), [tick, plans, r.byTown]); const counted = useMemo(() => [...counts.values()].reduce((a, t) => ({ you: a.you + t.you, rival: a.rival + t.rival, others: a.others + t.others }), { you: 0, rival: 0, others: 0 }), [counts]); const totalBallots = useMemo(() => r.byTown.reduce((a, t) => a + townTotal(t), 0) || 1, [r.byTown]); const finished = [...counts.values()].filter((c) => c.f >= 1).length; const progress = (counted.you + counted.rival + counted.others) / totalBallots; // 這一格剛開完的區(地圖上冒出差距) const latest = useMemo(() => { const fresh = r.byTown.filter((t) => counts.get(t.code)!.f >= 1 && !doneBefore.current.has(t.code)).map((t) => t.code); for (const c of fresh) doneBefore.current.add(c); return fresh.at(-1) ?? null; }, [counts, r.byTown]); // 換人領先:閃一下、警示音(開票三成以後才算,剛開始票數少、來回換很正常);每格翻一下選票的聲音 useEffect(() => { if (tick === 0) return; const now = counted.you > counted.rival ? "you" : counted.rival > counted.you ? "rival" : null; if (tick < TICKS) { if (latest) sfx.stamp(); else if (tick % 3 === 0) sfx.paper(); if (progress >= 0.3 && leader.current && now && now !== leader.current) { sfx.alert(); setFlash((f) => f + 1); } } if (now) leader.current = now; }, [tick]); // eslint-disable-line react-hooks/exhaustive-deps // 全部開完:蓋章、鞭炮(落選是一聲嘆息) useEffect(() => { if (tick < TICKS) return; const t = setTimeout(() => { setFinal(true); if (r.won) { sfx.stamp(); sfx.firecracker(); sfx.applause(); setMusic("party-disco-loop"); } else sfx.ooh(); }, 600); return () => clearTimeout(t); }, [tick, r.won]); const ms = Math.min(600, tickDelay(tick)); const you = useCountUp(counted.you, reduce, ms); const rival = useCountUp(counted.rival, reduce, ms); const others = useCountUp(counted.others, reduce, ms); // 百分比跟著畫面上的票數算,票數還是 0 的時候不會先跑出百分比 const cast = you + rival + others; const share = (x: number) => (cast > 0 ? x / cast : 0); const lead = you - rival; const rows = useMemo(() => [...r.byTown].sort((a, b) => townTotal(b) - townTotal(a)), [r.byTown]); const mapNode = map?.(counts, latest); return (
{flash > 0 && } {mapNode && (
{mapNode}
)}
LIVE

開票夜・{raceLabel(view)}

開票 {Math.round(progress * 100)}% 開完 {finished} / {rows.length} 區
0 && cast > 0} won={final && r.won} /> VS 0} won={final && !r.won && r.rival > r.others} />
    {rows.map((t) => { const c = counts.get(t.code)!; const total = c.you + c.rival + c.others; return (
  1. = 1 ? "is-done" : c.f > 0 ? "is-counting" : "is-waiting"}${t.code === latest && !final ? " is-new" : ""}`}> {names.get(t.code) ?? t.code} {total > 0 && ( <> )} {c.f >= 1 ? "開完" : `${Math.round(c.f * 100)}%`} = c.rival ? "is-up" : "is-down"}>{total > 0 ? signed(c.you - c.rival) : "—"}
  2. ); })}
{final ? (
{r.won ? `${view.you.name}凍蒜!` : `${view.you.name}落選`}
) : ( )}
); } function Side({ name, candidate, color, votes, share, leading, won }: { name: string; candidate: RogueView["you"]; color: string; votes: number; share: number; leading: boolean; won: boolean }) { return (
{name} {num(votes)} {pct(share)} {leading && 領先}
); } /** 結果:評價、得票率、走勢、各區、成就、分享 */ /** 挑戰連結的內容:劇本、候選人、種子、逆風、勢均力敵,以及這次的得票率(給朋友比) */ export function challengeLink(view: RogueView): string { const data = { s: view.scenarioId, c: view.you.id, seed: view.seed, a: view.options.ascension, e: view.options.even, share: Math.round((view.result?.youShare ?? 0) * 10000) / 10000, n: view.you.name }; const bytes = new TextEncoder().encode(JSON.stringify(data)); const code = btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); return `${location.origin}${location.pathname}#/rogue?challenge=${code}`; } function ResultPanel({ view, record, island, coins, onAgain, onHome, }: { view: RogueView; record: RunRecord; island: { points: number; reason: string } | null; coins: { coins: number; reason: string } | null; onAgain: (ascension?: number) => void; onHome: () => void; }) { const r = view.result!; const [feats, setFeats] = useState>(new Map()); const [sharing, setSharing] = useState(null); const tutorial = view.options.tutorial; const names = useMemo(() => new Map(view.towns.map((t) => [t.code, t.name])), [view.towns]); useEffect(() => { let alive = true; void loadFeatNames().then((m) => alive && setFeats(m)); if (record.newFeats.length > 0) sfx.good(); return () => { alive = false; }; }, [record.newFeats.length]); /** 朋友挑戰連結:同一場選舉、同一個種子、同樣的逆風等級(同一個區網或上線後才連得到) */ const copyChallenge = async () => { const link = challengeLink(view); try { await navigator.clipboard.writeText(link); setSharing("已複製挑戰連結,貼給朋友:同一個開局、同樣的牌序,看誰選得比較好"); } catch { setSharing(`挑戰連結:${link}`); } }; const share = async () => { setSharing("圖卡產生中…"); try { const blob = await drawShareCard(view); const file = new File([blob], "election-town-result.png", { type: "image/png" }); const nav = navigator as Navigator & { canShare?: (data: ShareData) => boolean }; if (nav.share && nav.canShare?.({ files: [file] })) { try { await nav.share({ files: [file], title: `${raceLabel(view)}選戰結果` }); setSharing(null); return; } catch (e) { if (e instanceof DOMException && e.name === "AbortError") { setSharing(null); return; } } } const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = "election-town-result.png"; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 4000); setSharing("圖卡已下載"); } catch { setSharing("圖卡產生失敗,請再試一次"); } }; return (
{tutorial ? (

教學完成!

你已經會看對手意圖、疊組合拳、打對台了。開始你的第一場選戰吧。

) : (
{r.grade} {GRADE_TEXT[r.grade]}
)}

{r.won ? `${view.you.name}凍蒜!` : `${view.you.name}落選`}

{raceLabel(view)} {view.options.ascension > 0 && 逆風 {view.options.ascension} 級} {view.options.daily && 每日一戰 {view.options.daily} 完成} {record.record && !tutorial && {r.won ? "新紀錄" : "個人最佳"}}

{record.unlocked !== null && (

解鎖逆風 {record.unlocked} 級!

)} {island && (

政績點 +{island.points}({island.reason}) 去政策島蓋建築

)} {coins && (

小鎮幣 +{coins.coins}({coins.reason}) 去服裝店

)}
{pct(r.youShare, 2)} {num(r.you)} 票 vs {pct(r.rivalShare, 2)} {num(r.rival)} 票
{r.feats.length > 0 && (

這局拿到的成就

    {r.feats.map((id, i) => { const f = feats.get(id); const fresh = record.newFeats.includes(id); return (
  • {f?.name ?? id} {f && {f.text}} {fresh && NEW}
  • ); })}
)}
各區開票
    {[...r.byTown] .sort((a, b) => townTotal(b) - townTotal(a)) .map((t) => { const total = townTotal(t) || 1; return (
  • {names.get(t.code) ?? t.code} = t.rival ? "is-up" : "is-down"}>{signed(t.you - t.rival)}
  • ); })}
{tutorial ? ( ) : ( <> {view.options.career ? ( ) : ( )} {record.unlocked !== null && !view.options.career && ( )} {!view.options.career && ( )} )}
{sharing && (

{sharing}

)}
); } /** 每週結束時的支持度走勢(已表態的票裡的比例) */ function Trend({ view }: { view: RogueView }) { const h = view.history; if (h.length < 2) return null; const W = 320; const H = 120; const values = h.flatMap((x) => [x.you, x.rival]); const lo = Math.min(...values) - 0.01; const hi = Math.max(...values) + 0.01; const x = (i: number) => 26 + (i / (h.length - 1)) * (W - 44); const y = (v: number) => 10 + (1 - (v - lo) / (hi - lo || 1)) * (H - 32); const line = (key: "you" | "rival") => h.map((p, i) => `${i ? "L" : "M"}${x(i).toFixed(1)},${y(p[key]).toFixed(1)}`).join(" "); const last = h[h.length - 1]!; return (
{h.map((p, i) => ( {p.week === 0 ? "開局" : p.week} ))}
● {view.you.name} ● {view.rival.name} 每週結束時的支持度
); } /** var(--slot-a) 這種寫法換成實際顏色(canvas 不認得 CSS 變數) */ function resolveColor(value: string, fallback: string): string { const m = /^var\((--[\w-]+)\)$/.exec(value.trim()); if (!m) return value || fallback; const v = getComputedStyle(document.documentElement).getPropertyValue(m[1]!).trim(); return v || fallback; } const cssVar = (name: string, fallback: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback; /** 1080×1350 的結果圖卡(PNG):不用外部圖片、不畫真人照片,右下角標「選舉小鎮・選戰遊戲」 */ async function drawShareCard(view: RogueView): Promise { const r = view.result!; const W = 1080; const H = 1350; const canvas = document.createElement("canvas"); canvas.width = W; canvas.height = H; const ctx = canvas.getContext("2d"); if (!ctx) throw new Error("瀏覽器不支援 canvas"); const serif = cssVar("--font-serif", '"Noto Sans TC", sans-serif'); const numFont = cssVar("--font-num", '"Noto Sans TC", sans-serif'); try { await Promise.all([document.fonts.load(`900 64px ${serif}`, `${raceLabel(view)}選戰凍蒜落選`), document.fonts.load(`800 64px ${numFont}`, "0123456789.%")]); } catch { // 字型載不到就用系統字 } const ink = "#111419"; const paper = "#ecebe6"; const stamp = "#d61f2c"; const signal = "#ffd23f"; const muted = "#5d646e"; const youColor = resolveColor(view.colors.you, "#d6457a"); const rivalColor = resolveColor(view.colors.rival, "#6b4fbb"); const otherColor = resolveColor("var(--slot-other)", "#858a8f"); const font = (weight: number, size: number, family = serif) => `${weight} ${size}px ${family}`; // 底與頂部紅色看板 ctx.fillStyle = paper; ctx.fillRect(0, 0, W, H); ctx.fillStyle = stamp; ctx.fillRect(0, 0, W, 250); ctx.fillStyle = ink; ctx.fillRect(0, 250, W, 10); ctx.fillStyle = signal; ctx.font = font(800, 34); ctx.textBaseline = "alphabetic"; ctx.fillText("選舉小鎮・選戰卡牌", 64, 86); ctx.fillStyle = "#ffffff"; ctx.font = font(900, 84); fitText(ctx, `${raceLabel(view)}選戰`, 64, 190, W - 128); // 雙方 const sides = [ { c: view.you, color: youColor, share: r.youShare, votes: r.you, x: 64 }, { c: view.rival, color: rivalColor, share: r.rivalShare, votes: r.rival, x: W / 2 + 24 }, ]; for (const s of sides) { const cx = s.x + 52; const cy = 350; ctx.beginPath(); ctx.arc(cx, cy, 46, 0, Math.PI * 2); ctx.fillStyle = s.color; ctx.fill(); ctx.lineWidth = 6; ctx.strokeStyle = ink; ctx.stroke(); ctx.fillStyle = "#ffffff"; ctx.font = font(800, 52, numFont); ctx.textAlign = "center"; ctx.fillText(String(s.c.number), cx, cy + 18); ctx.textAlign = "left"; ctx.fillStyle = ink; ctx.font = font(900, 50); fitText(ctx, s.c.name, s.x + 116, cy + 18, W / 2 - 160); ctx.fillStyle = s.color; ctx.font = font(800, 128, numFont); ctx.fillText(pct(s.share, 2), s.x, 530); ctx.fillStyle = muted; ctx.font = font(700, 32); ctx.fillText(`${num(s.votes)} 票`, s.x + 4, 580); } // 評價 ctx.fillStyle = r.won ? stamp : muted; roundRect(ctx, 64, 620, W - 128, 120, 22); ctx.fill(); ctx.fillStyle = "#ffffff"; ctx.font = font(800, 96, numFont); ctx.fillText(r.grade, 100, 715); ctx.font = font(900, 54); fitText(ctx, `${r.won ? `${view.you.name}凍蒜!` : `${view.you.name}落選`}・${GRADE_TEXT[r.grade]}`, 190, 702, W - 300); // 各區小長條(最多 13 區,人多的先) const names = new Map(view.towns.map((t) => [t.code, t.name])); const towns = [...r.byTown].sort((a, b) => townTotal(b) - townTotal(a)).slice(0, 13); const top = 790; const rowH = Math.min(30, Math.floor(330 / Math.max(1, towns.length))); towns.forEach((t, i) => { const y = top + i * rowH; const total = townTotal(t) || 1; ctx.fillStyle = ink; ctx.font = font(700, Math.min(24, rowH - 6)); fitText(ctx, names.get(t.code) ?? t.code, 64, y + rowH - 8, 170); let x = 250; const bw = 640; const bh = rowH - 10; for (const [v, color] of [ [t.you, youColor], [t.others, otherColor], [t.rival, rivalColor], ] as const) { const w = (v / total) * bw; ctx.fillStyle = color; ctx.fillRect(x, y + 4, w, bh); x += w; } ctx.strokeStyle = ink; ctx.lineWidth = 2; ctx.strokeRect(250, y + 4, bw, bh); ctx.fillStyle = t.you >= t.rival ? "#1f8a4c" : stamp; ctx.font = font(700, Math.min(24, rowH - 6), numFont); ctx.fillText(signed(t.you - t.rival), 910, y + rowH - 8); }); // 標語、日期、逆風、浮水印 let y = top + towns.length * rowH + 60; if (view.you.slogan) { ctx.fillStyle = ink; ctx.font = font(900, 44); fitText(ctx, `「${view.you.slogan}」`, 64, Math.min(y, 1220), W - 128); y += 60; } const meta = [todayKey(), view.options.ascension > 0 ? `逆風 ${view.options.ascension} 級` : "", view.options.daily ? "每日一戰" : ""].filter(Boolean).join("・"); ctx.fillStyle = muted; ctx.font = font(700, 28); ctx.fillText(meta, 64, H - 40); ctx.textAlign = "right"; ctx.fillText("選舉小鎮・選戰遊戲", W - 64, H - 40); ctx.textAlign = "left"; return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("圖卡產生失敗"))), "image/png")); } /** 太長的字縮小到放得下 */ function fitText(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, maxWidth: number): void { const m = /(\d+(?:\.\d+)?)px/.exec(ctx.font); let size = m ? Number(m[1]) : 32; const base = ctx.font; while (size > 14 && ctx.measureText(text).width > maxWidth) { size -= 2; ctx.font = base.replace(/\d+(?:\.\d+)?px/, `${size}px`); } ctx.fillText(text, x, y); ctx.font = base; } function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number): void { ctx.beginPath(); ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r); ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath(); }