January 20, 2008

Parsing Commands

This is a topic I thought about for a long time. My family thought I was just slacking about like a bum but I was really thinking. The challenge is converting what the player types into function calls -- only some function calls need more information than others and in differing order. I started with a huge, ugly IF-THEN sequence but quickly hated it. Plus, it wasn't very clean to expand.

I knew I wanted a dictionary lookup that would map verbs to functions and I wanted flexible control over which verbs different players could use -- 'equip sword' vs. 'cast fireball at Chadu'. The only common theme is every command begins with a verb.

I think my solution is both elegant and functional. I changed the dictionary to map verbs to functions and parsers. So the verb "tell" uses parser.dialogue (extract the recipient and the message) and "shout" uses parser.monoloque (no target, everything is the message).

Here's a snippet of where the Player class processes a line of input:
cmd = self.get_cmd()
verb, words = split_verb(cmd)

if self.has_ability(verb):
parser, function = shared.ABILITY_DICT[verb]
args = parser(words)
function(self, *args)


Notice the call to self.has_ability? We can grant and revoke abilities easily.

No comments: