John Jonela
John Jonela

Reputation: 31

Can't repeat what is asked in my code

I'm creating a text-based adventure game in Python 3.4.3 and I can't figure out how to make the code repeat a question. There's a bunch of narration before this, if that helps understand what's going on at all.

print("\n\n\n\n\nYou awake to find yourself in the center of a clearing in a forest.")
print("You stand up and decide to take a look around.")

str = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
print(" ")
if str in ("d"):
    print("You see your combat boots and the grassy ground below your feet. ")

if str in ("l"):
    print("The forest trees grow thicker and darker that way. You stare into the shadows and feel... cold...")

if str in ("r"):
    print("The forest is warm and inviting that way, you think you can hear a distant birds chirp.")

if str in ("u"):
    print("The blue sky looks gorgeous, a crow flies overhead... that's not a crow...")
    print("It's a Nevermore, an aerial Grim. You stand still until it passes.")

if str in ("b"):
    print("the grass slowly grows to dirt as the area falls into a mountain cliff. You now know where you are.")
    print("Mount Glenn, one of the most Grim-infested places in all of Remnant.")
    print("It's a bit unsettling.")

else:
    print("Try that again")

I want the code to repeat the question to the user, until they've answered every possible answer and move on to the next question. I also want it to repeat the question when they get else. How do I do this?

Upvotes: 2

Views: 102

Answers (4)

Martin Tournoij
Martin Tournoij

Reputation: 27822

Here's how I would do this; explanation is in the comments:

# Print out the start text
print("\n\n\n\n\nYou awake to find yourself in the center of a clearing in a forest.")
print("You stand up and decide to take a look around.")

# Use a function to get the direction; saves some repeating later
def get_direction():
        answer = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
        print(" ")
        return answer

# Keep running this block until the condition is False.
# In this case, the condition is True, so it keeps running forever
# Until we tell Python to "break" the loop.
while True:
        # I changed "str" to "answer" here because "str" is already a Python
        # built-in. It will work for now, but you'll get confused later on.
        answer = get_direction()

        if answer == "d":
                print("You see your combat boots and the grassy ground below your feet. ")

                # Stop the loop
                break
        elif answer == "l":
                print("The forest trees grow thicker and darker that way. You stare into the shadows and feel... cold...")
                break
        elif answer == "r":
                print("The forest is warm and inviting that way, you think you can hear a distant birds chirp.")
                break
        elif answer == "u":
                print("The blue sky looks gorgeous, a crow flies overhead... that's not a crow...")
                print("It's a Nevermore, an aerial Grim. You stand still until it passes.")
                break
        elif answer == "b":
                print("the grass slowly grows to dirt as the area falls into a mountain cliff. You now know where you are.")
                print("Mount Glenn, one of the most Grim-infested places in all of Remnant.")
                print("It's a bit unsettling.")
                break
        else:
                print("Try that again")

                # NO break here! This means we start over again from the top

Now, none of this scales very well if you add more than a few directions; because I assume that after you go "right" you want a new question, so that's a new loop inside the loop, etc.

# The start text
print("\n\n\n\n\nYou awake to find yourself in the center of a clearing in a forest.")
print("You stand up and decide to take a look around.")

# Use a function to get the direction
def get_direction():
    answer = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
    print(" ")
    return answer


# Use a function to store a "location" and the various descriptions that
# apply to it
def location_start():
    return {
        'down': [
            # Function name of the location we go to
            'location_foo',

            # Description of this
            'You see your combat boots and the grassy ground below your feet.'
        ],

        'left': [
            'location_bar',
            'The forest trees grow thicker and darker that way. You stare into the shadows and feel... cold...'
        ],

        'right': [
            'location_other',
            'The forest is warm and inviting that way, you think you can hear a distant birds chirp.'
        ],

        'up': [
            'location_more',
            "The blue sky looks gorgeous, a crow flies overhead... that's not a crow...\n" +
                "It's a Nevermore, an aerial Grim. You stand still until it passes."
        ],

        'behind': [
            'location_and_so_forth',
            "The grass slowly grows to dirt as the area falls into a mountain cliff. You now know where you are.\n" +
                "Mount Glenn, one of the most Grim-infested places in all of Remnant.\n" +
                "It's a bit unsettling."
        ],
    }

# And another location ... You'll probably add a bunch more...
def location_foo():
    return {
        'down': [
            'location_such_and_such',
            'desc...'
        ],
    }

# Store the current location
current_location = location_start

# Keep running this block until the condition is False.
# In this case, the condition is True, so it keeps running forever
# Until we tell Python to "break" the loop.
while True:
    # Run the function for our current location
    loc = current_location()
    answer = get_direction()

    if answer == ("d"):
        direction = 'down'
    elif answer == ("l"):
        direction = 'left'
    elif answer == ("r"):
        direction = 'right'
    elif answer == ("u"):
        direction = 'up'
    elif answer == ("b"):
        direction = 'behind'
    else:
        print("Try that again")

        # Continue to the next iteration of the loop. Prevents the code below
        # from being run
        continue

    # print out the key from the dict
    print(loc[direction][1])

    # Set the new current location. When this loop starts from the top,
    # loc = current_location() is now something different!
    current_location = globals()[loc[direction][0]]

Now, this is just one way of doing it; one downside here is that you'll need to repeat the descriptions for the locations if you want to allow the player to approach one location from different directions. This may not apply to your adventure game (the original adventure doesn't allow this, if I remember correctly).
You can fix that quite easily, but I'll leave that as an exercise to you ;-)

Upvotes: 0

Brian Cain
Brian Cain

Reputation: 14619

Don't use str as a variable name, it will shadow an important builtin and cause weird problems.

Use a while loop to restrict the output to valid options.

valid_choices = ('d', 'l', 'r', 'u', 'b',)

choice = None
while choice not in valid_choices:
    text = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
    choice = text.strip()

if choice == 'd':
    print ('...')
elif choice == 'u':
    print ('...')

See also:

Upvotes: 2

newbie
newbie

Reputation: 1412

Basically you can put your question in a loop and iterate through it until you enter one of the desired 'if' case. I have modified your code as below. Please have a look

print("\n\n\n\n\nYou awake to find yourself in the center of a clearing in a forest.")
print("You stand up and decide to take a look around.")

while True:
    str = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
    print(" ")
    if str in ("d"):
        print("You see your combat boots and the grassy ground below your feet. ")
        break

    if str in ("l"):
        print("The forest trees grow thicker and darker that way. You stare into the shadows and feel... cold...")
        break

    if str in ("r"):
        print("The forest is warm and inviting that way, you think you can hear a distant birds chirp.")
        break

    if str in ("u"):
        print("The blue sky looks gorgeous, a crow flies overhead... that's not a crow...")
        print("It's a Nevermore, an aerial Grim. You stand still until it passes.")
        break

    if str in ("b"):
        print("the grass slowly grows to dirt as the area falls into a mountain cliff. You now know where you are.")
        print("Mount Glenn, one of the most Grim-infested places in all of Remnant.")
        print("It's a bit unsettling.")
        break

    else:
        print("Try that again")

Upvotes: 1

Tales Pádua
Tales Pádua

Reputation: 1461

Do something like this:

answered = False
while not answered:
    str = input("Question")
    if str == "Desired answer":
        answered = True

Upvotes: 0

Related Questions