Files
projects/Dockers/inez-game/js/storage.js
T
Bram 73baba74b1
Build and Push Docker Images / build-and-push (push) Failing after 56s
Inez Game
2026-11-05 13:52:59 +01:00

118 lines
2.8 KiB
JavaScript

const Storage = (function () {
const STATE_KEY = "inez-unlock-game-v1";
const MUTE_KEY = "inez-unlock-muted";
function defaults() {
return { unlocked: 1, completed: [], revealed: [] };
}
function levelCount() {
if (typeof Levels !== "undefined" && Levels.count) return Levels.count;
return GAME_CONFIG.games ? GAME_CONFIG.games.length : 5;
}
function safeGet(key) {
try {
return window.localStorage.getItem(key);
} catch (error) {
return null;
}
}
function safeSet(key, value) {
try {
window.localStorage.setItem(key, value);
} catch (error) {
}
}
function load() {
const raw = safeGet(STATE_KEY);
if (!raw) return defaults();
try {
const parsed = JSON.parse(raw);
return sanitize(parsed);
} catch (error) {
return defaults();
}
}
function sanitize(value) {
const state = defaults();
const total = levelCount();
if (!value || typeof value !== "object") return state;
const unlocked = Number(value.unlocked);
if (Number.isFinite(unlocked)) {
state.unlocked = Math.min(total, Math.max(1, Math.floor(unlocked)));
}
if (Array.isArray(value.completed)) {
state.completed = uniqueLevels(value.completed);
}
if (Array.isArray(value.revealed)) {
state.revealed = uniqueGames(value.revealed);
}
const highest = state.completed.length > 0 ? state.completed[state.completed.length - 1] : 0;
state.unlocked = Math.max(state.unlocked, Math.min(total, highest + 1));
if (state.completed.length === total) state.unlocked = total;
return state;
}
function uniqueLevels(values) {
const seen = new Set();
const result = [];
const total = levelCount();
values.forEach(function (value) {
const number = Math.floor(Number(value));
if (number >= 1 && number <= total && !seen.has(number)) {
seen.add(number);
result.push(number);
}
});
return result.sort(function (a, b) { return a - b; });
}
function uniqueGames(values) {
const seen = new Set();
const result = [];
values.forEach(function (value) {
const number = Math.floor(Number(value));
const count = GAME_CONFIG.games ? GAME_CONFIG.games.length : 5;
if (number >= 0 && number < count && !seen.has(number)) {
seen.add(number);
result.push(number);
}
});
return result.sort(function (a, b) { return a - b; });
}
function save(state) {
safeSet(STATE_KEY, JSON.stringify(state));
}
function reset() {
const state = defaults();
save(state);
return state;
}
function loadMuted() {
return safeGet(MUTE_KEY) === "1";
}
function saveMuted(muted) {
safeSet(MUTE_KEY, muted ? "1" : "0");
}
return {
load: load,
save: save,
reset: reset,
loadMuted: loadMuted,
saveMuted: saveMuted
};
})();