How can I make "two questions in one" in python? - python

So Im making like a quiz sort of adventure game in Python. And as you can see, at the very start I have a guess=input statement. And then I have all my if statements. And so I said for the first line of it when you press A, it will print that text out. And the text says to say another answer. However, it stops me from entering anything else after I type in A. how can i resolve this so I'm able to say more than 1 word?
print('\n')
if guess=input ("You drive to your house, and you notice that the doors are all unlocked and some chairs are flipped over. You also hear some footsteps and hammering in the guest room. What do you do? A: Go in the room and see what is going on, B: Yell you are calling the cops and hide C: Grab a knife and head in the room D: Get too scared and run away out the door ").strip()
if guess.upper() == "A":
print("Maybe not the wisest choice... He is there with a loaded gun aimed at you. What do you do? E: Panic and just sob and close your eyes F: Attempt a ninja move and try to kick him G: Try to distract him and then push him from the behind so he falls on the ground H: Try to talk him out of aiming the gun at you")
if guess.upper() == "E":
print("Not the best idea, he shot you and you died.")
return
if guess.upper() == "F":
print("It worked! he was thinking about if he really wanted to do this and got distracted. You grabbed him by the hands then tied him up behind his back on the ground and called the cops. He was arrested. ")
print("Turns out he was most wanted! Now you have 2 options. I: Get $200,000 now from the goverment for capturing a most wanted man, or J: Get $700,000 in 2 years from the goverment for capturing a most wanted man. ")
if guess.upper() == "I":
balance = balance + 200000
print("If you don't need the money right now because you aren't struggling, than why did you do this? you could get more than 2x more by waiting!")
if guess.upper() == "J":
print("Smart option! no gains now but you will get a way bigger gain in 2 years! as long as you weren't struggling financially this was a great option.")
if guess.upper() == "B":
print("You made him madder and he did not want to get involved with the police, so he shot you, you died.")
return
if guess.upper() == "C":
print("You got lucky! he did not notice you, you stabbed him and he died. You called the cops and they gave you a reward because he was most wanted. They gave you two options for a reward. K: Audi R8 spider right now, or L: Batmobile in 10 years.")
if guess.upper() == "K":
print("You got a Audi R8 right now! it is a very nice car, but you already have one and you would have the coolest one ever in 10 years!")
if guess.upper() == "L":
print("Nice choice. You realized you already had a car so you would get a amazing one in 10 years.")
if guess.upper() == "D":
print("This did not work. He saw you running and shot you from a ways away, you died.")
return
print("Total Balance:$",balance)
keepgoing = False

This was answered by #cᴏʟᴅsᴘᴇᴇᴅ:
def start():
guess = input("You drive to your house, and you notice that the doors are all unlocked and some chairs are flipped over. You also hear some footsteps and hammering in the guest room. What do you do? A: Go in the room and see what is going on, B: Yell you are calling the cops and hide C: Grab a knife and head in the room D: Get too scared and run away out the door ").strip()
if guess.upper() == "A":
guess = input("Maybe not the wisest choice... He is there with a loaded gun aimed at you. What do you do? E: Panic and just sob and close your eyes F: Attempt a ninja move and try to kick him G: Try to distract him and then push him from the behind so he falls on the ground H: Try to talk him out of aiming the gun at you")
if guess.upper() == "E":
print("Not the best idea, he shot you and you died.")
return
elif guess.upper() == "F":
guess = input("It worked! he was thinking about if he really wanted to do this and got distracted. You grabbed him by the hands then tied him up behind his back on the ground and called the cops. He was arrested.\nTurns out he was most wanted! Now you have 2 options. I: Get $200,000 now from the goverment for capturing a most wanted man, or J: Get $700,000 in 2 years from the goverment for capturing a most wanted man. ")
if guess.upper() == "I":
balance = balance + 200000
print("If you don't need the money right now because you aren't struggling, than why did you do this? you could get more than 2x more by waiting!")
elif guess.upper() == "J":
print("Smart option! no gains now but you will get a way bigger gain in 2 years! as long as you weren't struggling financially this was a great option.")
elif guess.upper() == "B":
print("You made him madder and he did not want to get involved with the police, so he shot you, you died.")
return
elif guess.upper() == "C":
guess = input("You got lucky! he did not notice you, you stabbed him and he died. You called the cops and they gave you a reward because he was most wanted. They gave you two options for a reward. K: Audi R8 spider right now, or L: Batmobile in 10 years.")
if guess.upper() == "K":
print("You got a Audi R8 right now! it is a very nice car, but you already have one and you would have the coolest one ever in 10 years!")
elif guess.upper() == "L":
print("Nice choice. You realized you already had a car so you would get a amazing one in 10 years.")
elif guess.upper() == "D":
print("This did not work. He saw you running and shot you from a ways away, you died.")
return
start()
I removed def main from it at the start because I already had def main and then it worked. Appreciate it and thanks for the help guys!

