Book Image

HTML5 Game Development Hotshot

By : Seng Hin Mak, Makzan Makzan (Mak Seng Hin)
Book Image

HTML5 Game Development Hotshot

By: Seng Hin Mak, Makzan Makzan (Mak Seng Hin)

Overview of this book

Table of Contents (15 chapters)
HTML5 Game Development HOTSHOT
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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']) {
      game.buildingsList = JSON.parse(localStorage['city.buildinglist']);
    } else {
      game.buildingsList = [];
    }
  4. When we initialize coins and diamonds, we load the values from the local storage:

    game.coins = localStorage...