loadUnlockedOutfits()
This function shows how to restore game progress using the browser's localStorage API, which lets data survive page refreshes and browser restarts.
function loadUnlockedOutfits() {
let unlockedData = localStorage.getItem('snakeGameOutfits');
if (unlockedData) {
let unlockedNames = JSON.parse(unlockedData);
for (let outfit of outfits) {
if (unlockedNames.includes(outfit.name)) {
outfit.unlocked = true;
}
}
}
}
Line-by-line explanation (5 lines)
🔧 Subcomponents:
for (let outfit of outfits) {
Loops through every outfit and flips its unlocked flag on if its name was saved previously
let unlockedData = localStorage.getItem('snakeGameOutfits');- Reads a saved string from the browser's localStorage under the key 'snakeGameOutfits' - this persists even after the page is closed
if (unlockedData) {- Only proceeds if something was actually saved before (first-time players will have nothing stored)
let unlockedNames = JSON.parse(unlockedData);- Converts the saved string back into a real JavaScript array of outfit names
if (unlockedNames.includes(outfit.name)) {- Checks if this outfit's name is in the saved list of unlocked names
outfit.unlocked = true;- Marks the outfit object as unlocked so the outfits menu shows it as available