Java Reference
In-Depth Information
Some items cannot be picked up.
The player can drop items in the current room.
To achieve these goals, we can do the following:
If not already done, we add a class Item to the project. An item has, as discussed above, a
description (a string) and a weight (an integer).
We should also add a field name to the Item class. This will allow us to refer to the item
with a name shorter than that of the description. If, for instance, there is a book in the current
room, the field values of this item might be:
name: book
description: an old, dusty book bound in gray leather
weight: 1200
If we enter a room, we can print out the item's description to tell the player what is there. But
for commands, the name will be easier to use. For instance, the player might then type take
book to pick up the topic.
We can ensure that some items cannot be picked up, by just making them very heavy (more
than a player can carry). Or should we have another boolean field canBePickedUp ?
Which do you think is the better design? Does it matter? Try answering this by thinking
about what future changes might be made to the game.
We add commands take and drop to pick up and drop items. Both commands have an item
name as a second word.
Somewhere we have to add a field (holding some form of collection) to store the items cur-
rently carried by the player. We also have to add a field with the maximum weight the player
can carry, so that we can check it each time we try to pick up something. Where should these
go? Once again, think about future extensions to help you make the decision.
This last task is what we will discuss in more detail now, in order to illustrate the process of
refactoring.
The first question to ask ourselves when thinking about how to enable players to carry items
is: Where should we add the fields for the currently carried items and the maximum weight? A
quick look over the existing classes shows that the Game class is really the only place where it
can be fitted in. It cannot be stored in Room , Item , or Command , because there are many differ-
ent instances of these classes over time, which are not all always accessible. It does not make
sense in Parser or CommandWords either.
Reinforcing the decision to place these changes in the Game class is the fact that it already
stores the current room (information about where the player is right now), so adding the current
items (information about what the player has) seems to fit with this quite well.
This approach could be made to work. It is, however, not a solution that is well designed. The
Game class is fairly big already, and there is a good argument that it contains too much as it is.
Adding even more does not make this better.
We should ask ourselves again which class or object this information should belong to.
Thinking carefully about the type of information we are adding here (carried items, maximum
 
Search WWH ::




Custom Search