This is the answer.
balance = 0
print('\n')
guess=input ("You drive to your house, and you notice that the doors are all unlocked and some chairs are flipped over. You also hear some footsteps and hammering in the guest room. What do you do? A: Go in the room and see what is going on, B: Yell you are calling the cops and hide C: Grab a knife and head in the room D: Get too scared and run away out the door ").strip()
if guess.upper() == "A":
guess1 = input("Maybe not the wisest choice... He is there with a loaded gun aimed at you. What do you do? E: Panic and just sob and close your eyes F: Attempt a ninja move and try to kick him G: Try to distract him and then push him from the behind so he falls on the ground H: Try to talk him out of aiming the gun at you")
if guess1.upper() == "E":
print("Not the best idea, he shot you and you died.")
elif guess1.upper() == "F":
print("It worked! he was thinking about if he really wanted to do this and got distracted. You grabbed him by the hands then tied him up behind his back on the ground and called the cops. He was arrested. ")
guess2 = input("Turns out he was most wanted! Now you have 2 options. I: Get $200,000 now from the goverment for capturing a most wanted man, or J: Get $700,000 in 2 years from the goverment for capturing a most wanted man. ")
if guess2.upper() == "I":
balance = balance + 200000
print("If you don't need the money right now because you aren't struggling, than why did you do this? you could get more than 2x more by waiting!")
elif guess2.upper() == "J":
print("Smart option! no gains now but you will get a way bigger gain in 2 years! as long as you weren't struggling financially this was a great option.")
elif guess.upper() == "B":
print("You made him madder and he did not want to get involved with the police, so he shot you, you died.")
elif guess.upper() == "C":
guess3 = input("You got lucky! he did not notice you, you stabbed him and he died. You called the cops and they gave you a reward because he was most wanted. They gave you two options for a reward. K: Audi R8 spider right now, or L: Batmobile in 10 years.")
if guess3.upper() == "K":
print("You got a Audi R8 right now! it is a very nice car, but you already have one and you would have the coolest one ever in 10 years!")
elif guess3.upper() == "L":
print("Nice choice. You realized you already had a car so you would get a amazing one in 10 years.")
elif guess.upper() == "D":
print("This did not work. He saw you running and shot you from a ways away, you died.")
print("Total Balance:$", balance)
keepgoing = False

You need a while loop which is always true and then try to make a condition which your code escapes the while loop. Your code checks if an statement is true, in your case guess.upper()=A and then runs the code within the if statement and skips the rest of the code. Let's say you ask the user whenever you enter Z, the program ends. You can rewrite your code as:
While true:
{your code}
If guess.upper=='Z':
Break
Your second line is also wrong. What exactly do you want to do over there?

Related

Use a Boolean variable that will act as a switch in the code. If the user still has guesses remaining out of the 3

