Using local storage to save game progress

Viewed 927

I'm creating a clicker browser game, and want to be able to save progress. I know about how to use local storage, but I'm wondering what the best methods for storing different objects, variables, and elements if they’ve been created.

I know how to use local storage, but what I’m trying to figure out is if there is a better way then just saying setItem for every single thing? And, then how would I deal with doing it with objects vs variables?

I was looking at the game a dark room’s GitHub to see how it was one there. I haven’t worked with jquery at all, but it seems like there is very little code to save info, and I don’t quite understand how it does it.

I’m trying to improve as a programmer, and instead of going through and “brute forcing” it, with lots of code, I’m trying to find better ways to write it-make it more efficient and not write the same function repeatedly.

I don’t have a snippet as it’s a lot of code, not looking for you to write the code obviously, just looking for methods of saving these different types of data better! Any help would be appreciated, thank you!

2 Answers

You can save your current gameState in an object, then use JSON.stringify to store it in the localStorage. Then when you want to load it again you use JSON.parse to make it an object again and there you get all your values out of.

const saveState = {
  level: 5,
  charName: 'John Doe',
  age: 10,
  wealth: {
    money: 5,
    debt: -4
  },
  inventory: ['shovel', 'stick', 'fish']
};

const saveStateString = JSON.stringify(saveState);
localStorage.setItem('saveState', saveStateString);

const loadSaveStateString = localStorage.getItem('saveState');
const loadSaveState = JSON.parse(loadSaveStateString);

Note: localstorage is disabled on so, in browser it works fine

saveGame = function(id){
    let file = {
        score: 110,
        palyer: 'player1'
        
        // ...
    };
    localStorage.setItem(`saveGame${id}`,JSON.stringify(file));
};

loadGame = function(id){
    var file = JSON.parse(localStorage.getItem('saveGame22'));
    let score = file.score;
    let player = file.player;
     
    // ...
};
Related