What have I done wrong with programming a multiple choice game - python

I'm trying to create a game and cant get the y/n function to work
I've tried the code below and it says y is not defined or it will just skip asking and print ("Lets go!")
import time
name = input ("Hello, what is your name?")
print ("Hello," +name)
time.sleep(1)
print ("ready to play? [y/n]")
y = print ("Let's go!")
Here's how it should look like:
Hello, what is your name? xyz
Hello, xyz
ready to play? [y/n] y
Let's go!
I wanted it to wait for my input of either y or n before it said ("Let's go!")

You are not asking for input on "ready to play" line you are just printing, so therefore it is not going to wait.

First, you need to change print ("ready to play? [y/n]") to input("ready to play? [y/n]") and put it inside a variable. Next, remove y = print ("Let's go!"), and change it with this (if you want to):
ready_status = input("are you ready? [y/n]")
if ready_status == 'y':
print("let's go!")
if ready_status == 'n':
print("...")
#do anything you want

You do not have a wait command after your print prompt. Therefore it is not going to wait.
Try this method for inputting a wait time
answer = input("y/n?")

Related

Python 3 Y/N Loop Issue

I'm very new to Python, and I'm just having a play with making some very simple little programs to get a feel for it, so probably best to keep any explanations really simple haha!
I'm currently making a little program that asks if you want to roll a dice, rolls it, gives you the answer and asks if you want to roll again.
The issue I'm having trouble figuring out is the following (copied from console):
What is your name: Nasicus
Greetings Nasicus!
Would you like to roll the dice? [Y/N]? : Y
Let's do this!
Rolling...
You rolled a 3!
Do you want to roll again? [Y/N]?: Y
Yahoo!
Would you like to roll the dice? [Y/N]? : N
Oh, Okay. Maybe next time.
Would you like to roll the dice? [Y/N]? : N
Oh, Okay. Maybe next time.
Process finished with exit code 0
As you can see, it prompts twice when you select N before it closes.
I'm probably missing something incredibly simple, so could anyone advise how I can either A. Stop it prompting twice or (preferably for the sake of simplicity) B. Stop it asking if You want to roll the dice after you have already selected Y to roll again, and just go straight from the Let's do this! line.
Here is my code, any pointers on how to keep things tidier/more pythonic always appreciated too! I appreciated the time.sleep() probably look a little messy, but I do like the way it paces things when I run it:
import random
import time
def diceroll():
while True:
diceyn = input ("Would you like to roll the dice? [Y/N]? : ")
if diceyn == "Y":
print ("Let's do this!")
time.sleep(0.5)
print ("Rolling...")
time.sleep(1)
rand = random.randint(1, 6)
print ('You rolled a ',rand,'!', sep='')
time.sleep(0.5)
again = str(input("Do you want to roll again? [Y/N]?: "))
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
else:
time.sleep(0.3)
print ('Okay, bye!')
break
elif diceyn == "N":
print ("Oh, Okay. Maybe next time.")
break
input_name = input ("What is your name: ")
print ("Greetings ",input_name,"!", sep='')
time.sleep(1)
diceroll()
Thank you for your time, and I look forward to learning more :D
The problem is in this section of code:
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
You're recursively calling the diceroll() function, so when that recursive call finally finishes, the iteration of the current call still continues.
You're already in a while True loop, so you don't even need the recursive call. Just take it out, and let the loop continue.
You are calling diceroll recursively.
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
So you call diceroll() and then whenever the user is asked
Do you want to roll again
You call diceroll() again.
Here is what is happening. You have a top level diceroll().
diceroll()
Then you have another diceroll() under it like this:
diceroll()
-- diceroll()
And then you have yet another diceroll() inside it.
diceroll()
-- diceroll()
---- diceroll()
When you call the break statement, all you are doing is breaking out of that inner diceroll() loop, not the loop where you called it.
A break in the third row sends you to
diceroll()
-- diceroll()
I would just break out your actual rolling into a separate function in your diceroll() function, that way you won't confuse the paths.
import random
import time
def diceroll():
def rollIt():
time.sleep(0.5)
print ("Rolling...")
time.sleep(1)
rand = random.randint(1, 6)
print ('You rolled a ',rand,'!', sep='')
time.sleep(0.5)
while True:
diceyn = input ("Would you like to roll the dice? [Y/N]? : ")
if diceyn == "Y":
print ("Let's do this!")
rollIt()
again = str(input("Do you want to roll again? [Y/N]?: "))
if again == "Y":
print ('Yahoo!')
rollIt()
else:
time.sleep(0.3)
print ('Okay, bye!')
break
elif diceyn == "N":
print ("Oh, Okay. Maybe next time.")
break
input_name = input ("What is your name: ")
print ("Greetings ",input_name,"!", sep='')
time.sleep(1)
diceroll()
Here is the Object Oriented approach:
import random
import time
class Rolling_Dice_Game () :
def startup (self) :
prompt = ("Would you like to roll the dice? [Y/N]? : ")
if self.query_user (prompt) == 'Y' :
self.run_the_game ()
return True
else : return False
def run_the_game (self) :
print ("Let's do this")
print ('Rolling...')
time.sleep (1)
rand = random.randint (1, 6)
print ('You rolled a ', rand, '!')
time.sleep (0.5)
return True
def query_user (self, prompt) :
return input (prompt) [0].upper ()
def continue_the_game (self) :
prompt = ("Do you want to roll again? [Y/N]?: ")
if self.query_user (prompt) != 'Y' :
print ('Oh, Okay. Maybe next time.')
return False
else : return True
my_dice = Rolling_Dice_Game ()
if my_dice.startup () == True :
while my_dice.continue_the_game () == True :
my_dice.run_the_game ()

