Game Development Reference
In-Depth Information
// calculate cloud position and velocity
// ...
this.add(cloud);
}
}
Look closely at the loop: you're removing and adding objects to a list while traversing it with a for
instruction. This can be dangerous, because you modify the length of the list in the body of the for
instruction, and the value of i depends on the length of the list. If you aren't careful, you could run
into a case where you remove an item from the list you're traversing, but i is still incremented until
it reaches the old length of the list, resulting in an error when you try to access the list outside of its
bounds. In this particular case, you won't run into trouble because whenever you remove a cloud, you
add a new one; but you have to be very careful when programming these kinds of operations. One
way to be sure the program runs correctly in all cases is to simply break out of the loop using either a
break or a return call. This way, as soon as you modify the list in some way, you stop the loop.
Finalizing the Level Progression
To complete the game, you still need to add the game states for dealing with the event that the
player has lost or won a level. You approach this in a fashion similar to how you handled it in the
Penguin Pairs game, except that here you have an explicit “game over” game state in addition to the
“level finished” game state. These states are coded in a fairly straightforward way, similar to how you
did it in previous games. You can find the complete code in the GameOverState and LevelFinished
state classes in the TickTickFinal example belonging to this chapter.
To determine whether the player has finished a level, you add a completed property to the Level
class that checks for two things:
Has the player collected all the water drops?
Has the player reached the exit sign?
Both of these things are fairly easy to check. To check whether the player has reached the end
sign, you can see whether their bounding boxes are intersecting. Checking whether the player has
collected all the water drops can be done by verifying that all water drops are invisible. This is the
complete property:
Object.defineProperty(Level.prototype, "completed",
{
get: function () {
var player = this.find(ID.player);
var exit = this.find(ID.exit);
if (!exit.collidesWith(player))
return false;
for (var i = 0, l = this._waterdrops.length; i < l; ++i) {
if (this._waterdrops.at(i).visible)
return false;
}
return true;
}
});
 
Search WWH ::




Custom Search