View Single Post
  #2 (permalink)  
Old 07-31-2007, 10:51 PM
brianhks brianhks is offline
Senior Member
 
Join Date: Jul 2007
Posts: 134
brianhks will become famous soon enough
OK If I understand correctly, in your game if I typed "kill" you want it to match up with a class that handles the "kill" command and then runs some method on that class to perform the operation right?

This is how I would do it. Create a file of commands and the class name ex.
kill=KillClass
run=RunClass
...

I would make all command classes implement an interface or inherit from a common base class. For my example I'll call it the Command interface.

Then in the startup read the file and load the commands into a Map<String, Command>. You can do this by reading each line and splitting it on the '='. The left side is the key in the map and the right you use to instantiate the class like so:
Code:
Map<String, Command> commandMap = new HashMap<String, Command>(); Class commandClass = this.getClass().getClassLoader().loadClass(rightSideClassName); Command com = (Command)commandClass.newInstance(); commandMap.put(commandKey, com);
Then when they type in a command just look it up in the map, pull out the Command class and call the method.
Reply With Quote