2026-10-30 11:47:19 +00:00
|
|
|
|
import { ABILITY_IDS, DEFAULT_AVATAR_SPEC, START_POINTS, StartPoints, legacyPoints, parseAvatarLoose, type CustomCandidate } from "@election2026/protocol";
|
2026-10-28 07:58:33 +00:00
|
|
|
|
|
|
|
|
|
|
/** 玩家捏好的角色存在這台瀏覽器裡(只是方便下次再用;讀不到就是空的) */
|
|
|
|
|
|
const KEY = "tongsuan.characters";
|
|
|
|
|
|
|
2026-10-30 11:47:19 +00:00
|
|
|
|
/** 開局能力存在 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) };
|
|
|
|
|
|
}
|
2026-10-28 07:58:33 +00:00
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 讀存檔時清洗頭像(docs/24):照部件目錄檢查,看不懂的部件代號換成預設、壞掉的欄位丟掉,存檔壞掉也不會當機。
|
2026-10-30 11:47:19 +00:00
|
|
|
|
* 舊存檔的頭像本來就合法,原封不動;舊版的能力點數換成開局能力點。
|
2026-10-28 07:58:33 +00:00
|
|
|
|
*/
|
|
|
|
|
|
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;
|
2026-10-30 11:47:19 +00:00
|
|
|
|
return { ...withPoints(c), avatar: parseAvatarLoose(c.avatar) ?? DEFAULT_AVATAR_SPEC };
|
2026-10-28 07:58:33 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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 {
|
|
|
|
|
|
// 同上
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|