Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant command-parsing in an OOP-based text game

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.

like image 823
Shadowfirebird Avatar asked Feb 05 '10 12:02

Shadowfirebird


2 Answers

The Interpreter design pattern is the most object-oriented approach to parsing that I'm aware of, but I'm sure compiler experts will point out algorithms that are more powerful.

like image 115
Mark Seemann Avatar answered Oct 31 '22 13:10

Mark Seemann


Sounds like you need a parser.

Split the input string into tokens (words). Then feed the tokens, one at a time, to a state machine. I find that the push-down automata is rather intuitive and powerful way to write such an stm.

like image 39
troelskn Avatar answered Oct 31 '22 13:10

troelskn