Input needing to be entered twice for my code to work

I'm fairly new to coding and have been assigned a class project, in this project to make a game I was trying to write a function that upon losing/dying the
def playAgain(): function would ask the user if they want to play again.
from sys import exit
def playAgain():
print('Do you want to play again? (yes or no)')
while True:
if input("> ").lower().startswith('yes')== True:
start()
elif input("> ").lower().startswith('no')== True:
print ('Bye for now')
exit(0)
else:
print ("I don't understand what you mean?")
This function 'should' ask the user if they want to play again and depending on if yes or no was entered it would either go to the function start() or exit.
The issue is that when the input is entered the first time it is seemingly ignored in the code and must be entered a second time for any thing to happen in the code.
This has confused me a fair amount so any input on how to resolve this issue would be greatly appreciated.
Side note - this issue doesn't appear to happen when yes is entered first meaning this is probably an issue with the elif or else statements
from sys import exit
def playAgain():
print('Do you want to play again? (yes or no)')
while True:
choice = input("> ")
if choice.lower().startswith('yes'):
start()
elif choice.lower().startswith('no'):
print ('Bye for now')
exit(0)
else:
print ("I don't understand what you mean?")
If you want to write it as a function then really you should return a value upon which to base your next step.
def playAgain():
while True:
ans = input("Do you want to play again? (yes or no) ")
if ans.lower().startswith('y'):
return True
elif ans.lower().startswith('n'):
return False
else:
print ("I don't understand what you mean?")
def start():
print ("game restarted")
if playAgain():
start()
else:
print ("Bye for now")
quit()
Note that startswith allows you to check just y and n rather than the full words yes and no
The solution is to assign a variable to the input and compare the variable as many times as you want.
from sys import exit
def playAgain():
print('Do you want to play again? (yes or no)')
while True:
inp = input("> ").lower()
if inp.startswith('y'):
start()
elif inp.startswith('n'):
print ('Bye for now')
exit(0)
else:
print ("I don't understand, what do you mean?")

Python Maze Game trouble

I'm trying to make a game where you go through a maze and try to escape from a voice, but everytime the player says the wrong answer to one of the questions it says "Game Over" but then carries on where it kept off, I've tried a lot of things and researched, but I can't seem to figure it out, I'm only a beginner
`
import time
import os
print ("Your adventure starts as a young boy, running away from home becuase you're a rebel")
time.sleep(2)
print ("You find the famous labyrinth, do you go in?")
time.sleep(2)
answer = input("Make your choice, Yes OR No")
time.sleep(2)
print ("The answer",answer ,"got you stuck in a hole")
time.sleep(2)
print ("But you find a secret passage")
answer = input("Do you go through the door, Yes or No?")
if answer == "No":
time.sleep(2)
print ("Game Over.")
elif answer == "Yes":
time.sleep(2)
print("You hear a strange voice")
time.sleep(2)
answer = input("What do you say to the Voice, Hello or Who are you?")
if answer == "Hello":
print ("Hello")
elif answer == "Who are you?":
print ("Im your worst nightmare")
time.sleep(2)
print("You try and escape the labyrinth and turn a large gate with a gnome on the over end")
answer = input("Do you open the gate, Yes Or No?")
if answer == "Yes":
time.sleep(3)
print ("Game Over, you get brutally killed by a gnome, good job")
os._exit(0)
elif answer == "No":
time.sleep(3)
print ("You go the other way and see a light at the end of the tunnel")
answer = input("You see your family outside crying and waiting for you, do you go with them?")
if answer == "Yes":
print("You have a nice ending and you're sorry you ran away")
print("You have been graded: ")
elif answer == "No":
print("God smites you for being stupid.")
os._exit(0)`
take this block, for example
print ("But you find a secret passage")
answer = input("Do you go through the door, Yes or No?")
if answer == "No":
time.sleep(2)
print ("Game Over.")
elif answer == "Yes":
time.sleep(2)
print("You hear a strange voice")
time.sleep(2)
# continuation
if the user enters "No" it will print "Game Over" - which I assume is correct. However, control flow in the program continues past the if/else block. What you need to do is exit the program using something like sys.exit() or make sure your control flow only has paths forward if it should i.e. wrapping what happens next in the truthy part of the if/else block
if answer == "No":
time.sleep(2)
print ("Game Over.")
elif answer == "Yes":
time.sleep(2)
print("You hear a strange voice")
time.sleep(2)
# put continuation here

