Historic 66
Historic 66

Reputation: 37

Calling a function, stored as a value in a dictionary, if the user's input matches the value's key

I'm currently creating a simple interactive fiction (IF) game in Python. In addition to the commands relevant to each room they explore, I would like for the player to have access to a list of "global commands" that can be called at anytime (inventory, help, etc).

I used this thread to get started, but I don't think it's quite what I'm looking for.

Essentially, what I want is something like this (obviously, not all of this is valid code):

def inventory():
    # Shows the user's inventory

def game_help():
    # shows a list of available commands

global_commands = {
    'inventory': inventory(),
    'help': game_help(),
}

command = raw_input().downcase()
if command == "get item":
     print "You take the item"
elif command == "open door":
     print "You open the door"
elif command in global_commands:
     # execute the function that is tied to the user's input

Any and all help is appreciated!

Upvotes: 3

Views: 140

Answers (1)

James K
James K

Reputation: 3752

Make the values in the global_commands dictionary the functions. Don't include parentheses as you don't want to call them yet.

global_commands = {
    'inventory': inventory,
    'help': game_help,
}

Then look up the command in the dictionary and execute the corresponding function:

elif command in global_commands:
    global_commands[command]()

Upvotes: 6

Related Questions