Game Development Reference
In-Depth Information
else
return
(b + Product(a
−
1, b));
}
The key here is that the recursive method should have a
termination condition
some-
where, so that in some cases, the method does not call itself but does something else.
In this example, the termination condition is
a==0
. In that case, the method does
not call itself, but it simply returns 0 (which is correct, since any number multiplied
by 0 results in 0).
16.2.5 Finding the Game World
Although we can look for a game object with a particular ID in a
GameObjectList
in-
stance, we are going to need access to the object representing the game world. The
variable that refers to this object is declared in the
JewelJam
class, and there is no
real easy way to access it. One way to solve it would be to use the same approach
as we did in the
Painter
game: make the game world a static member variable and
add a property, so the expression
JewelJam.GameWorld
would yield the game world.
However, this is not an ideal solution for several reasons. As we have said before,
it is better to avoid static variables when possible. A variable should only be static
when you are sure that there will only ever be a single meaningful instance belong-
ing to the class that contains the member variable. Although we only have a single
game world in both the
Painter
and
JewelJam
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 is wise to al-
ready prepare ourselves so that the classes that we write will also be useful in these
cases. A second problem with accessing the game world as a static variable from the
JewelJam
class is that all the game objects now use a game-specific class (
JewelJam
)
to access the game world. If we would like to use our game object classes in another
game, we would have to go through the code and replace all the calls to the
JewelJam
class with calls to the class specific for that game.
Clearly, we need a better solution to get access to the game world that is useful
across different games. In order to do that, we are going to rely on the parent-child
relationship that is encoded into the generic
GameObject
class. For each game object,
we can assume that if we get to the root of the hierarchy that the game object belongs
to, that this root is the game world. Therefore, we can easily retrieve the game world
by walking through the list of parents to get to the root. We add a property called
Root
to the
GameObject
class that does exactly this, and it relies on recursion:
public
GameObject Root
{
get
{
if
(parent !=
null
)