My program is a guessing game that has three questions the user tey to guess the answers of the 3 questions and they have only three chances if they did make three mistakes the program restart again but if they answer the 3 questions before their 3 chances finished they get their score at the end.
The problem
When the user enters a wrong answer from their first try it automatically goes to the second question.
number_of_guesses = 0
print("Guess the Animal\n")
while number_of_guesses < 3:
number_of_guesses += 1
guess1 = (input("Which bear lives at the North Pole?"))
if number_of_guesses == 3:
break
if guess1 != ("polar bear"):
print("please try again")
else:
print("correct answer")
guess2 = (input("Which is the fastest land animal?"))
if number_of_guesses == 3:
break
if guess2 != ("cheetah"):
print("please try again")
else:
print("correct answer")
I'm trying to make it look like this:
Guess the Animal
Which bear lives at the North Pole? grizzly
Sorry Wrong Answer, try again teddy
Sorry Wrong Answer, try again black
The Correct answer is polar bear
Lob Kei We Ran asa Tie ia ote hn Bie Molo tee)
Correct Answer
Which is the largest animal? elephant
Sorry Wrong Answer, try again blue whale
Correct Answer
Your Score is 2
The following function returns True when the question is answered correctly and False otherwise:
def question(q, a):
for i in range(3):
x = input(f'{q}\n' if i == 0 else 'Wrong answer, try again:\n')
if x == a:
print('Correct answer')
return True
print(f'The correct answer is "{a}"')
return -1
To support multiple questions and print the total score in the end you can try:
questions = {
'Which bear lives at the North Pole?': 'polar bear',
'Which is the fastest land animal?': 'cheetah',
'Which is the largest animal?': 'blue whale',
}
print(f'Your score is {sum(question(q, a) for q, a in questions.items())}')
You need to start again at the top of the while loop when they have given an incorrect answer.
So, you see wherever you have print("please try again").
After this, put down continue in a new line.
This will cause the program to start again at the top of the while loop.

How can I stop the loop after max wrong answer?

This is an exercise from Introduction to CompSci and Programming in Python from OCW MIT. I modified it a little bit. The problem is I want to stop the program when I reached the max wrong answer but it stops if I try two times. Why two times ? How can I fix this ? As a new starter should I ask every question here ? Thanks to all
n = 0
max_guesses = 3
n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
if n == "left" or "Left":
print("You're out of lost forest")
while n == "right" or n == "Right":
n = input("You are in the Lost Forest\n****************\n****** ***\n :(\n****************\n****************\nGo left or right? ")
n =+ 1
for n in range (max_guesses):
break
print("Game over! You ran out of your lives")
There are a few errors that contribute to your code not working properly
Your variable n is the same as the value you get from the value you input best to separate those into different values to make it easier to avoid hard to detect errors
You need to have a condition that checks if n >= max_guesses.
Welcome to the community, we try to discuss the issues here rather than looking for a whole solution.
I suggest you to first learn the very basics of programming like the decision making, control flows (i.e if statements and loops).
Also, try to attempt the question, multiple numbers of times with different logics and inputs at runtime. it will give you a better understanding of logical analysis.
Here's one of the ways you could have added the logic.
#Maximum allowed guesses
max_guesses = 3
def func1():
#Input string 'left' or 'right'
in_str = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
#Number of attempts made
n = 1
if in_str.lower() == "left":
print("You're out of lost forest")
while in_str.lower() == "right":
in_str = input("You are in the Lost Forest\n****************\n****** ***\n :(\n****************\n****************\nGo left or right? ")
n += 1
if in_str.lower() == "left":
print("You're out of lost forest")
break
if n >= max_guesses:
print("Game over!!!")
break
print("Total attempts made by user: ",n)
func1()
I have attempted to fix your code however, I have had to remove the for loop and change the variable names. Hopefully, it helps.
n = 1
max_guesses = 3
a = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
if a.lower() == "left":
print("You're out of lost forest")
while a.lower() == "right":
if n == 3:
print("Game over! You ran out of your lives")
break
else:
a = input("You are in the Lost Forest\n****************\n****** ***\n :(\n****************\n****************\nGo left or right? ")
n += 1

