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

212 lines
7.4 KiB
TypeScript
Raw Normal View History

import type { RogueView } from "@election2026/protocol";
import { rogueApi } from "../api.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;
}
export interface PlayedCandidate {
runs: number;
wins: number;
grade: string | null;
scenarios: string[];
}
const KEY = "tongsuan.rogue.progress.v1";
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 } });
}
export interface RunRecord {
/** 這局第一次拿到的成就 */
newFeats: string[];
/** 這局解鎖的逆風等級(沒有是 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: [], 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 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,
};
saveProgress(next);
return { newFeats, unlocked, record, progress: next };
}