if/elif statements not working in while loop [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 7 years ago.
I'm writing a simple 8ball response program and have an issue. When I run this program but give any option other than "y" or "yes" in response to the variable 'rd', the program thinks I have actually inputted "yes" and goes ahead with the code indented in the 'if' statement with a yes response. Why is this? I can't work out why.
import time
import random
import sys
resp = ["Yes!", "No!", "Maybe!", "Don't be so silly!",
"In your dreams!", "Without a doubt!", "Most likely!",
"Very doubtful!", "I'm going to have to say no this time!",
"What kind of a question is that? Of course not!", "I reckon there's a 20% chance!",
"Better not tell you now", "I've been told by to tell you no...",
"I've been told to tell you yes...", "It's possible!", "More likely to see pigs fly!",
"You wish!", "All signs point to no!", "All signs point to yes!",
"If you truly believe it!"
]
def intro():
print "Hello! Welcome to 8 Ball!\n"
time.sleep(2)
def main():
quit = 0
while quit != "n":
rd = raw_input("Are you ready to play? Enter y/n: ")
if rd.lower() == "y" or "yes":
question = raw_input("\nType your question and please press enter: ")
print "\n"
print random.choice(resp)
print "\n"
quit = raw_input("Do you want to roll again? Enter y/n: ")
elif rd.lower() == "n" or "no":
print "Looks like you need some more time to think. Have a few seconds to think about it.."
time.sleep(3)
quit = raw_input("Are you ready to play now? Enter y/n: ")
else:
print "That wasn't an option. Try again."
rd = raw_input("Are you ready to play? Enter y/n: ")
print "Okay! Thanks for playing."
intro()
main()
>>> bool("yes")
True
"yes" evaluates to true
if rd.lower() in ("y", "yes"):
could be used check to see if the value is 'y' or 'yes'
You can't do if x == a or b in python you have to do x == a or x == b or x in (a, b)
import time
import random
import sys
resp = ["Yes!", "No!", "Maybe!", "Don't be so silly!",
"In your dreams!", "Without a doubt!", "Most likely!",
"Very doubtful!", "I'm going to have to say no this time!",
"What kind of a question is that? Of course not!", "I reckon there's a 20% chance!",
"Better not tell you now", "I've been told by to tell you no...",
"I've been told to tell you yes...", "It's possible!", "More likely to see pigs fly!",
"You wish!", "All signs point to no!", "All signs point to yes!",
"If you truly believe it!"
]
def intro():
print "Hello! Welcome to 8 Ball!\n"
time.sleep(2)
def main():
quit = 0
while quit != "n":
rd = raw_input("Are you ready to play? Enter y/n: ")
if rd.lower() in ("y", "yes"):
question = raw_input("\nType your question and please press enter: ")
print "\n"
print random.choice(resp)
print "\n"
quit = raw_input("Do you want to roll again? Enter y/n: ")
elif rd.lower() in ("n", "no"):
print "Looks like you need some more time to think. Have a few seconds to think about it.."
time.sleep(3)
quit = raw_input("Are you ready to play now? Enter y/n: ")
else:
print "That wasn't an option. Try again."
rd = raw_input("Are you ready to play? Enter y/n: ")
print "Okay! Thanks for playing."
intro()
main()
You can't do this:
if rd.lower() == "y" or "yes":
because it's evaluating "yes" by itself. Instead try:
if rd.lower() == "y" or rd.lower() == "yes":
also consider:
if rd.lower() in ["y", "yes"]:

How do I use 2 loops, and if it is false, repeat the program indefinetely

Right now I am doing the tutorial "Dragon Realm" from this site http://inventwithpython.com/chapter6.html
I understand what it's all doing slightly but that is not my problem. At the end I'm wanting to add a bit of code that if the player says no, it says, as I currently have it, "too bad *!" and move back up to the beginning of the program. I've gotten it to do that, but once it goes through the second time and i get to the input of whether you want to try again whether or not you type yes or no it just ends the program. I've tried multiple combinations of while, if/else, while True, while False and I am not getting the results I am wanting. I don't understand how you just keep it to keep going? It's probably really simple but I can't figure it out.
this is the code for the program.
import random
import time
def displayIntro():
print('You are in a land full of dragons. In front of you,')
print('you see two caves. In one cave, the dragon is friendly')
print('and will share his treasure with you. The other dragon')
print('is greedy and hungry, and will eat you on sight.')
print()
def chooseCave():
cave = ''
while cave != '1' and cave != '2':
print('Which cave will you go into? (1 or 2)')
cave = input()
return cave
def checkCave(chosenCave):
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
friendlyCave = random.randint(1, 2)
if chosenCave == str(friendlyCave):
print('Gives you his treasure!')
else:
print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
caveNumber = chooseCave()
checkCave(caveNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()
You could add simply,
if 'n' in playAgain:
print "too bad"
playAgain = 'yes'
At the end (inside your while loop)
By the way, these two lines can be combined:
print('Do you want to play again? (yes or no)')
playAgain = input()
as simply:
playAgain = input('Do you want to play again? (yes or no)')
Because input will display the string argument when asking for input.

Categories

Resources