Python not reading string a second time

85 views Asked by At

I'm writing a text adventure (does anyone remember Zork?), and I'm having troubles with this code:

from random import randint

def prompt():
    action = input(">>> ").lower()
    if action == "exit":
        quit()
    elif action == "save":
        save()
    else:
        return action

def action_error(custom=False):
    if custom != False:
        print(custom)
    else:
        phrases = ["A bunch", "of funny", "error phrases"]
        print(phrases[randint(1, len(phrases)-1)])
    return prompt()

action = prompt()
while True:
    print(action) #Debugging purposes
    if action.find("switch") != -1:
        if action.find("light") != -1:
            second_room() #Story continues
        else:
            action = action_error("What do you want to switch?")
    action = action_error()

The matter is that if I enter a string that contains "switch", the next input is not picked up.

Also, anyone has better ways to parse verb-noun strings like "switch the light", "open the door" or "look around"/"look at OBJECT"?

2

There are 2 answers

0
Giovanni Berti On BEST ANSWER

First of all I noticed that if you enter switch twice the second time it's caught as an error by your program. I think the problem lies at the end of the action_error function where you assign the return value to prompt(), so the input get consumed too early.

A possible fix would be:

def action_error(custom=False):
    if custom != False:
        print(custom)
    else:
        phrases = ["A bunch", "of funny", "error phrases"]
        print(phrases[randint(1, len(phrases)-1)])

while True:
    action = prompt()
    print(action) #Debugging purposes
    if action.find("switch") != -1:
        if action.find("light") != -1:
            second_room() #Story continues
        else:
            action_error("What do you want to switch?")
    else:
        action_error()

So no return value for action_error() and direct assignment at the beginning of the while loop.

2
Kevin On

How about, in the case of a partially entered compound action, you concatenate the new input to the old one? Then "switch" becomes "switch light", and both of your conditionals will pass.

action = prompt()
while True:
    print(action) #Debugging purposes
    if action.find("switch") != -1:
        if action.find("light") != -1:
            second_room() #Story continues
        else:
            action = action + " " + action_error("What do you want to switch?")
            continue
    action = action_error()

Bonus style suggestions:

  • replace a.find("b") != -1 with "b" in a
  • use random.choice(phrases) instead of phrases[randint(1, len(phrases)-1)]