Episode 14: Saving & Loading

Hopefully this episode is short, because all I’m going to talk about is saving and loading player data.

Web Storage

As I mentioned, I used JavaScript to write this game, and it turns out that modern browsers support a feature called Web Storage, which lets you save small chunks of data on the user’s computer. Here’s how saving works:

And loading:

I love it when things are simple and easy to use.

The next step was to organize these functions in a factory, as I’ve done with all my other code. I ended up with these functions:

  • new
  • load
  • save
  • reset

I later realized that I didn’t need reset, because it’s just a combination of new and save.

Anyway, once I had the factory working, I just set up the calls to the the appropriate functions during gameplay (mostly from the menu).

One tricky thing is keeping track of the data you are saving and loading. After all, you may want to store a bunch of different things, and you may want to save or load each of them separately. Here are some of the things that I store:

  • Progress
  • Items
  • Money
  • Custom missions
  • Settings

Potential Problems

One choice I made that was probably a mistake was to store the player’s data in a global variable. I probably should have written functions in the storage factory that gave access to this data. Perhaps I’ll change it in the future.

Another problem I’m anticipating is that game data may become corrupted as I make changes to the game. I imagine a good solution would be to add a version name to the local storage key (like Zyrian 0.41), so that any player who accesses an updated version of the game starts with new data.

This could end up aggravating players who lose their data, so it would probably be smart to write some code that checks if the existing Web Storage data is compliant with the current version of the game. Now you can see why I haven’t done this yet.

Leave a Reply