HTML and CSS Reference
In-Depth Information
var loseGame = function() {
Game.setBoard(3,new TitleScreen("You lose!",
"Press fire to play again",
playGame));
}
Adding the level becomes as trivial as adding a new Level sprite to the board and passing in the level data
level1 and the success callback winGame .
The winGame method just reuses the TitleScreen object to show a success message and a message let-
ting the player know they can replay the game.
The loseGame method works the same way as the winGame method but with a less congratulatory mes-
sage. Lose game so far isn't called yet anywhere, but this can be remedied by adding a custom hit method to
the PlayShip object. Add the following definition to game.js under the rest of the PlayerShip methods
(make sure to add it underneath where the prototype is set):
PlayerShip.prototype.hit = function(damage) {
if(this.board.remove(this)) {
loseGame();
}
}
The PlayerShip doesn't get an explosion when it dies; this is just for simplicity's sake. However, you
could add one in and add a callback to the end of the explosion step to show the loseGame screen only after
the PlayerShip has finished blowing up.
Implementing the Level Object
All that's left now is the implementation of the Level object. This object's duties have already been defined
by how the level data and playGame and winGame methods were set up. The Level object has only two
methods: the constructor function, which makes a copy of the level data for its own use (and modification) and
the step method, which loops through the level data and adds enemies onto the board as necessary.
Add the constructor function shown in Listing 2-14 to the bottom of engine.js .
Listing 2-14: Level Object Constructor
var Level = function(levelData,callback) {
this.levelData = [];
for(var i =0; i<levelData.length; i++) {
this.levelData.push(Object.create(levelData[i]));
}
this.t = 0;
this.callback = callback;
}
The one major responsibility of the constructor function is to make a deep copy of the passed-in level data.
Cloning the data is necessary because the method is going to modify the level data as the level progresses. Be-
cause objects are passed by reference in JavaScript, this would prevent the level from being reused if the player
were to play the level a second time.
 
 
 
Search WWH ::




Custom Search