Game Development Reference
In-Depth Information
Creating the Player Data
The final data object is PlayerData , which is used to reference the data saved in local storage and is set to the property
player . Listing 14-8 shows the entire PlayerData object.
Listing 14-8. data.js - The PlayerData Object Retrieves and Stores Player Data from Local Storage
PlayerData = {
player:null,
dataTemplate:{
board:1,
level:1,
maxHP:10,
power:5,
defense:1,
coins:3,
attack:-1,
fire:1,
earth:0,
lightning:0,
potion:1,
gameLevel:1
},
getData:function () {
if (localStorage.gameLevel) {
this.player = localStorage;
}
else {
this.player = this.setLocalStorage();
}
},
setLocalStorage:function () {
for (var key in this.dataTemplate) {
localStorage.setItem(key, this.dataTemplate[key]);
}
return localStorage;
}
}
The getData method is called before the main application class is created, within the index.html file. This is to
assure that the data from local storage is either loaded or created if the values have not yet been set. This can be done
by checking if the gameLevel property has been set in local storage.
if (localStorage.gameLevel) {
this.player = localStorage;
}
If this property does exist in local storage, then you know there has been data previously saved, so it is assigned to
the player property. This will be the access point to local storage when getting and saving values during gameplay.
var coins = data.PlayerData.player.coins; //10
coins += 3; //coins updated to 13 and saved to local storage
 
Search WWH ::




Custom Search