timeless actions (a roguelike in Python, #12)

One last important thing I needed to add to command handling was commands that take no time — certain out-of-game actions or meta commands like switching UI views and things like that. I’m imagining that most commands will take a player’s turn but I wanted to have support for actions that don’t.

At the same time I wanted to centralize command parsing — before commands were enacted by calling the command directly which was OK but made it tedious to add things that would happen when any command was called. So here’s what I came up with — some significant changes to the Command class:

class Command(object):
    def __init__(self): 
        self.playbook = {
                        'north' : ('takes turn', self.move, 0, -1),
                        'east'  : ('takes turn', self.move, 1, 0),
                        'south' : ('takes turn', self.move, 0, 1),
                        'west'  : ('takes turn', self.move, -1, 0),
                        'ctrl north'    : ('takes turn', self.ctrl, 0, -1),
                        'ctrl east'     : ('takes turn', self.ctrl, 1, 0),
                        'ctrl south'    : ('takes turn', self.ctrl, 0, 1),
                        'ctrl west'     : ('takes turn', self.ctrl, -1, 0),
                        'print history' : ('free action', self.print_history, None)}

And now commands are routed through a single function:

    
    def do(self, string, enactor):
        command = self.playbook[string]
        command_name, args = command[1], command[2:]
        command_name(enactor, *args)
        self.history.append((string, enactor.name))
        return command[0]
 

Which gets called like this in the player input function:

        command_name = self.ctrl + self.keycfg[key]
        game.message.text = "Go!"

        if game.command.do(command_name, player.thing) == 'free action':
            self.gameplay_update()

So the command_name is created, for example ‘ctrl north’, and is sent to command.do. That gets looked up in the playbook, and the command is called with its arguments. The lookup also tells the game if the action takes a turn or not — this information is returned to the original call, and if it’s a free action the player input function is called again without a turn passing.

The ‘history’ is mostly a way to test this out. I have a vague idea of allowing playback of moves, but that’s going to require a lot of other work that’s not a priority right now.

Advertisements

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: