Game Development Reference
In-Depth Information
which is either null or a game object) are sent back through the return values. Finally, the first caller
of the method gets the object (if it was found somewhere in the tree), or null if no object carrying the
requested ID was found. This kind of search strategy is also called depth first , because you call the
find method on the child object before examining the rest of the objects in the list.
When a method calls itself, this is called recursion . Recursion is a very powerful tool, because it
allows you to perform these kinds of complicated search algorithms without having to write a lot
of code. However, watch out with recursion, because you could end up writing a method that calls
itself indefinitely. Suppose you want to use recursion to compute the product of two (positive)
integers by adding them up:
function product(a, b) {
return b + product(a-1, b);
}
This code doesn't check that the product should return 0 if a equals zero. So, the method calls itself
indefinitely, resulting in an endless loop, similar to what can happen if you forget to increment the
counter in the while instruction. The correct version of this recursive method is, of course
function product(a, b) {
if (a === 0)
return 0;
else
return b + product(a-1, b);
}
The key is that the recursive method should have a termination condition somewhere, so that in
some cases, the method doesn't call itself but does something else. In this example, the termination
condition is a === 0 . If that happens, the method doesn't call itself, but returns 0 (which is correct,
because any number multiplied by 0 results in 0).
Accessing the Game World
Although you can look for a game object with a particular ID in a GameObjectList instance, you need
access to the object representing the game world. The variable that refers to this object is a member
variable of the Game class. So, whenever you want to look for a particular object, you can call the
find method on the Game.gameWorld object, because that object also inherits from GameObjectList .
Although you only have a single game world in both the Painter and Jewel Jam games, this is
certainly not the case for more complicated games. Each level in a game could be a separate game
world. Even a single level could contain several different game worlds. So, it's wise to prepare
yourself so the classes you write will also be useful in these cases.
In order to do this, you rely on the parent-child relationship that is encoded into the generic
GameObject class. For each game object, you can assume that if you get to the root of the hierarchy
that the game object belongs to, this root is the game world of that particular game object.
 
Search WWH ::




Custom Search