user3056783 user3056783 - 4 years ago 188
Python Question

Python text adventure - how to create HINT and SAVE in every prompt

So, finally I'm getting to the end of LPTHW and I'm creating my own text adventure type of game.

I want to incorporate save function to the game (prolly by using file write). Also the game can give you hints relative to a location in the game. What I basically need is following... There will be lots of prompts for user input (raw_input) in while loops.

I want to be able to type SAVE or HINT anytime to trigger a function. How do I do this so I don't have to create the same conditional everytime? (for example

elif action == "HINT": print "..."

Is there a way to create some global expressions so that everytime they're typed in the prompt I can act on them? I will create a module with dictionary that will reference to a certain hint when the player is present in certain location. I just want to avoid putting the same conditionals all over the place.

Answer Source

If you separate the input into a function, you can pass a hint and access save easily:

def user_input(prompt, hint):
    while True:
        ui = raw_input(prompt)
        if ui.lower() == "hint":
            print hint
        elif ui.lower() == "save":
            return ui

You could also add checking here that the user stays within specific choices (an additional argument), deal with any errors and only ever return valid input.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download