O'Reilly logo

HTML5 Game Development HOTSHOT by Makzan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Saving and loading the game progress

In the task, we store the game progress locally. When a player loads the game, we use the world time to calculate the building construction.

Engage thrusters

We will use the following steps to store game parameters and load them at the initial stage:

  1. Create the saving function with the following code:
    game.autoSave = function() {
      if (cjs.Ticker.getTicks() % 100 === 0) {
        localStorage['city.coins'] = game.coins;
        localStorage['city.diamonds'] = game.diamonds;
        localStorage['city.buildinglist'] = JSON.stringify(game.buildingsList);
      }
    };
  2. Add the saving function to the ticker so that it can autosave:
    cjs.Ticker.addEventListener('tick', game.autoSave);
  3. Now, we can load the saved game using the following code:
    if (localStorage['city.buildinglist']) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required