Text based adventure challenge issues - python

I'm new at coding and I've been trying this text-based adventure game. I keep running into syntax error and I don't seem to know how to solve this. Any suggestions on where I could have gone wrong would go a long way to helping.
def play_again():
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
play_again()
else:
exit()
def game_over(reason):
print("\n", reason)
print("Game Over!!!")
play_again()
def diamond_room():
print("\nYou are now in the room filled with diamonds")
print("what would you like to do?")
print("1) pack all the diamonds")
print("2) Go through the door")
answer = input(">")
if answer == "1":
game_over("The building collapsed bcos the diamonds were cursed!")
elif answer == "2":
print("You Win!!!")
play_again()
else:
game_over("Invalid prompt!")
def monster_room():
print("\nYou are now in the room of a monster")
print("The monster is sleeping and you have 2 choices")
print("1) Go through the door silently")
print("2) Kill the monster and show your courage")
answer = input(">")
if answer == "1":
diamond_room()
elif answer == "2":
game_over("You are killed")
else:
game_over("Invalid prompt")
def bear_room():
print("\nThere's a bear in here!")
print("The bear is eating tasty honey")
print("what would you like to do?")
print("1) Take the honey")
print("2) Taunt the bear!")
answer = input(">").lower()
if answer == "1":
game_over("The bear killed you!!!")
elif answer == "2":
print("The bear moved from the door, you can now go through!")
diamond_room()
else:
game_over("Invalid prompt")
def start():
print("Do you want to play my game?")
answer = input(">").lower()
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
if answer == "l":
bear_room()
elif answer == "r":
monster_room()
else:
game_over("Invalid prompt!")
start()
it keeps popping error and i cant detect where the error is coming from.

You have 2 problems.
Assertion instead of Assignment.
Calling the wrong function.
For 1. You have
def start():
print("Do you want to play my game?")
answer = input(">").lower()
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
if answer == "l":
bear_room()
elif answer == "r":
monster_room()
else:
game_over("Invalid prompt!")
You should uuse answer = input(">") and not answer ==.
For 2. You have
def play_again():
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
play_again()
else:
exit()
You should call start not play_again

In this part of your code, you should change you last line:
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
to answer = input(">").lower()
use = to assign a value to a variable, and use == to check the similarity(ex. in an if)
it is better to make the user input to lower case as other parts of your code, because in next lines of you've checked its value in an if condition with lower case (r and l).
3)another problem is that in def play_again(): you have to call start() function, sth like this:
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
start()

Related

