HTML and CSS Reference
In-Depth Information
with code that is easy to work with. It may take a little bit more work on the implementation, but you'll be hap-
pier in the long run.
One initial impulse you might have would be to encode the starting location of each enemy and each enemy
type in an array. Because a level might have a hundred or more enemies, this would get laborious quickly. A
better option is to encode each string of enemies as a single entry with a start time, end time, and per-enemy
delay. This way each string of enemies is succinctly encoded into the level data, and you can take one look at
the definition and get a good understanding of what's going on.
Listing 2-12:
Level Data
var level1 = [
// Start, End, Gap, Type, Override
[ 0, 4000, 500, 'step' ],
[ 6000, 13000, 800, 'ltr' ],
[ 12000, 16000, 400, 'circle' ],
[ 18200, 20000, 500, 'straight', { x: 150 } ],
[ 18200, 20000, 500, 'straight', { x: 100 } ],
[ 18400, 20000, 500, 'straight', { x: 200 } ],
[ 22000, 25000, 400, 'wiggle', { x: 300 }],
[ 22000, 25000, 400, 'wiggle', { x: 200 }]
];
Each line gives a start time in milliseconds, an end time in milliseconds, and a gap in milliseconds between
each enemy followed by the enemy type and any override parameters.
Loading and Finishing a Level
Defining how the
level
class is going to consume level data is half the battle; the other half is deciding on
how the
Level
object will be used by the
PlayGame
method to start the game. The easiest solution is to
simply create another sprite-like object that is added to the game board and spawns enemies at the correct time
intervals. When the
Level
is out of enemies, it can make a callback to indicate success.
Again working backward, you write the way the
Level
object should be used before tackling the actual
implementation. Replace the existing
playGame
method with the one shown in
Listing 2-13
, and add new
winGame
and
loseGame
methods as well.
Listing 2-13:
Modified Game Initialization Methods
var playGame = function() {
var board = new GameBoard();
board.add(new PlayerShip());
board.add(new Level(level1,winGame));
Game.setBoard(3,board);
}
var winGame = function() {
Game.setBoard(3,new TitleScreen("You win!",
"Press fire to play again",
playGame));
}