Question

I want to code a simple command that could take 3 arguments for a text adventure game.

Basically at the prompt, I would type 'use key unlock door' and it would run a particular block.

Here is what I coded but it does not work:

def do_use(self, tool, action, object):

    if tool == 'key':
        if action == 'unlock':
            if object == 'door':
                print("seems like it works!")
            else:
                print("nope 1")
        else:
            print("nope 2")
    else:
        print("nope 3")     

Notes: the rest of the commands work fine. I imported cmd and the following is the main code:

class Game(cmd.Cmd):

    def __init__(self):
        cmd.Cmd.__init__(self)

    ....


    if __name__ == "__main__":
        g = Game()
        g.cmdloop()

At the prompt, when I type:

>>> use key unlock door

I get the following error message:

TypeError: do_use() takes exactly 4 arguments (2 given)

The code would work if it would print:

seems like it works!

Any help will be appreciated.

Was it helpful?

Solution

Reading that documentation, it looks like all of the commands just take in a single string, and you have to parse the string yourself. Your command is defined as taking 4 arguments (including self), and cmd is calling it with self, input, which is 2. I think could get the result you want with the following:

def do_use(self, user_input):
    args = user_input.split()
    if len(args) != 3:
        print "*** invalid number of arguments"
    else:
        tool, action, obj = args
 # Do the rest of your code here
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top