106 lines
2.3 KiB
JavaScript

// storage.js — localStorage helpers
const Storage = (() => {
const KEYS = {
PLAYER_NAME: "gd_playerName",
LOBBY_NAME: "gd_lobbyName",
GAME_STATE: "gd_gameState",
LEADERBOARD: "gd_leaderboard",
};
/**
* Safely write a value to localStorage.
* Silently fails if storage quota is exceeded or unavailable.
* @param {string} key
* @param {string} value
*/
function _set(key, value) {
try {
localStorage.setItem(key, value);
} catch {
console.warn(`Storage: could not write key "${key}"`);
}
}
/** @param {string} name */
function savePlayerName(name) {
_set(KEYS.PLAYER_NAME, name.trim());
}
/** @returns {string} */
function getPlayerName() {
return localStorage.getItem(KEYS.PLAYER_NAME) || "Anonymous";
}
/** @param {string} name */
function saveLobbyName(name) {
_set(KEYS.LOBBY_NAME, name.trim());
}
/** @returns {string} */
function getLobbyName() {
return localStorage.getItem(KEYS.LOBBY_NAME) || "My Lobby";
}
/**
* @param {{ scores: number[], totalScore: number, countries: string[] }} state
*/
function saveGameState(state) {
_set(KEYS.GAME_STATE, JSON.stringify(state));
}
/**
* @returns {{ scores: number[], totalScore: number, countries: string[] } | null}
*/
function getGameState() {
try {
return JSON.parse(localStorage.getItem(KEYS.GAME_STATE)) || null;
} catch {
return null;
}
}
function clearGameState() {
localStorage.removeItem(KEYS.GAME_STATE);
}
/**
* Add an entry to the leaderboard and keep the top 20.
* @param {{ name: string, totalScore: number, scores: number[], date: string }} entry
*/
function saveLeaderboard(entry) {
const board = getLeaderboard();
board.push(entry);
board.sort((a, b) => b.totalScore - a.totalScore);
_set(KEYS.LEADERBOARD, JSON.stringify(board.slice(0, 20)));
}
/**
* @returns {{ name: string, totalScore: number, scores: number[], date: string }[]}
*/
function getLeaderboard() {
try {
return JSON.parse(localStorage.getItem(KEYS.LEADERBOARD)) || [];
} catch {
return [];
}
}
function clearLeaderboard() {
localStorage.removeItem(KEYS.LEADERBOARD);
}
return {
savePlayerName,
getPlayerName,
saveLobbyName,
getLobbyName,
saveGameState,
getGameState,
clearGameState,
saveLeaderboard,
getLeaderboard,
clearLeaderboard,
};
})();