I came across what is most likely is an indentation error, but I can't figure it out [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 23 days ago.
Improve this question
I'm programming a text adventure game in python, and while fixing some syntax. I got what I think is an indentation error, but I can't seem to be able to fix it. My expected results were for the opening part in the game to run, me enter the main game, and be able to test the inventory system. now my question may be silly, but I'm just starting in python. the specific error is:
File "main.py", line 56
else:
^
SyntaxError: invalid syntax
and my code is:
import random
room = random.randrange(100,400)
door = 0
closets = 0
invintorySlots = 0
# Menu
print(" --------DOORS--------")
answer = input(" < Press enter to continue >")
#intro
print("You enter the hotel, its storming outside")
print("The receptionist, a girl with black hair and brown eyes says hi to you.")
print("Her: Your reserved room is number",room)
print(" ")
answer = input("(A): Thanks! (B): Your cute (C): ...")
if answer == "a":
print("You: Thanks!")
print("Her: No problem!")
elif answer == "b":
print("You: Your cute.")
print("Her: Im not really into dating right now.. Thank you though!")
elif answer == "c":
print("Her: Not much of a talker eh?")
print("You walk to your room")
print("You enter but its not your room. its another room, with another door.")
#main game
door += 1
print("You enter door",door)
if closets > 0:
if random.randrange(1,2) == 2:
print("The lights flicker")
answer = input("(A): Hide in the closet (B): go to the next door (C): look around")
if answer == "a":
print("You hide in a closet")
elif answer == "b":
door += 1
print("You enter door",door)
elif answer == "c":
print("You look around")
if random.randrange(1,10) == 1:
print("You found a lighter!")
#Each item has a number ID
if invintorySlots == 0:
invintorySlots = 1
print("You got a lighter")
else:
print("Would you like to replace your current item with this one?")
answer = input("(A): yes (B): no
if answer == "a":
print("You swapped your item for a lighter")
else:
print("You kept your lighter")
else:
answer = input("(A): Go to the next door (B): say your name (C): ...")
answer = input("(A): yes
Should be
answer = input("(A): yes (B): no")
And your if else should not be tabbed over after.
You have an extra else statement at the end which will never be reached.
Your code should look like this:
import random
room = random.randrange(100,400)
door = 0
closets = 0
invintorySlots = 0
# Menu
print(" --------DOORS--------")
answer = input(" < Press enter to continue >")
#intro
print("You enter the hotel, its storming outside")
print("The receptionist, a girl with black hair and brown eyes says hi to you.")
print("Her: Your reserved room is number",room)
print(" ")
answer = input("(A): Thanks! (B): Your cute (C): ...")
if answer == "a":
print("You: Thanks!")
print("Her: No problem!")
elif answer == "b":
print("You: Your cute.")
print("Her: Im not really into dating right now.. Thank you though!")
elif answer == "c":
print("Her: Not much of a talker eh?")
print("You walk to your room")
print("You enter but its not your room. its another room, with another door.")
#main game
door += 1
print("You enter door",door)
if closets > 0:
if random.randrange(1,2) == 2:
print("The lights flicker")
answer = input("(A): Hide in the closet (B): go to the next door (C): look around")
if answer == "a":
print("You hide in a closet")
elif answer == "b":
door += 1
print("You enter door",door)
elif answer == "c":
print("You look around")
if random.randrange(1,10) == 1:
print("You found a lighter!")
#Each item has a number ID
if invintorySlots == 0:
invintorySlots = 1
print("You got a lighter")
else:
print("Would you like to replace your current item with this one?")
answer = input("(A): yes (B): no")
if answer == "a":
print("You swapped your item for a lighter")
else:
print("You kept your lighter")

Why do the if statements work, but NOT the else statements?

All if statements work, but the else statements in the first two if/else blocks return the following error? Can someone please tell me why this is?
Traceback (most recent call last):
File "main.py", line 36, in <module>
if swim_or_wait.lower() == "wait":
NameError: name 'swim_or_wait' is not defined
code
left_or_right = input("Choose which way you want to go. Left or right? ")
if left_or_right.lower() == "left":
swim_or_wait = input("Do you want to swim or wait? ")
else:
print("Wrong way. You fell into a hole. Game over.")
if swim_or_wait.lower() == "wait":
which_door = input("Choose which door you want to go through? Red, blue, or yellow? ")
else:
print("You've been attacked by a trout. Game Over.")
if which_door.lower() == "red":
print("Burned by fire. Game Over.")
elif which_door.lower() == "blue":
print("Eaten by beasts. Game Over.")
elif which_door.lower() == "yellow":
print("Congratulations!!! The game is yours. You Win!")
else:
print("Wrong door. Game Over.")`your text
swim_or_wait is only ever defined in the first if statement. If that first if statement doesn't trigger, then this variable does not exist. You essentially have a logic error as really you need to have this second if statement nested (ugh, there are better more elegant ways of doing this but this will suffice for a homework project that this sounds like).
Forgive my formatting below on the indentations.
Par Example:
left_or_right = input("Choose which way you want to go. Left or right? ")
if left_or_right.lower() == "left":
swim_or_wait = input("Do you want to swim or wait? ")
if swim_or_wait.lower() == "wait":
which_door = input(
"Choose which door you want to go through? Red, blue, or yellow?"
)
## You'd be better with a case switch here
if which_door.lower() == "red":
print("Burned by fire. Game Over.")
elif which_door.lower() == "blue":
print("Eaten by beasts. Game Over.")
elif which_door.lower() == "yellow":
print("Congratulations!!! The game is yours. You Win!")
else:
print("Wrong door. Game Over.")
else:
print("You've been attacked by a trout. Game Over.")
else:
print("Wrong way. You fell into a hole. Game over.")

How can I return my code to the start of the code?

I've been trying to return my code to the beginning after the player chooses 'yes' when asked to restart the game. How do I make the game restart?
I've tried as many solutions as possible and have ended up with this code. Including continue, break, and several other obvious options.
import time
def start():
score = 0
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurist to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
print("Type 1 to explore Atlantis alone.")
time.sleep(1.5)
print("Type 2 to talk to the resident merpeople.")
start()
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = -1
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
score = 1
print("To explore alone enter 5. To go to the surface enter 6.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 4
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
print("Type 3 to go to the castle or 4 to go to the surface.")
score = 5
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 6
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
def choice_made():
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
def choice2_made():
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
elif choice2 == "3":
castle()
elif choice2 == "yes":
start()
elif choice2 == "no":
exit()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
def choice3_made():
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
def restart_made():
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
while True:
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
while True:
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
if choice2 == "3":
castle()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
while True:
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
if choice3 == "1":
drowndeath()
if choice3 == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
while True:
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
I want for my code to restart completely when 'yes' is typed after given the option.
In general, if you want to be able to 'go back to the beginning' of something, you want to have a loop that contains everything. Like
while True:
""" game code """
That would basically repeat your entire game over and over. If you want it to end by default, and only restart in certain situations, you would do
while True:
""" game code """
if your_restart_condition:
continue # This will restart the loop
if your_exit_condition:
break # This will break the loop, i.e. exit the game and prevent restart
""" more game code """
break # This will break the loop if it gets to the end
To make things a little easier, you could make use of exceptions. Raise a RestartException whenever you want to restart the loop, even from within one of your functions. Or raise an ExitException when you want to exit the loop.
class RestartException(Exception):
pass
class ExitException(Exception):
pass
while True:
try:
""" game code """
except RestartException:
continue
except ExitException:
break
break
You have two main options.
First option: make a main function that, when called, executes your script once. Then, for the actual execution of the code, do this:
while True:
main()
if input("Would you like to restart? Type 'y' or 'yes' if so.").lower() not in ['y', 'yes']:
break
Second, less compatible option: use os or subprocess to issue a shell command to execute the script again, e.g os.system("python3 filename.py").
EDIT: Despite the fact this is discouraged on SO, I decided to help a friend out and rewrote your script. Please do not ask for this in the future. Here it is:
import time, sys
score = 0
def makeChoice(message1, message2):
try:
print("Type 1 "+message1+".")
time.sleep(1.5)
print("Type 2 "+message2+".")
ans = int(input("Which do you choose? "))
print()
if ans in (1,2):
return ans
else:
print("Please enter a valid number.")
return makeChoice(message1, message2)
except ValueError:
print("Please enter either 1 or 2.")
return makeChoice(message1, message2)
def askRestart():
if input("Would you like to restart? Type 'y' or 'yes' if so. ").lower() in ['y', 'yes']:
print()
print("Okay. Restarting game!")
playGame()
else:
print("Thanks for playing! Goodbye!")
sys.exit(0)
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
def playGame():
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurer to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
ans = makeChoice("to explore Atlantis alone", "to talk to the resident merpeople")
if ans == 1:
drowndeath()
askRestart()
merpeople()
ans = makeChoice("to go to the castle", "to return to the surface")
if ans == 2:
surface()
askRestart()
castle()
ans = makeChoice("to return to the surface", "to explore alone")
if ans == 1:
famous()
else:
alone()
askRestart()
playGame()

Rock Paper Scissors Running Twice Error

I'm new to programming. I have written code for the rock paper scissors game but there is one bug that I can't seem to fix. When the game closes, the user is asked if he wants to play again. If the user answers yes the first time, then plays again then answers no the second time, the computer for some reason asks the user again if he wanted to play again. The user must enter no in this case. This is because although the user answers no, the answer gets reset to yes and goes over again. How can this be fixed?
# This code shall simulate a game of rock-paper-scissors.
from random import randint
from time import sleep
print "Welcome to the game of Rock, Paper, Scissors."
sleep(1)
def theGame():
playerNumber = 4
while playerNumber == 4:
computerPick = randint(0,2)
sleep(1)
playerChoice = raw_input("Pick Rock, Paper, or Scissors. Choose wisely.: ").lower()
sleep(1)
if playerChoice == "rock":
playerNumber = 0
elif playerChoice == "paper":
playerNumber = 1
elif playerChoice == "scissors":
playerNumber = 2
else:
playerNumber = 4
sleep(1)
print "You cookoo for coco puffs."
print "You picked " + playerChoice + "!"
sleep(1)
print "Computer is thinking..."
sleep(1)
if computerPick == 0:
print "The Computer chooses rock!"
elif computerPick == 1:
print "The Computer chooses paper!"
else:
print "The Computer chooses scissors!"
sleep(1)
if playerNumber == computerPick:
print "it's a tie!"
else:
if playerNumber < computerPick:
if playerNumber == 0 and computerPick == 2:
print "You win!"
else:
print "You lose!"
elif playerNumber > computerPick:
if playerNumber == 2 and computerPick == 0:
print "You lose!"
else:
print "You win!"
replay()
def replay():
sleep(1)
playAgain = "rerun"
while playAgain != "no":
playAgain = raw_input("Would you like to play again?: ").lower()
if playAgain == "yes":
sleep(1)
print "Alright then brotha."
sleep(1)
theGame()
elif playAgain == "no":
sleep(1)
print "Have a good day."
sleep(1)
print "Computer shutting down..."
sleep(1)
else:
sleep(1)
print "What you said was just not in the books man."
sleep(1)
theGame()
This is because of the way the call stack is created.
The First time you play and enter yes to play again, you are creating another function call to theGame(). Once that function call is done, your program will continue with the while loop and ask if they want to play again regardless if they entered no because that input was for the second call to theGame().
To fix it, add a break or set playAgain to no right after you call theGame() when they enter yes
while playAgain != "no":
playAgain = raw_input("Would you like to play again?: ").lower()
if playAgain == "yes":
sleep(1)
print "Alright then brotha."
sleep(1)
theGame()
break ## or playAgain = "no"
You should break out of the loop after calling theGame. Imagine you decided to play again 15 times. Then there are 15 replay loops on the stack, waiting to ask you if you want to play again. Since playAgain is "yes" in each of these loops, each is going to ask you again, since playAgain is not "no"

my first else condition jumps to the second else

So i am trying to NOT let the first ELSE proceed until it meets the condition to require an input that will include only 1 or 2 or 3... but it failes to do so... after 1 time print it goes on to the second ELSE... what am i doing wrong here ?
def line_func(): # line to separate
print("==========================================================================")
def vs1():
print("") # vertical space
def start1():
vs1()
print("=====================================================")
print("Would you like to start? Choose with (y)yes or (n)no.\n=====================================================\n")
while True:
start = input("Answer: ")
vs1()
if start == "y" or start == "Y" or start == "yes" or start == "YES" or start == "Yes":
line_func()
vs1()
menu1 = input("How would you like to proceed?\n\n1)Find an enemy to crush\n2)Restart game\n3)Exit game\n\nodgovor: ")
if menu1 == "1":
vs1()
start_round()
elif menu1 == "2":
vs1()
print("================= RESTARTING GAME ===================")
vs1()
print("=====================================================")
print("Would you like to start? Choose with (y)yes or (n)no.\n=====================================================\n")
continue
start1()
elif menu1 == "3":
print("Ok see you next time... bye bye :)")
break
else:
print("You have to choose one of the options to proceed...")
elif start == "n" or start == "N" or start == "no" or start == "NO" or start == "No":
print("Ok see you next time... bye bye :)")
break
else:
print("You have to choose with yes or no...")
start1()
try the below code, working for me:
def line_func(): # line to separate
print("==========================================================================")
def vs1():
print("") # vertical space
def start1():
vs1()
print("=====================================================")
print("Would you like to start? Choose with (y)yes or (n)no.\n=====================================================\n")
while not start:
start = input("Answer: ")
vs1()
if start == "y" or start == "Y" or start == "yes" or start == "YES" or start == "Yes":
start = True
line_func()
vs1()
menu1 = input("How would you like to proceed?\n\n1)Find an enemy to crush\n2)Restart game\n3)Exit game\n\nodgovor: ")
if menu1 == "1":
vs1()
start_round()
elif menu1 == "2":
vs1()
print("================= RESTARTING GAME ===================")
vs1()
print("=====================================================")
print("Would you like to start? Choose with (y)yes or (n)no.\n=====================================================\n")
continue
start1()
elif menu1 == "3":
print("Ok see you next time... bye bye :)")
break
else:
print("You have to choose one of the options to proceed...")
elif start == "n" or start == "N" or start == "no" or start == "NO" or start == "No":
start = True
print("Ok see you next time... bye bye :)")
break
else:
print("You have to choose with yes or no...")
start = False
start1()
while True:
line_func()
vs1()
menu1 = input("How would you like to proceed?\n\n1)Find an enemy to crush\n2)Restart game\n3)Exit game\n\nodgovor: ")
if menu1 == "1":
vs1()
start_round()
elif menu1 == "2":
vs1()
print("================= RESTARTING GAME ===================")
vs1()
print("=====================================================")
print("Would you like to start? Choose with (y)yes or (n)no.\n=====================================================\n")
continue
start1()
elif menu1 == "3":
print("Ok see you next time... bye bye :)")
break
else:
print("You have to choose one of the options to proceed...")
What you need is another while loop.The break condition is up to your demand.

Categories