election-game/web/src/game/rogue/finale.tsx

819 lines
35 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { RogueResult, RogueView } from "@election2026/protocol";
import { ArrowRight, Coins, Flame, Home, Landmark, MapPin, Medal, RotateCcw, Share2, SkipForward, Swords, Trophy } from "lucide-react";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { api, 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, TERRITORIES, todayKey, type RunRecord } from "./progress.ts";
import "./rogue-finale.css";
/**
* 選戰卡牌的最後一幕(docs/22):開票夜一區一區開出來,然後是結果、成就、分享圖卡。
* view.phase === "finished" 時由 RogueScreen 蓋在地圖上面。
*/
export const GRADE_TEXT: Record<RogueResult["grade"], string> = { S: "壓倒性勝利", A: "穩穩當選", B: "險勝凍蒜", C: "飲恨落選", D: "大敗" };
type TownResult = RogueResult["byTown"][number];
const townTotal = (t: Pick<TownResult, "you" | "rival" | "others">) => t.you + t.rival + t.others;
/** 同一局只記一次(重新整理、React 開發模式重跑都不會重複算) */
const records = new Map<string, RunRecord>();
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<Map<string, { name: string; text: string }>> | 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<string, { name: string; text: string }>();
});
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<typeof countPlan>, byTown: readonly TownResult[]): Map<string, TownCount> {
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<string, TownCount>, 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" ? <VoteNight view={view} map={map} onDone={() => setStage("result")} /> : <ResultPanel view={view} record={record} island={island} coins={coins} onAgain={onAgain} onHome={onHome} />;
}
/** 開票夜:各區一點一點開,地圖跟著上色,兩邊的票數往上跳 */
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<string>());
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 (
<div className="rgn-overlay" role="dialog" aria-modal="true" aria-label="開票夜">
<section className={`rgn-night${mapNode ? " has-map" : ""}`}>
{flash > 0 && <span className="rgn-flash" key={flash} aria-hidden />}
{mapNode && (
<div className="rgn-map" aria-hidden>
{mapNode}
</div>
)}
<header className="rgn-night-head">
<span className="rgn-live">LIVE</span>
<h2>開票夜・{raceLabel(view)}</h2>
<span className="rgn-progress">
開票 <b>{Math.round(progress * 100)}%</b>
<small>
開完 {finished} / {rows.length} 區
</small>
</span>
</header>
<div className="rgn-board">
<Side name={view.you.name} candidate={view.you} color={view.colors.you} votes={you} share={share(you)} leading={lead > 0 && cast > 0} won={final && r.won} />
<span className="rgn-vs">VS</span>
<Side name={view.rival.name} candidate={view.rival} color={view.colors.rival} votes={rival} share={share(rival)} leading={lead < 0 && cast > 0} won={final && !r.won && r.rival > r.others} />
</div>
<div className="rgn-tug" aria-hidden>
<i style={{ width: `${share(you) * 100}%`, background: view.colors.you }} />
<i style={{ width: `${share(others) * 100}%`, background: "var(--slot-other)" }} />
<i style={{ width: `${share(rival) * 100}%`, background: view.colors.rival }} />
</div>
<ol className="rgn-towns" aria-label="各區開票">
{rows.map((t) => {
const c = counts.get(t.code)!;
const total = c.you + c.rival + c.others;
return (
<li key={t.code} className={`${c.f >= 1 ? "is-done" : c.f > 0 ? "is-counting" : "is-waiting"}${t.code === latest && !final ? " is-new" : ""}`}>
<b>{names.get(t.code) ?? t.code}</b>
<span className="rgn-bar">
{total > 0 && (
<>
<i style={{ width: `${(c.you / total) * 100}%`, background: view.colors.you }} />
<i style={{ width: `${(c.others / total) * 100}%`, background: "var(--slot-other)" }} />
<i style={{ width: `${(c.rival / total) * 100}%`, background: view.colors.rival }} />
</>
)}
</span>
<span className="rgn-town-f">{c.f >= 1 ? "開完" : `${Math.round(c.f * 100)}%`}</span>
<small className={c.you >= c.rival ? "is-up" : "is-down"}>{total > 0 ? signed(c.you - c.rival) : "—"}</small>
</li>
);
})}
</ol>
{final ? (
<div className={`rgn-final${r.won ? " is-won" : ""}`}>
<span className="rgn-stamp">
<BallotStamp size={92} color={r.won ? "var(--stamp)" : "var(--muted)"} />
</span>
<strong>{r.won ? `${view.you.name}凍蒜!` : `${view.you.name}落選`}</strong>
<button type="button" className="btn btn-primary btn-lg" onClick={onDone} autoFocus>
看結果 <ArrowRight size={18} aria-hidden />
</button>
</div>
) : (
<button type="button" className="btn btn-ghost rgn-skip" onClick={() => setTick(TICKS)}>
<SkipForward size={16} aria-hidden /> 跳過,直接開完
</button>
)}
</section>
</div>
);
}
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 (
<div className={`rgn-side${leading ? " is-leading" : ""}${won ? " is-won" : ""}`} style={{ "--c": color } as React.CSSProperties}>
<CandidateBadge candidate={candidate} size={56} />
<b className="rgn-name">{name}</b>
<span className="rgn-votes">{num(votes)}</span>
<span className="rgn-share">{pct(share)}</span>
{leading && <em className="rgn-lead">領先</em>}
</div>
);
}
/** 結果:評價、得票率、走勢、各區、成就、分享 */
/** 挑戰連結的內容:劇本、候選人、種子、逆風、勢均力敵,以及這次的得票率(給朋友比) */
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<Map<string, { name: string; text: string }>>(new Map());
const [sharing, setSharing] = useState<string | null>(null);
const tutorial = view.options.tutorial;
const names = useMemo(() => new Map(view.towns.map((t) => [t.code, t.name])), [view.towns]);
const free = !tutorial && !view.options.career;
const level = view.options.ascension;
// 贏了就能直接挑戰下一級(已經解鎖的話):一場接一場
const nextLevel = r.won && free && !view.options.daily && level < 10 && level + 1 <= record.progress.ascension ? level + 1 : null;
const owned = Object.keys(record.progress.conquered ?? {}).length;
const [moving, setMoving] = useState(false);
/** 攻下一塊地盤(全台制霸):挑一個還沒打下的縣市,縣市長劇本(勢均力敵版優先、最近一屆),兩大黨候選人隨機一位 */
const conquerNext = async () => {
setMoving(true);
try {
const done = new Set(Object.keys(record.progress.conquered ?? {}));
const list = await api.scenarios();
const open = list.filter((s) => !done.has(s.region.countyCode) && (s.region.kind === "mayor" || s.region.kind === "president"));
const counties = [...new Set(open.map((s) => s.region.countyCode))];
const county = counties[Math.floor(Math.random() * counties.length)];
const pool = open.filter((s) => s.region.countyCode === county).sort((a, b) => Number(b.id.endsWith("-even")) - Number(a.id.endsWith("-even")) || b.electionDate.localeCompare(a.electionDate));
const s = pool[0];
if (!s) return;
const majors = s.candidates.filter((c) => c.slot === "a" || c.slot === "b");
const cand = (majors.length ? majors : s.candidates)[Math.floor(Math.random() * (majors.length || s.candidates.length))]!;
const { runId } = await rogueApi.create(s.id, cand.id, { ascension: level, even: s.id.endsWith("-even") });
location.hash = `#/rogue/${runId}`;
} catch (e) {
setSharing(e instanceof Error ? e.message : String(e));
setMoving(false);
}
};
// Enter 直接再來一局(贏了就挑戰下一級):焦點不在按鈕、輸入框上的時候
useEffect(() => {
if (!free) return;
const onKey = (e: KeyboardEvent) => {
if (e.key !== "Enter" || e.repeat || (document.activeElement && document.activeElement !== document.body)) return;
e.preventDefault();
onAgain(nextLevel ?? undefined);
};
addEventListener("keydown", onKey);
return () => removeEventListener("keydown", onKey);
}, [free, nextLevel, onAgain]);
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 (
<div className="rgn-overlay is-result" role="dialog" aria-modal="true" aria-label="開票結果">
<section className="rgn-result">
{tutorial ? (
<div className="rgn-tutorial">
<Trophy size={48} aria-hidden />
<h2>教學完成!</h2>
<p>你已經會看對手意圖、疊組合拳、打對台了。開始你的第一場選戰吧。</p>
</div>
) : (
<div className={`rgn-grade g-${r.grade}`}>
<BallotStamp size={86} color={r.won ? "var(--stamp)" : "var(--muted)"} />
<b>{r.grade}</b>
<span>{GRADE_TEXT[r.grade]}</span>
</div>
)}
<h2 className="rgn-title">{r.won ? `${view.you.name}凍蒜!` : `${view.you.name}落選`}</h2>
<p className="rgn-tags">
{raceLabel(view)}
{view.options.ascension > 0 && <span className="rgn-tag is-asc">逆風 {view.options.ascension} 級</span>}
{view.options.daily && <span className="rgn-tag is-daily">每日一戰 {view.options.daily} 完成</span>}
{record.record && !tutorial && <span className="rgn-tag is-record">{r.won ? "新紀錄" : "個人最佳"}</span>}
</p>
{record.unlocked !== null && (
<p className="rgn-unlock">
<Flame size={20} aria-hidden /> 解鎖逆風 {record.unlocked} 級!
</p>
)}
{record.conquered && (
<p className="rgn-unlock is-map">
<MapPin size={20} aria-hidden /> 全台制霸:拿下{record.conquered}!({owned}/{TERRITORIES.length})
<a href="#/rogue/collection">看制霸地圖</a>
</p>
)}
{record.typeRecord && view.identity && (
<p className="rgn-unlock is-type">
<Medal size={20} aria-hidden /> {view.identity.name}的新紀錄:贏下逆風 {record.typeRecord.level} 級
</p>
)}
{island && (
<p className="rgn-unlock is-island">
<Landmark size={20} aria-hidden /> 政績點 +{island.points}({island.reason})
<a href="#/island">去政策島蓋建築</a>
</p>
)}
{coins && (
<p className="rgn-unlock is-coins">
<Coins size={20} aria-hidden /> 小鎮幣 +{coins.coins}({coins.reason})
<a href="#/shop">去服裝店</a>
</p>
)}
<div className="rgn-final-score">
<span>
<CandidateBadge candidate={view.you} size={44} />
<b style={{ color: view.colors.you }}>{pct(r.youShare, 2)}</b>
<small>{num(r.you)} 票</small>
</span>
<span className="rgn-vs-small">vs</span>
<span>
<CandidateBadge candidate={view.rival} size={44} />
<b style={{ color: view.colors.rival }}>{pct(r.rivalShare, 2)}</b>
<small>{num(r.rival)} 票</small>
</span>
</div>
<Trend view={view} />
{r.feats.length > 0 && (
<section className="rgn-feats" aria-label="這局拿到的成就">
<h3>這局拿到的成就</h3>
<ul>
{r.feats.map((id, i) => {
const f = feats.get(id);
const fresh = record.newFeats.includes(id);
return (
<li key={id} className={fresh ? "is-new" : ""} style={{ "--i": i } as React.CSSProperties}>
<Trophy size={18} aria-hidden />
<span>
<b>{f?.name ?? id}</b>
{f && <small>{f.text}</small>}
</span>
{fresh && <em>NEW</em>}
</li>
);
})}
</ul>
</section>
)}
<details className="rgn-bytown">
<summary>各區開票</summary>
<ul>
{[...r.byTown]
.sort((a, b) => townTotal(b) - townTotal(a))
.map((t) => {
const total = townTotal(t) || 1;
return (
<li key={t.code}>
<span>{names.get(t.code) ?? t.code}</span>
<span className="rgn-bar">
<i style={{ width: `${(t.you / total) * 100}%`, background: view.colors.you }} />
<i style={{ width: `${(t.others / total) * 100}%`, background: "var(--slot-other)" }} />
<i style={{ width: `${(t.rival / total) * 100}%`, background: view.colors.rival }} />
</span>
<small className={t.you >= t.rival ? "is-up" : "is-down"}>{signed(t.you - t.rival)}</small>
</li>
);
})}
</ul>
</details>
<div className="rgn-actions">
{tutorial ? (
<button type="button" className="btn btn-primary btn-lg" onClick={() => (location.hash = "#/rogue")}>
開始第一場選戰 <ArrowRight size={18} aria-hidden />
</button>
) : (
<>
{view.options.career ? (
<button type="button" className="btn btn-primary btn-lg" onClick={() => (location.hash = `#/rogue/career?run=${view.runId}`)}>
<ArrowRight size={18} aria-hidden /> {r.won ? (view.options.career.stage >= view.options.career.total ? "政治生涯完成" : "挑幕僚和牌,前往下一關") : "回政治生涯"}
</button>
) : (
<button type="button" className="btn btn-primary btn-lg" onClick={() => onAgain()}>
<RotateCcw size={18} aria-hidden /> 再選一次
</button>
)}
{nextLevel !== null && (
<button type="button" className="btn btn-lg rgn-asc-btn" onClick={() => onAgain(nextLevel)}>
<Flame size={18} aria-hidden /> 挑戰逆風 {nextLevel} 級
</button>
)}
{free && owned < TERRITORIES.length && (
<button type="button" className="btn btn-soft btn-lg" onClick={() => void conquerNext()} disabled={moving}>
<MapPin size={18} aria-hidden /> {moving ? "挑選地盤中…" : `攻下一塊地盤(還有 ${TERRITORIES.length - owned} 塊)`}
</button>
)}
{!view.options.career && (
<button type="button" className="btn btn-soft btn-lg" onClick={() => void copyChallenge()}>
<Swords size={18} aria-hidden /> 挑戰朋友
</button>
)}
<button type="button" className="btn btn-soft btn-lg" onClick={() => void share()} disabled={sharing === "圖卡產生中…"}>
<Share2 size={18} aria-hidden /> 分享結果圖卡
</button>
</>
)}
<button type="button" className="btn btn-ghost btn-lg" onClick={onHome}>
<Home size={18} aria-hidden /> 回首頁
</button>
</div>
{sharing && (
<p className="rgn-sub" role="status">
{sharing}
</p>
)}
</section>
</div>
);
}
/** 每週結束時的支持度走勢(已表態的票裡的比例) */
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 (
<figure className="rgn-trend">
<svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label={`每週支持度走勢:最後一週你 ${pct(last.you)}、對手 ${pct(last.rival)}`}>
<path d={line("rival")} fill="none" stroke={view.colors.rival} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
<path d={line("you")} fill="none" stroke={view.colors.you} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
{h.map((p, i) => (
<g key={i}>
<circle cx={x(i)} cy={y(p.you)} r="3.2" fill={view.colors.you} stroke="var(--surface)" strokeWidth="1.5" />
<circle cx={x(i)} cy={y(p.rival)} r="2.8" fill={view.colors.rival} stroke="var(--surface)" strokeWidth="1.5" />
<text x={x(i)} y={H - 6} textAnchor="middle" fontSize="10" fill="currentColor" opacity="0.6">
{p.week === 0 ? "開局" : p.week}
</text>
</g>
))}
</svg>
<figcaption>
<span style={{ color: view.colors.you }}>● {view.you.name}</span> <span style={{ color: view.colors.rival }}>● {view.rival.name}</span> 每週結束時的支持度
</figcaption>
</figure>
);
}
/** 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<Blob> {
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();
}