I'm attempting to write an escape room game in Python.
When I run the code with pycharm the process ends with "process finished with exit code 0."
Is there something wrong in the defining of the functions?
Here is my code (its a bit lengthy):
choice = None
def main_choice():
print("1. Examine door")
print("2. Examine painting")
print("3. Examine desk")
print("4. Examine bookshelf")
choice == input("Make your choice: ")
def door():
print("1. Try to open door")
print("2. Take a closer look")
print("3. Go back to where you were.")
door_choice = input("What now? ")
if door_choice == "1":
print("The door is too heavy to open with your bare hands.")
door()
if door_choice == "2":
print("There is a red light above the door, but it seems to have no purpose.")
print("You notice a 9 key keypad next to the door. It looks like it will accept a 3 digit code.")
keypad_code = input("Would you like to enter a code?").lower
if keypad_code == " yes":
guess = input("ENTER CODE: ")
if guess == complete_key:
print("The light turns green and you hear the sound of a mechanical lock unlocking. The door opens.")
print("YOU WIN!!!")
if guess != complete_key:
print("Wrong code.")
main_choice()
if door_choice == "3":
main_choice()
else:
print("You didn't answer")
main_choice()
if choice == "1":
print("You walk to the door")
door()
I think that it might be the last "if" statement, but I'm not positive.
You need to change choice == input("Make your choice: ") to choice = input("Make your choice: ") in your main_choice function:
def main_choice():
print("1. Examine door")
print("2. Examine painting")
print("3. Examine desk")
print("4. Examine bookshelf")
choice = input("Make your choice: ")
Otherwise the choice variable will still be None and if choice == "1": will always be False.
You should write:
choice = input("Make you choice: ")
rather than:
choice == input("Make you choice: ")
Double equals signs return a boolean rather than changing a value.
Related
How do I make a loop in an if-statement within an if-statement? I'm busy with How to learn Python 3 the hard way, and so far I know I can do the following:
while True:
print("choose 1st branch")
choice = input()
if choice == '1':
print('1, now choose second branch')
while True:
choice = input("")
if choice == "2":
print("2")
while True:
choice = input("")
if choice == "3":
print('3')#
else: #needs to ask for input for choice 3 again
print("try again")
else:print("try again")#needs to ask for input for choice 2 again
ive edited a simpler code example of what im trying to accomplish
Instead of creating a loop everywhere you want to check if the user input is a valid choice, you can extract that "checking if user input is within a valid choices" into a function. Said function will be something like
def get_user_choice(prompt, choices=None):
while True:
choice = input(prompt)
if choices is None:
# Return the entered choice without checking if it is
# valid or not.
return choice
if choice in choices:
return choice
print("unknown choice, try again")
With this new function, we check the validity of the choices first, then after we received the correct input, we then process with the logic for each of the choices.
occu = "ranger"
prompt = "-->"
def get_user_choice(prompt, choices=None):
while True:
choice = input(prompt)
if choices is None:
# Return the entered choice without checking if it is
# valid or not.
return choice
if choice in choices:
return choice
print("unknown choice, try again")
def room1():
print("you walk into an bare room")
door = False
gemstone = False
hole = False
monster = False
rat = False
trap = False
occu = "ranger"
while True:
print("you see a door infront of you")
print("do you go left, right or forward?")
choice = get_user_choice(prompt, ("left", "right", "forward"))
if choice == "left" and hole == False:
print("\nDo you \ndodge \nor \nattack?")
choice = get_user_choice(prompt, ("dodge", "attack"))
if choice == "dodge" and occu == "ranger":
trap = True
rat = True
print("\nhole \nroom")
choice = get_user_choice(prompt, ("hole", "room"))
if choice == "hole" and rat == True:
print("you walk up to the hole, you see a faint glitter")
print("do you reach your hand in?")
print("\nyes \nno")
choice = get_user_choice(prompt, ("yes", "no"))
if choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
choice = True
elif choice == "no":
print(" you go back to the centre of the room")
Notice that other input also get modified to use this function to check if the choice user selected is valid or not.
The problem is that you are reusing the variable choice, and assigning it to be a boolean value and later on be the input. Try using another variable as well for either the boolean or the input, i.e. proceed.
proceed = False # CREATE VARIABLE PROCEED
while proceed == False: # LOOP WHILE PROCEED IS FALSE
print("do you reach your hand in?")
print("\nyes \nno")
choice = input(prompt)
if choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
proceed = True # CHANGE PROCEED, NOT CHOICE
elif choice == "no":
print("You go back to the center of the room")
# Perhaps assign proceed to be True here as well?
else:
print("unknown choice, try again")
occu = 'ranger'
prompt = "-->"
def room1():
print("you walk into an bare room"
door = False
gemstone = False
hole = False
monster = False
rat = False
trap = False
occu = 'ranger'
while True:
print("you see a door infront of you")
print("do you go left, right or foward?")
if input(prompt) == 'left' and hole == False:
print('\nDo you \ndodge \nor \nattack?')
if input(prompt) == 'dodge' and occu == 'ranger':
trap = True
rat = True
print("\nhole \nroom")
if input(prompt) == 'hole' and rat == True:
print("you walk up to the hole, you see a faint glitter")
while True:
print("do you reach your hand in?")
print("\nyes \nno")
choice = input(prompt)
if choice not in ['yes', 'no']:
print("unknown choice, try again")
continue # <-- Starts loop over.
elif choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
else:
print(" you go back to the centre of the room")
break # <-- Breaks out of loop.
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()
all_options = ["rock", "paper", "scissors"]
outcomes = {"rockP": ["paper", "computer"], "rockS": ["scissor", "player"], "paperR": ["rock", "player"], "paperS": ["scissor", "computer"], "scissorsR": ["rock", "computer"], "scissorsP": ["paper", "player"]}
input_loop = True
def play_again():
again = input("Would you like to play again?(Yes or No): ")
if again.lower() == "yes":
continue
elif again.lower() == "no":
exit()
else:
print("Invalid input. Exiting")
exit()
while True:
while input_loop == True:
choice = input("Please input Rock, Paper, or Scissors: ")
if choice.lower() in all_options: #Making sure that the input is lowercase so it doesn't error
choice = choice.lower()
input_loop = False
break
else:
print("\n That is not a valid input \n")
computer_choice = random.choice(all_options)
if choice == computer_choice:
print("Draw!")
play_again()
computer_choice = computer_choice.upper()
current_outcome = choice + computer_choice
current_outcome_list = outcomes.get(current_outcome)
current_outcome_list.insert(0, choice)
player, winner, outcome = current_outcome_list
winning_message = print(f"{winner} has won, \nplayer chose: {player}, \ncomputer chose: {computer}.")
print(winning_message)
play_again()
How can I use that function with the continue statement? Or any other method to avoid me repeating that chunk of code. I am new to python and I need to add enough words to allow me to post this. Thank you for everybody who is going to help me :)
Error message:
C:\desktop 2\files\Python projects\rock paper scissiors\Method2>gamelooped.py
File "C:\desktop 2\files\Python projects\rock paper scissiors\Method2\gamelooped.py", line 9
continue
^
SyntaxError: 'continue' not properly in loop
It sounds like you may not be familiar with the purpose of the continue keyword. It can only be used in loops. When you reach a continue statement in a for or while loop, none of the remaining statements in the loop are executed, and the loop continues from the beginning of the next iteration (if there is another iteration to be had).
You can't continue in a function unless you're in a loop that's in a function. What is it that you intended for that continue statement to do? It might be that you just need to return.
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()
I thought the logic of my while loop made sense, but it abruptly stops after the first loop.
choice=int(input("Enter choice:"))
if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
valid = False
while valid == False:
print("Invalid choice, please enter again")
choice=int(input("Enter choice:"))
return choice
if choice ==1:
valid=True
display_modules_average_scores()
menu()
elif choice ==2:
valid=True
display_modules_top_scorer()
menu()
elif choice==0:
exist=True
print("===============================================")
print("Thank you for using Students' Result System")
print("===============================================")
If I enter 5, it does:
print("Invalid choice, please enter again")
choice=int(input("Enter choice:"))
But if I enter 5 again, it stops the program. What am I doing wrong?
if I enter 5 again, it stops the program
Because you have a return statement that immediate ends the function you're running within.
You seem to be trying to create an infinite loop. You can start with testing exit and invalid conditions with this. Note:choice will never equal an empty string
while True:
choice=int(input("Enter choice (0 to exit):"))
if choice == 1:
pass # do something
elif choice == 2:
pass # do something else
elif choice == 0:
break
else:
print("Invalid choice, please enter again")
print("Thanks")
To exit the loop, you can use break, which executes code after the loop. Use return to end the function, as mentioned. There is a difference
If you're running this loop inside of the menu() function, you do not need to actually call the menu function again. That's the point of the while loop
By defining the function we can perform this task easily with no code duplication.
The Below code calls the function inputchoice() and then the inputchoice() will check the value entered by the user and if there the value is not valid then the inputchoice will call itself and the process continues untill the user enter correct input.
def inputchoice():
choice=int(input("Enter choice: "))
if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
print("Invalid choice!")
choice = inputchoice()
return choice
def menu():
choice = inputchoice()
print(choice)
if choice ==1:
valid=True
print("Do something if Valid = True")
elif choice ==2:
valid=True
print("Do something if Valid = True")
elif choice==0:
valid=True
print("Do something if Valid = True")
menu() #implementing menu function
I prefer making a dictionary with your functions, keeps the code clean in my eyes.
Consider this code here:
def choice1():
return 'choice1'
def choice2():
return 'choice2'
def defaultchoice():
return 'default'
choicedict = {
'1': choice1,
'2': choice2
}
while True:
choice = input("Enter choice (0 to exit):") # maintain as str to avoid error!
if choice == '0':
break
value = choicedict.get(choice, defaultchoice)()
print(value)
Single Function Code
def menu():
choice=int(input("Enter choice:"))
if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
print("Invalid choice, please enter again")
menu()
elif choice ==1:
print("Oh, its working")
menu()
elif choice ==2:
print("Oh, its working")
menu()
elif choice==0:
print("===============================================")
print("Thank you for using Students' Result System")
print("===============================================")
menu()
Hi i would use a while loop like this. It would seem from this assignment that we are from the same institution. This is what i use for my code, I hope this helps.
while True:
user_input = input("Enter choice: ")
if (user_input == "0"):
print("=====================================================")
print("Thank You for using Students' Result System")
print("=====================================================")
break
elif(user_input == "1"):
display_modules_average_scores()
elif(user_input == "2"):
display_modules_top_scorer()
else:
print("Invalid choice, please enter again")