Game Development Reference
In-Depth Information
We want to be able to save a game, as shown in Listing 3-12, so that we can retrieve it between
interruptions.
Listing 3-12. Saving Game
ns.Storage = function() {
var gameKey = 'chessdemo_game';
return {
saveGame: function(game) {
localStorage.setItem(gameKey, JSON.stringify(game));
},
retrieveGame: function() {
return JSON.parse(localStorage.getItem(gameKey));
},
emptyGame: function() {
localStorage.removeItem(gameKey);
}
}
}();
Implementing our controller
Let's implement the actions of the controller made previously. You will see the entry point of the game
initialization in these actions. We are going to use all classes defined before, as shown in Listing 3-13.
Listing 3-13. Insert Listing Caption Here.
// ...
continueGame: function(){
if(!ns.currentGame && ns.Storage.hasGameSaved()) {
ns.currentGame = new ns.Game( ns.Storage.retrieveGame() );
}
return this.game();
},
newGame: function(){
ns.Storage.emptyGame();
ns.currentGame = null;
return this.game();
},
game: function(){
var renderer = new ns.Renderer();
if(!ns.currentGame)
ns.currentGame = new ns.Game().init();
var game = ns.currentGame;
renderer.init(game);
game.bindChange(function(){
ns.Storage.saveGame( game.export() );
if( game.isFinished() ) {
alert("CheckMate!"); // TODO: render a finish page instead
ns.currentGame = null;
history.back();
}
})
scene('game');
}, // ...
 
Search WWH ::




Custom Search