문제

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 a save function to the game (probably by using file write). Also, the game can give you hints based on your 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 any time to trigger a function. How do I do this so I don't have to create the same conditional every time? (for example elif action == "HINT": print "...")

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

도움이 되었습니까?

해결책

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":
            save()
        else:
            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.

다른 팁

you should probably use a dictionary

def do_save(*args,**kwargs):
    print "SAVE!"

def do_hint(*args,**kwargs):
    print "HINT!"

def do_quit(*args,**kwargs):
    print "OK EXIT!"

global_actions = {'SAVE':do_save,
           'HINT':do_hint,
           'QUIT':do_quit}

def go_north(*args,**kwargs):
   print "You Go North"

def go_east(*args,**kwargs):
   print "you go east"

def make_choice(prompt="ENTER COMMAND:",actions={},context_info={}):   
    choice = raw_input(prompt)
    fn = actions.get(choice.upper(),lambda *a,**kw:sys.stdout.write("UNKOWN CHOICE!"))
    return fn(some_context=context_info)


local_actions = {"NORTH":go_north,"EAST":go_east}
player_actions = dict(global_actions.items() + local_actions.items())
print "From Here You Can Go [North] or [East]"
result = make_choice(actions=player_actions,
                     context_info={"location":"narnia","player_level":5})

I don't know about the save feature but for hint you could just have;

If raw_input == hint:
    print "whatever you want here"

Or if you need the hint to be different depending on your position you could have a variable for what the hint for that room is and have it update each time you enter a new room then have:

if raw_input == "hint":
    print hintvariable

If this doesn't work then sorry, I'm new.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top