Question

pretty new to this and second question tonight, but I'm working on a text-based adventure game. Throughout it I'm using functions for certain commands, and there are different stages to it but I need one function to be available throughout the entire game. the "help" command. I can only think of one way this could be done which would be to add to EVERY if elif statement a line saying.

if option == 'help':
    help()

also need a way to display inventory the same way, which will be a dict

but I'd prefer an easier way if anyone knows one.

Was it helpful?

Solution

Typically, you'd put something like that in a separate file and import it whenever you needed it. Here's how your project directory structure might look:

# /home/your_user_name/PROJECT_DIR
# PROJECT_DIR/setup.py
# PROJECT_DIR/README.md
# PROJECT_DIR/your_app
# PROJECT_DIR/your_app/__init__.py # mark this folder as a python package named your_app
# PROJECT_DIR/your_app/main.py # your main codes
# PROJECT_DIR/your_app/utils.py # put stuff like help in here

So in utils.py:

def help():
    ret = "calculating stuff to return"
    return ret

And in main.py:

from your_app import utils
def run():
    if option == 'help':
        utils.help()
if __name__ == "__main__":
    run()

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top