Java Reference
In-Depth Information
validCommands.put("help", CommandWord.HELP);
validCommands.put("quit", CommandWord.QUIT);
}
The command typed by a user can now easily be converted to its corresponding enumerated
type value.
Exercise 6.34 Review the source code of the zuul-with-enums-v1 project to see how it
uses the CommandWord type. The classes Command , CommandWords , Game , and Parser
have all been adapted from the zuul-better version to accommodate this change. Check that
the program still works as you would expect.
Exercise 6.35 Add a look command to the game, along the lines described in
Section 6.9.
Exercise 6.36 “Translate” the game to use different command words for the GO and
QUIT commands. These could be from a real language or just made-up words. Do you only
have to edit the CommandWords class to make this change work? What is the significance
of this?
Exercise 6.37 Change the word associated with the HELP command and check that it
works correctly. After you have made your changes, what do you notice about the welcome
message that is printed when the game starts?
Exercise 6.38 In a new project, define your own enumerated type called Position with
values TOP , MIDDLE , and BOTTOM .
6.13.2
Further decoupling of the command interface
The enumerated CommandWord type has allowed us to make a significant decoupling of the
user interface language from the game logic, and it is almost completely possible to translate
the commands into another language just by editing the CommandWords class. (At some stage,
we should also translate the room descriptions and other output strings, probably by reading
them from a file, but we shall leave this until later.) There is one further piece of decoupling
of the command words that we would like to perform. Currently, whenever a new command is
introduced into the game, we must add a new value to the CommandWord and an association
between that value and the user's text in the CommandWords classes. It would be helpful if we
could make the CommandWord type self-contained—in effect, move the text:value association
from CommandWords to CommandWord .
Java allows enumerated type definitions to contain much more than a list of the type's values.
We will not explore this feature in much detail but just give you a flavor of what is possible.
Code 6.10 shows an enhanced CommandWord type that looks quite similar to an ordinary class
definition. This can be found in the zuul-with-enums-v2 project.
 
Search WWH ::




Custom Search