loadUnlockedOutfits()
This function runs once in setup() to restore progress between browser sessions. localStorage only stores strings, which is why the array of names is serialized with JSON.stringify() when saving and parsed back with JSON.parse() when loading.
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) {
Goes through every outfit and flips unlocked to true if its name was saved in localStorage
let unlockedData = localStorage.getItem('snakeGameOutfits');- Reads a saved string from the browser's localStorage, or null if nothing was saved before
if (unlockedData) {- Only continue if there is actually saved data (first-time players will have null here)
let unlockedNames = JSON.parse(unlockedData);- Converts the saved JSON string back into a real JavaScript array of outfit names
if (unlockedNames.includes(outfit.name)) {- Checks whether 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