election-game/web/src/game/rogue/progress.ts

260 lines
10 KiB
TypeScript
Raw Normal View History

import { RogueArchetype, type RogueView } from "@election2026/protocol";
import { rogueApi } from "../api.ts";
import { COUNTIES } from "../counties.ts";
/**
* 選戰卡牌的進度(docs/22):成就、逆風難度解鎖、圖鑑看過的東西、每日一戰成績。
* 只存在玩家自己的瀏覽器(localStorage);讀不到(私密模式)就當作第一次玩。
*/
export interface Progress {
/** 拿到的成就 → 第一次拿到的日期 */
feats: Record<string, string>;
/** 解鎖到第幾級逆風(贏了第 n 級開第 n+1 級) */
ascension: number;
seen: { cards: string[]; advisors: string[]; events: string[] };
runs: number;
wins: number;
/** 各劇本最好的成績(得票率) */
best: Record<string, { share: number; grade: string; ascension: number; won: boolean }>;
/** 每日一戰:日期 → 成績 */
daily: Record<string, { share: number; won: boolean; grade: string }>;
/** 已經記錄過的局(重新整理結果畫面不會重複算) */
recorded: string[];
/** 玩過的真實參選人(參選人卡冊用,玩過才上色):名字 → 局數、勝場、最好評等、玩過的劇本 */
played: Record<string, PlayedCandidate>;
/** 舊存檔已經從記錄過的局補過 played */
playedBackfilled?: boolean;
tutorialDone: boolean;
/** 全台制霸(docs/25):打贏過的縣市代碼 → 第一次打贏的日期;總統大選是 "00000" */
conquered?: Record<string, string>;
/** 每種候選人類型打贏過的最高逆風等級(沒贏過就沒有) */
typeBest?: Partial<Record<RogueArchetype, number>>;
}
export interface PlayedCandidate {
runs: number;
wins: number;
grade: string | null;
scenarios: string[];
}
const KEY = "tongsuan.rogue.progress.v1";
/** 上一局的 id(首頁的「繼續選戰」用) */
export const LAST_RUN_KEY = "tongsuan.rogue.last";
const MAX_ASCENSION = 10;
const empty = (): Progress => ({
feats: {},
ascension: 0,
seen: { cards: [], advisors: [], events: [] },
runs: 0,
wins: 0,
best: {},
daily: {},
recorded: [],
played: {},
tutorialDone: false,
});
export function loadProgress(): Progress {
try {
const raw = localStorage.getItem(KEY);
if (!raw) return empty();
const p = JSON.parse(raw) as Partial<Progress>;
const base = empty();
return { ...base, ...p, seen: { ...base.seen, ...(p.seen ?? {}) } };
} catch {
return empty();
}
}
function saveProgress(p: Progress): void {
try {
localStorage.setItem(KEY, JSON.stringify(p));
} catch {
// 私密模式存不了:這次的進度只留在畫面上
}
}
/** 今天的日期(玩家當地時間),每日一戰用 */
export function todayKey(now = new Date()): string {
const y = now.getFullYear();
const m = String(now.getMonth() + 1).padStart(2, "0");
const d = String(now.getDate()).padStart(2, "0");
return `${y}-${m}-${d}`;
}
/** 每日一戰的題目:同一天從清單裡挑同一個(清單順序要固定) */
export function dailyPick<T>(items: readonly T[], date: string): T | undefined {
let h = 2166136261;
for (const ch of date) h = Math.imul(h ^ ch.charCodeAt(0), 16777619);
return items[(h >>> 0) % Math.max(1, items.length)];
}
/** 記下看過的牌、幕僚、事件(圖鑑用) */
export function markSeen(view: RogueView): void {
const p = loadProgress();
const add = (list: string[], ids: readonly string[]) => {
const set = new Set(list);
let changed = false;
for (const id of ids) {
if (!set.has(id)) {
set.add(id);
changed = true;
}
}
return changed ? [...set] : list;
};
const offers = view.stop && "options" in view.stop ? view.stop.options : view.stop?.kind === "shop" ? view.stop.items : [];
const cards = add(p.seen.cards, [...view.deck.map((c) => c.id), ...offers.filter((o) => o.kind === "card").map((o) => o.id)]);
const advisors = add(p.seen.advisors, [...view.advisors.map((a) => a.id), ...offers.filter((o) => o.kind === "advisor").map((o) => o.id)]);
const events = add(p.seen.events, [view.event.id]);
if (cards === p.seen.cards && advisors === p.seen.advisors && events === p.seen.events) return;
saveProgress({ ...p, seen: { cards, advisors, events } });
}
/** 全台制霸的地盤:22 個縣市加總統大選 */
export const PRESIDENT_CODE = "00000";
export const TERRITORIES: readonly [string, string][] = [...COUNTIES, [PRESIDENT_CODE, "總統大選"]];
const territoryName = (code: string): string | null => TERRITORIES.find(([c]) => c === code)?.[1] ?? null;
export interface CompletionPart {
id: "map" | "types" | "climb" | "feats";
label: string;
hint: string;
done: number;
total: number;
}
/**
* 完成度(docs/25:讓人一場接一場、想把東西收集完):全台制霸、六種類型都贏過、每種類型的逆風挑戰、成就。
* percent 是四項的平均;featTotal 是成就總數(圖鑑目錄給)
*/
export function completion(p: Progress, featTotal: number): { parts: CompletionPart[]; percent: number } {
const types = RogueArchetype.options;
const best = p.typeBest ?? {};
const parts: CompletionPart[] = [
{ id: "map", label: "全台制霸", hint: "22 個縣市和總統大選,每一塊都打贏一次", done: Object.keys(p.conquered ?? {}).length, total: TERRITORIES.length },
{ id: "types", label: "六種類型", hint: "媒體、組織、資深、財務、清廉、黑馬型都贏過", done: types.filter((t) => best[t] !== undefined).length, total: types.length },
{ id: "climb", label: "類型逆風挑戰", hint: "每種類型從逆風 0 一路贏到逆風 10", done: types.reduce((a, t) => a + (best[t] === undefined ? 0 : best[t]! + 1), 0), total: types.length * (MAX_ASCENSION + 1) },
{ id: "feats", label: "成就", hint: "圖鑑裡的成就", done: Object.keys(p.feats).length, total: Math.max(featTotal, Object.keys(p.feats).length) },
];
const percent = parts.reduce((a, x) => a + (x.total ? Math.min(1, x.done / x.total) : 0), 0) / parts.length;
return { parts, percent };
}
export interface RunRecord {
/** 這局第一次拿到的成就 */
newFeats: string[];
/** 這局第一次打下的地盤(縣市或總統大選;沒有是 null) */
conquered: string | null;
/** 這個類型的逆風新紀錄(沒有是 null) */
typeRecord: { archetype: RogueArchetype; level: number } | null;
/** 這局解鎖的逆風等級(沒有是 null) */
unlocked: number | null;
/** 這個劇本的新紀錄 */
record: boolean;
progress: Progress;
}
function playedAfter(prev: PlayedCandidate | undefined, scenarioId: string, won: boolean, grade: string): PlayedCandidate {
const p = prev ?? { runs: 0, wins: 0, grade: null, scenarios: [] };
const better = !p.grade || "SABCD".indexOf(grade) < "SABCD".indexOf(p.grade);
return {
runs: p.runs + 1,
wins: p.wins + (won ? 1 : 0),
grade: better ? grade : p.grade,
scenarios: p.scenarios.includes(scenarioId) ? p.scenarios : [...p.scenarios, scenarioId],
};
}
/** 玩過的真實參選人(名字 → 紀錄),參選人卡冊用 */
export function playedCandidates(): Record<string, PlayedCandidate> {
return loadProgress().played;
}
/** 有 played 之前就玩過的局:從記錄過的局補一次(只做一次;讀不到的局略過) */
export async function backfillPlayed(): Promise<Record<string, PlayedCandidate>> {
const p = loadProgress();
if (p.playedBackfilled) return p.played;
const views = await Promise.all(p.recorded.map((id) => rogueApi.get(id).catch(() => null)));
let played = p.played;
for (const v of views) {
if (!v?.result || v.options.tutorial || v.you.id === "custom") continue;
played = {
...played,
[v.you.name]: playedAfter(played[v.you.name], v.scenarioId, v.result.won, v.result.grade),
};
}
// 補的這段時間可能又打完一局:以最新的存檔為準,只補它還沒有的人
const now = loadProgress();
const merged = { ...played, ...now.played };
saveProgress({ ...now, played: merged, playedBackfilled: true });
return merged;
}
/** 一局打完:記成就、解鎖下一級逆風、最佳成績、每日一戰。同一局只算一次 */
export function recordRun(view: RogueView): RunRecord {
const p = loadProgress();
const r = view.result;
if (!r || p.recorded.includes(view.runId)) return { newFeats: [], conquered: null, typeRecord: null, unlocked: null, record: false, progress: p };
const today = todayKey();
const newFeats = r.feats.filter((f) => !p.feats[f]);
const feats = {
...p.feats,
...Object.fromEntries(newFeats.map((f) => [f, today])),
};
const tutorial = view.options.tutorial;
const level = view.options.ascension;
const unlocked = r.won && !tutorial && level >= p.ascension && level < MAX_ASCENSION ? level + 1 : null;
const prev = p.best[view.scenarioId];
const record = !tutorial && (!prev || r.youShare > prev.share);
// 全台制霸與類型挑戰:打贏才算,新手教學不算
const territory = territoryName(view.countyCode) ? view.countyCode : null;
const conquered = r.won && !tutorial && territory && !p.conquered?.[territory] ? territory : null;
const arch = view.identity?.archetype ?? null;
const typeRecord = r.won && !tutorial && arch && level > (p.typeBest?.[arch] ?? -1) ? { archetype: arch, level } : null;
const next: Progress = {
...p,
feats,
ascension: unlocked ?? p.ascension,
runs: p.runs + (tutorial ? 0 : 1),
wins: p.wins + (r.won && !tutorial ? 1 : 0),
best: record
? {
...p.best,
[view.scenarioId]: {
share: r.youShare,
grade: r.grade,
ascension: level,
won: r.won,
},
}
: p.best,
daily:
view.options.daily && !p.daily[view.options.daily]
? {
...p.daily,
[view.options.daily]: {
share: r.youShare,
won: r.won,
grade: r.grade,
},
}
: p.daily,
recorded: [...p.recorded, view.runId].slice(-60),
played:
tutorial || view.you.id === "custom"
? p.played
: {
...p.played,
[view.you.name]: playedAfter(p.played[view.you.name], view.scenarioId, r.won, r.grade),
},
tutorialDone: p.tutorialDone || tutorial,
conquered: conquered ? { ...p.conquered, [conquered]: today } : p.conquered,
typeBest: typeRecord ? { ...p.typeBest, [typeRecord.archetype]: typeRecord.level } : p.typeBest,
};
saveProgress(next);
return { newFeats, conquered: conquered ? territoryName(conquered) : null, typeRecord, unlocked, record, progress: next };
}