election-game/web/src/game/creator/characters.ts

55 lines
2.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

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 { ABILITY_IDS, DEFAULT_AVATAR_SPEC, START_POINTS, StartPoints, legacyPoints, parseAvatarLoose, type CustomCandidate } from "@election2026/protocol";
/** 玩家捏好的角色存在這台瀏覽器裡(只是方便下次再用;讀不到就是空的) */
const KEY = "tongsuan.characters";
/** 開局能力存在 points(docs/27 第 6 節);舊存檔的 stats 讀進來就換算掉 */
export type SavedCharacter = Omit<CustomCandidate, "replace" | "points" | "stats"> & { id: string; points: StartPoints };
/** 舊存檔(捏人物還是知名度、謀略那五項的時候):stats 換成開局能力點 */
export function withPoints(c: SavedCharacter & { stats?: CustomCandidate["stats"] }): SavedCharacter {
const { stats, ...rest } = c;
const ok = StartPoints.safeParse(c.points);
const points = ok.success && ABILITY_IDS.reduce((a, k) => a + ok.data[k], 0) <= START_POINTS ? ok.data : null;
if (points && !stats) return c;
return { ...rest, points: points ?? legacyPoints(stats) };
}
/**
* 讀存檔時清洗頭像(docs/24):照部件目錄檢查,看不懂的部件代號換成預設、壞掉的欄位丟掉,存檔壞掉也不會當機。
* 舊存檔的頭像本來就合法,原封不動;舊版的能力點數換成開局能力點。
*/
function cleanCharacter(raw: unknown): SavedCharacter | null {
if (!raw || typeof raw !== "object") return null;
const c = raw as SavedCharacter;
if (typeof c.id !== "string" || typeof c.name !== "string") return null;
return { ...withPoints(c), avatar: parseAvatarLoose(c.avatar) ?? DEFAULT_AVATAR_SPEC };
}
export function loadCharacters(): SavedCharacter[] {
try {
const raw = localStorage.getItem(KEY);
const list: unknown = raw ? JSON.parse(raw) : [];
return Array.isArray(list) ? list.map(cleanCharacter).filter((c): c is SavedCharacter => c !== null) : [];
} catch {
return [];
}
}
export function saveCharacter(c: SavedCharacter): void {
try {
const list = loadCharacters().filter((x) => x.id !== c.id);
localStorage.setItem(KEY, JSON.stringify([c, ...list].slice(0, 12)));
} catch {
// 存不了就算了,這次還是可以玩
}
}
export function deleteCharacter(id: string): void {
try {
localStorage.setItem(KEY, JSON.stringify(loadCharacters().filter((x) => x.id !== id)));
} catch {
// 同上
}
}