How to make python code go back to the original question after it hits the else or elif in an if else statement instead of quitting the code

For example:
if answer == "1":
print ("right answer")
elif answer == "2":
print ("Wrong answer. Try again")
else:
print ("Invalid input: Please try again")
So that was just a quick example of what I'm trying to say. Instead of allowing the user to enter the answer again, the code quits and they have to go through the whole thing.
How can I make it so that they get to return to the original answer instead of starting the entire code over again?
Thank you.
EDIT: I should have used the actual code instead of an example because I can't understand it in the context of my actual code.
print ("\nYou do not have any dogs treats. Maybe you should have grabbed some--your mother always keeps the dog treats in one of the bedrooms upstairs.")
next_choice = input("\nWhat do you do now?\n1. Go back upstairs and get the dog treats\n2. Walk down anyway\n")
if next_choice == "1":
which_bedroom = input ("\nYou go back upstairs to look for the dog treats. Which room do you go to first?\n1. Your bedroom\n2. Your sister's bedroom\n3. The bathroom\n4. Your mother's bedroom\n")
if which_bedroom == "1":
print ("This is where you first started. There is nothing here. Please try again.")
elif which_bedroom == "2":
print ("There is nothing here. Please try again.")
elif which_bedroom == "3":
print ("The bathroom is locked--your sister must be in there. Why would there be dog treats in the bathroom anyway? Please try again.")
elif which_bedroom == "4":
print ("Congrats! You found the dog treats along with a note that says: 1970")
downstairs_again = input ("You go back downstairs, and yet again, your dogs spots you. What do you do?\n1. Walk down anyway\n2. Give him the dog treats\n")
Depending on the specific application your code block and if conditions might be different, but from your example it would be something akin to this.
answered=False
while(not answered):
if answer=='1':
answered=True
print('Right answer')
elif answer=='2':
print('Wrong answer try again')
else:
print('Invalid input try again')
EDIT:
I'm assuming your function input() is handling all UI inputs behind the scenes.
answered=False
while(not answered):
which_bedroom = input('....') #insert your long string
if which_bedroom=='1':
print('wrong answer try again')
elif which_bedroom =='2':
print('wrong answer try again')
elif which_bedroom == '3':
answered=True
print('correct! next question...')
else:
print('Invalid input try again')
next_question() #copy above for downstairs_again instead of nesting it in this loop
Since you created a new variable for your second question after your first question is correctly answered, I assume you have completely different if-else conditions for your next question. I'd therefore recommend implementing a similar while loop for the new question if your text-dungeon-crawler-esque adventure is relatively short and you're just trying to get a proof of concept.
Put it in a while loop:
while (answer := input("QUESTION: ") != "1":
print("Wrong answer. Try again" if answer == "2" else "Invalid input: Please try again")
Without the fancy stuff:
answer = None
while answer != "1":
answer = input("QUESTION: ")
if answer == "2":
print ("Wrong answer. Try again")
else:
print ("Invalid input: Please try again")
EDIT: Here's what your code will look like using the above:
print ("\nYou do not have any dogs treats. Maybe you should have grabbed some--your mother always keeps the dog treats in one of the bedrooms upstairs.")
while (next_choice := input("\nWhat do you do now?\n1. Go back upstairs and get the dog treats\n2. Walk down anyway\n")) != "1":
if next_choice == "2":
print("whatever you want to print after picking 2")
print("whatever you want to print after picking 1")
while (which_bedroom := input ("\nYou go back upstairs to look for the dog treats. Which room do you go to first?\n1. Your bedroom\n2. Your sister's bedroom\n3. The bathroom\n4. Your mother's bedroom\n")) != "4":
if which_bedroom == "1":
print ("This is where you first started. There is nothing here. Please try again.")
elif which_bedroom == "2":
print ("There is nothing here. Please try again.")
elif which_bedroom == "3":
print ("The bathroom is locked--your sister must be in there. Why would there be dog treats in the bathroom anyway? Please try again.")
print ("Congrats! You found the dog treats along with a note that says: 1970")
while (downstairs_again := input ("You go back downstairs, and yet again, your dogs spots you. What do you do?\n1. Walk down anyway\n2. Give him the dog treats\n")) != "correct choice":
pass #do stuff
while loops are an easy way to accomplish this, but look into using classes holding objects of the same class to easily build and execute a tree of choices.

Problems with a Python if-else statement

I am doing an assignment for an IT class. Very basic Python projects. I have no experience with it but am able to grasp what is going on most of the time. This project involves making choices involving random integer selections. I can get the options to work the way I want in the if-else format but the else command isn't responding the way I want. The options all load properly but if the choice is 1-3 for some reason the program then prints the "else" statement after printing the "if" statements. This doesn't happen if they choose option 4 or pick an invalid number(the reason for the else statement).
I didn't have this issue in the previous section of the program. I must have missed something, but I can't tell what it is. I should reiterate I am very much a beginner at this and am basically copy-pasting code as the assignment instructed, and then editing it to suit my needs.
interactions = ["Back Away Slowly","Point Towards the Chamber","Attack","Try To Communicate",]
import random
badchoice = random.randint(1,3)
loop = 1
while loop == 1:
choice=menu(interactions, "How do you decide to interact?")
print("")
if choice == 1:
print("You start to slowly back away from the man.")
print("You worry you are giving off the wrong attitude.")
print("")
if choice == badchoice:
loop=0
print("The stranger was already weary of your presence.")
print(interactions[choice-1], "was not the correct decision.")
print("He calls for help. Villagers and guards immediately surround you.")
print("You are thrown back into the chamber. Hitting your head, and getting knocked unconscious in the process.")
print("You are back where you started and the items have been removed.")
print("There is no escape.")
print("Lamashtu's Curse can not be broken.")
print("Game Over.")
else:
print("The stranger looks at you in confusion.")
print("")
# Choices 2 and 3 go here. Same code. Seemed redundant to post all of it.
if choice == 4:
loop=0
print("The stranger is weary of your presence, and can not understand you.")
print("You can see in his eyes that he wants to help,")
print("and he escorts you back to his home for the time being.")
print("He offers you some much needed food and water.")
print("You are no closer to understanding what curse brought you here.")
print("Perhaps tomorrow you will have more time to inspect your surroundings.")
print("In time you may be able to communicate enough with your host to explain your dilemma,")
print("but for now you are trapped 6000 years in the past with no other options.")
print("At least you've made it out alive thus far......")
print("To be continued...")
else:
print("Please choose a number between 1 and 4.")
The else only applies to the most recent if at the same level, ie the one for number 4. The other three if statements are all independent. So after checking each of those, it then goes to check if the choice is 4, and runs the else if it isn't.
You need to make these all part of the same statement, which you do by using elif for every if after the first. Like this:
if choice == 1:
...
elif choice == 2:
...
elif choice == 3:
...
elif choice == 4:
...
else:
...
Your logic is incorrect. Your final if statement directs choice 4 to it's True branch, and everything else to the False branch. Python does exactly what you told it to do. There is no logical reference to the previous blocks.
The logic you need is
if choice == 1:
...
elif choice == 2:
...
elif choice == 3:
...
elif choice == 4:
...
else:
print("Please choose a number between 1 and 4.")

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?
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:
string.strip
tuples
None
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")
Do something like this:
answered = False
while not answered:
str = input("Question")
if str == "Desired answer":
answered = True
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 ;-)

Categories

Resources