I'm trying to make a Choose Your Own Adventure game in Python 3.X. I'm using the idle platform. Here is a sample of my code.
import time
again = True
while again == True:
print("You wake up as you normally do, but something's not quite right. What will be the first thing you do? \n Choices: \n Go back to sleep \n Get up")
action1 = input(": ")
if action1 == "Go back to sleep":
print("You lazyhead. As you were about to fall asleep, your ceiling collapsed on you and killed you. Don't be lazy.")
playAgain = input("Play again? Y/N: ")
if playAgain == "Y":
again = True
elif playAgain == "N":
again = False
Obviously, there is stuff between action1 and playAgain. I want to replace again = false in elif playAgain =="N"
elif playAgain =="N":
again = false
I want to instead jump to playAgain so I don't just end the program. This is my first question so my formatting is probably a bit weird so please correct that too.
As mentioned, python doesn't support GoTo. One way of achieving the same result is to create a quit game function like below then call it at the end of your main game code.
def quit_game():
playAgain = input("Play again? Y/N: ")
if playAgain == "Y":
return True
elif playAgain == "N":
quit_game()
In original code:
...
again = quit_game()
Related
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.
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.
Im quite new to python and am struggling with an infinite loop. It seems that this should work given the user input is no however it just kills the program.
start = "no"
while start.lower() == "no":
start = input("Are you finished?")
break
break unconditionally aborts the while loop. Remove it, like this:
start = "no"
while start.lower() == "no":
start = input("Are you finished?")
Alternatively, if you want to use break, make it conditional:
while True:
start = input("Are you finished?")
if start.lower() != "no":
break
how do I make it restart when the user types "yes"
import random
answer=(random.randint (1,100))
play_again="yes"
tries=(0)``
guess=int(input("I'm thinking of a number between 1 and 100 "))
tries+=1
while play_again=="yes":
if (guess<answer):
guess=int(input("its higher than "+str(guess)+" "))
tries+=1
elif (guess>answer):
guess=int(input("it's lower than "+str(guess)+" "))
tries+=1
elif (guess==answer):
print("well done! You guessed the number in "+str(tries)+" guesses!")
play_again=input("would you like to play again?")
how do I make the game restart after the user wins when they type "yes"?
use two loops. one outer with play_again == "yes" and one inner with guess != answer.
while play_again == "yes":
# get input
while guess != answer:
# if lower:
# get guess
# if higher
# get guess
# get play_again
You can do this , create a function !
import random
import sys
def main():
# your code here
while True:
play_again = input("play again? :") # For python 2 raw_input()
if play_again == "yes":
main()
else:
sys.exit()
Something like this !
I hope this helps you!!
With a function that calls itself
def main():
# your code goes here
if input('Play again?') == 'yes':
main()