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.
Related
I have written a menu that runs before I am testing it will only run the first if and not any of the following elif lines.
An example being when asked to make my input in the first question in the menu, if I type exit (or any capitalised variation) it will output 'Goodbye' as expected and stop running but if I type in 'color', 'colour', 'play' or make an invalid entry nothing happens and the script stops running.
print("Python Adventure\n")
def menu(): # This is the menu text for options before running the game
option_1 = input("Select an option:\nPlay Color Exit\nType:")
if option_1.lower() == "exit":
print("\nGoodbye")
exit()
elif option_1.lower() == "color" or "colour": # color options here
def color():
color_1 = input("Play with color? yes/no\nType:")
if color_1.lower() == "n" or "no":
print("Color off\n")
menu()
elif color_1.lower() == "y" or "yes":
print("Color on\n")
menu()
elif color_1.lower() != "":
print("Not recognised please try again.")
color()
color()
elif option_1.lower() == "play": # Text based game will start here.
print("Running: Python Woods")
elif option_1.lower() != "": # Invalid entry trigger.
print("Invalid entry, try again.")
menu()
menu()
Please feel welcome to correct me on any terminology and formatting too. Any learning is helpful.
Here is a better design, which most of the commenters have implied:
print("Python Adventure\n")
def color():
color_1 = input("Play with color? yes/no\nType:")
if color_1.lower() in ("n", "no"):
print("Color off\n")
elif color_1.lower() in ("y", "yes"):
print("Color on\n")
else:
print("Not recognised please try again.")
return True
return False
def menu(): # This is the menu text for options before running the game
option_1 = input("Select an option:\nPlay Color Exit\nType:")
if option_1.lower() == "exit":
print("\nGoodbye")
return False
elif option_1.lower() in ("color", "colour"): # color options here
while color():
pass
elif option_1.lower() == "play": # Text based game will start here.
print("Running: Python Woods")
elif option_1.lower() != "": # Invalid entry trigger.
print("Invalid entry, try again.")
return True
while menu():
pass
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()
I want to print the menu again after someone enters a number (selects an option) on the same menu except for 5 which means quit. How can I do this? It has to print whatever it is in that option plus the menu again.
def main():
choice = '0'
while choice == '0':
print("Welcome to the Game!")
print("1) Sort by Value")
print("2) Sort by ID")
print("3) Find Card")
print("4) New Hand")
print("5) Quit")
choice = input("Please make a selection: ")
if choice == "5":
print("Thanks for Playing!")
elif choice == "4":
pass
elif choice == "3":
pass
elif choice == "2":
for i in range(1, 31):
myCard = Card(i)
print(myCard)
elif choice == "1":
myDeck = Deck()
print(myDeck)
else:
print("I don't understand your choice.")
You should put your if-statements in while-loop. And your while-loop condition should not be '0' if you intend to make '5' be quitting the game.
How about you create a function called print_menu(), and call it every time when you need it?
def print_menu():
print("1) Sort by Value")
print("2) Sort by ID")
print("3) Find Card")
print("4) New Hand")
print("5) Quit")
def main():
print("Welcome to the Game!")
print_menu()
while True:
choice = input("Please make a selection: ")
if choice == '5':
print("Thanks for Playing!")
break
elif choice == '4':
print_menu()
# something
elif choice == '3':
print_menu()
# something
elif choice == '2':
print_menu()
# something
elif choice == '1':
print_menu()
# something
else:
print("I don't understand your choice.")
print_menu()
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'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"