Alex Rivera | Logout

Elegant command-parsing in an OOP-based text game

Asked 2010-02-05T12:37:18.197
9

I'm playing with writing a MUD/text adventure (please don't laugh) in Ruby. Can anyone give me any pointers towards an elegant, oop-based solution to parsing input text?

We're talking about nothing more complex than "put wand on table", here. But everything needs to be soft; I want to extend the command set painlessly, later.

My current thoughts, slightly simplified:

  1. Each item class (box, table, room, player) knows how to recognise a command that 'belongs' to it.

  2. The game class understands a sort of a domain-specific language involving actions such as "move object X inside object Y", "show description of object X", etc.

  3. The game class asks each item in the room if it recognises the input command. First to say yes wins.

  4. It then passes control to a method in the item class that handles the command. This method rephrases the command in the DSL, passes it back to the game object to make it happen.

There must be well-worn, elegant ways of doing this stuff. Can't seem to google anything, though.

Edit
Report

1 Answer

1

For command interpreters, I'm rather fond of this simple, not all that elegant pattern. Patterns in dynamic languages tend to involve fewer boxes and lines than GOF patterns.

class Thing

  # Handle a command by calling the method "cmd_" + command.
  # Raise BadCommand exception if there is no method for that command.

  def handle_command(command, args)
    method_name = "cmd_#{command}"
    raise BadCommand, command unless respond_to?(method_name)
    send(method_name, args)
  end

  def cmd_quit(args)
    # the code for command "quit"
  end

  def cmd_list(args)
    # the code for command "list"
  end

  ...

end

In this way, adding a new command is just adding a new method. No tables or case statements need to be adjusted.

answered 2010-02-05T12:54:11.363

Your Answer