On Tue, 05 May 2009 16:52:39 +0100, George Oliver <georgeolive...@gmail.com> wrote:

hi, I'm a Python beginner with a basic question. I'm writing a game
where I have keyboard input handling defined in one class, and command
execution defined in another class. The keyboard handler class
contains a dictionary that maps a key to a command string (like 'h':
'left') and the command handler class contains functions that do the
commands (like def do_right(self):),

I create instances of these classes in a list attached to a third,
'brain' class. What I'd like to have happen is when the player presses
a key, the command string is passed to the command handler, which runs
the function. However I can't figure out a good way to make this
happen.

I've tried a dictionary mapping command strings to functions in the
command handler class, but those dictionary values are evaluated just
once when the class is instantiated. I can create a dictionary in a
separate function in the command handler (like a do_command function)
but creating what could be a big dictionary for each input seems kind
of silly (unless I'm misunderstanding something there).

Taking a wild guess when you were creating that dictionary mapping
command strings to functions, did you map to function calls or to the
function objects themselves?  I'd make a small wager you did the former,
and the latter would have done what you want.  Something like this,
maybe?

CODE FOLLOWS<<<<

class DoSomething(object):
    def do_this(self):
        print "Doing this"

    def do_that(self):
        print "Doing that"

    def do_the_other(self):
        print "Doing the other"

    _CMD_DICT = { 'this' : do_this,
                  'that' : do_that,
                  'the other' : do_the_other }

    def update(self, cmd):
        try:
            DoSomething._CMD_DICT[cmd](self)
        except KeyError:
            print "Foul!  Foul, I say!"

END CODE<<<<

To be honest, the getattr approach is probably as easy to follow
and less prone to forgetting to update the dictionary.


--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to