loadUnlockedOutfits()
This function demonstrates how to persist game progress across browser sessions using the Web Storage API (localStorage), a common technique for save systems in browser games.
🔬 This loop restores unlocked outfits by name. What happens if you clear your browser's localStorage (or rename an outfit in the outfits array) - does the game forget your progress?
for (let outfit of outfits) {
if (unlockedNames.includes(outfit.name)) {
outfit.unlocked = true;
}
}
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) { if (unlockedNames.includes(outfit.name)) { outfit.unlocked = true; } }
Marks each outfit object as unlocked if its name was saved in localStorage from a previous session
let unlockedData = localStorage.getItem('snakeGameOutfits');- Reads a saved string from the browser's localStorage under the key 'snakeGameOutfits' - returns null if nothing was ever saved.
if (unlockedData) {- Only proceeds if something was actually saved before (skips on a brand new browser).
let unlockedNames = JSON.parse(unlockedData);- Converts the saved JSON string back into a real JavaScript array of outfit names.
for (let outfit of outfits) {- Loops through every outfit object defined in the global outfits array.
if (unlockedNames.includes(outfit.name)) { outfit.unlocked = true; }- If this outfit's name is in the saved list, flips its unlocked property to true.