Game Development Reference
In-Depth Information
window.localStorage , the value is retained over different sessions. The latter is a very useful option.
For example, you can do the following:
window.localStorage.playerName = "Bridget";
The next time you start the game, you can read the value of the variable and surprise (or freak out)
the player by remembering her name. However, there are some strings attached to using local
storage. First, it's very easy to accidentally clear the localStorage variable, because it's accessible
to any JavaScript program. Also, the user can do this explicitly from the browser menu, so your
program should never rely on data that is stored in this fashion without a backup or default value for
the data. Modern browsers typically disable the usage of local storage when they operate in private
mode. If your game relies heavily on local storage, and it's disabled, it might be a good idea to notify
the player in some way.
Another limitation is that you can only store strings as values in local storage. That means any
complex data you want to store must be converted to a string value. When you read the data, you
need to parse the string and convert the data back. Because the windows.LEVELS variable contains
all the level data, including the locked/solved status of each level, you want to convert this object to
a string and store it in local storage in its entirety. The question is, how do you convert a complex
variable like that to a string and back again?
Again, JavaScript comes to the rescue! A really great feature of the language is that JavaScript
allows for seamless conversion to and from strings of object literals such as windows.LEVELS . This is
done using the JSON object. JavaScript Object Notation (JSON) is an open standard for representing
structured objects as strings, much like XML. JavaScript has a few useful methods for automatically
converting an object literal to such a string and back. For example, to store all the level data as a
JSON string in local storage, you only need the following line of code:
localStorage.penguinPairsLevels = JSON.stringify(window.LEVELS);
Going from a JSON string to an object literal is just as easy:
window.LEVELS = JSON.parse(localStorage.penguinPairsLevels);
In the Level class, you add two methods, loadLevelsStatus and writeLevelsStatus , that read and
write the level information from and to the local storage. You add a few checks in these methods
to make sure local storage is actually available (which it only is in newer browsers). Here are both
method definitions:
PlayingState.prototype.loadLevelsStatus = function () {
if (localStorage && localStorage.penguinPairsLevels) {
window.LEVELS = JSON.parse(localStorage.penguinPairsLevels);
}
};
PlayingState.prototype.writeLevelsStatus = function () {
if (!localStorage)
return;
localStorage.penguinPairsLevels = JSON.stringify(window.LEVELS);
};
 
Search WWH ::




Custom Search