import java.util.HashMap;
/**
* Representations for all the valid command words for the game
* along with a string in a particular language.
*
* ---------------------------------------------------------------------------
* The CommandWords class was merged with this one since there is really no
* point to haveing them separate. There are many reasons to have the
* reverse-lookup implemented within the enum, and that was really all the
* CommandWords class was doing.
* ---------------------------------------------------------------------------
*
* @author Michael Kolling and David J. Barnes
* @version 2006.03.30
*
* @author Modified by Charles Cusack, October 2008.
*
*/
public enum CommandWord
{
// A value for each command word along with its
// corresponding user interface string.
GO("go"), QUIT("quit"), HELP("help"), UNKNOWN("?");
// The command string.
private String commandString;
/**
* Initialise with the corresponding command word.
* @param commandWord The command string.
*/
private CommandWord(String commandString)
{
this.commandString = commandString;
}
/**
* @return The command word as a string.
*/
public String toString()
{
return commandString;
}
// The following code, taken from CommandWords, allows for
// reverse lookup.
//
// A mapping between a command word and the CommandWord
// associated with it.
private static HashMap<String, CommandWord> validCommands;
// This static block is executed once--it fills the HashMap
static {
validCommands = new HashMap<String, CommandWord>();
for(CommandWord command : CommandWord.values()) {
if(command != CommandWord.UNKNOWN) {
validCommands.put(command.toString(), command);
}
}
}
/**
* Find the CommandWord associated with a command word.
* @param commandWord The word to look up.
* @return The CommandWord correspondng to commandWord, or UNKNOWN
* if it is not a valid command word.
*/
public static CommandWord getCommandWord(String commandWord)
{
CommandWord command = validCommands.get(commandWord);
if(command != null) {
return command;
} else {
return CommandWord.UNKNOWN;
}
}
/**
* Returns a String representation of all valid commands.
*/
public static String getAllCommandWords()
{
StringBuilder sb = new StringBuilder("");
for(String command : validCommands.keySet()) {
sb.append(command + " ");
}
return sb.toString();
}
/**
* Check whether a given String is a valid command word.
* @return true if it is, false if it isn't.
*/
public boolean isCommand(String aString)
{
return validCommands.containsKey(aString);
}
}