Java Reference
In-Depth Information
Code 6.3
continued
Source code of the
(badly designed)
Room
class
/**
* Define the exits of this room. Every direction either
* leads to another room or is null (no exit there).
*/
public
void
setExits(Room north, Room east, Room south,
Room west)
{
if
(north !=
null
) {
northExit = north;
}
if
(east !=
null
) {
eastExit = east;
}
if
(south !=
null
) {
southExit = south;
}
if
(west !=
null
) {
westExit = west;
}
}
/**
* Return the description of the room (the one that was
* defined in the constructor).
*/
public
String getDescription()
{
return
description;
}
}
It is a bit more work to find all relevant places in the
Game
class. The source code is somewhat
longer (it is not fully shown here), and finding all the relevant places takes some patience and care.
Reading the code shown in Code 6.1, we can see that the
Game
class makes heavy use of the
exit information of a room. The
Game
object holds a reference to one room in the
current-
Room
variable and frequently accesses this room's exit information.
■
In the
createRoom
method, the exits are defined.
■
In the
printWelcome
method, the current room's exits are printed out so that the player
knows where to go when the game starts.
■
In the
goRoom
method, the exits are used to find the next room. They are then used again to
print out the exits of the next room we have just entered.
If we now want to add two new exit directions, we will have to add the
up
and
down
options in
all these places. However, read the following section before you do this.
Search WWH ::
Custom Search