3

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!

Community
  • 1
  • 1

1 Answers1

6

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]()
Zev Averbach
  • 1,044
  • 1
  • 11
  • 25
James K
  • 3,692
  • 1
  • 28
  • 36
  • Perfect! Thank you! – Historic 66 Aug 21 '16 at 19:25
  • As a side note, you can also pass functions into other functions this way, by using their name without the brackets to call them. – Jeff Aug 21 '16 at 19:56
  • The text is wrong. The dictionary values aren't the names of the functions, they **are** the functions. – Stefan Pochmann Aug 21 '16 at 20:12
  • It was working fine when I tested it (created a new file to do so) but when I try to run my characterCreation script, I get the following error: "name 'inventory' is not defined" referring to my "inventory" function. Any thoughts? Should I post the code as an answer? – Historic 66 Aug 22 '16 at 22:06
  • Create a [minimal complete working example](http://stackoverflow.com/help/mcve) That is a script that is a concise as possible but still shows the problem. – James K Aug 22 '16 at 22:16