def playAgain():
b = input('Do you want to play again? y/n')
if b == ('y'):
def startGame():
startGame()
else:
print('Goodbye!')
time.sleep(1)
sys.exit()
import random
import time
import sys
global shots
shots = 0
while shots <=5:
chanceofDeath =random.randint(1,6)
input('press enter to play Russian roulette.')
if chanceofDeath ==1:
shots = shots + 1
print (shots)
print('You died.')
time.sleep(1)
playAgain()
else:
shots = shots + 1
print (shots)
print ('click')
if shots == 5:
print('You won without dying!')
time.sleep(1)
playAgain()
When I run the program, when it asks to play again or not, if you choose yes it works, but continues from the last shot. For example, if you died on the second shot and played again, instead of restarting, it starts right off at 3. How do I make the shots reset everytime?
The reason why it continues from the last shot is because you never actually set the 'shots' back to 0 this code:
import random
import time
import sys
global shots
shots = 0
is ran only once, meaning shots is never assigned back to 0.
What you want is if the user chooses to play again, the 'shots' variable should be set back to 0. You could edit your playAgain() function to return True if the user wanted to play again. For example:
def playAgain():
b = input('Do you want to play again? y/n')
if b == ('y'):
return True
else:
print('Goodbye!')
time.sleep(1)
sys.exit()
This allows you to check for whether the user wanted to play again in your main while loop and set 'shots' to 0 like this:
if playAgain():
shots = 0
Also as shots is declared outside of any functions and the while loop is the only thing using it, it does not need to be defined as a global variable.
Revised Program
def playAgain():
b = input('Do you want to play again? y/n')
if b == ('y'):
return True
else:
print('Goodbye!')
time.sleep(1)
sys.exit()
import random
import time
import sys
shots = 0
while shots <=5:
chanceofDeath =random.randint(1,6)
input('press enter to play Russian roulette.')
if chanceofDeath ==1:
shots = shots + 1
print (shots)
print('You died.')
time.sleep(1)
if playAgain():
shots = 0
else:
shots = shots + 1
print (shots)
print ('click')
if shots == 5:
print('You won without dying!')
time.sleep(1)
if playAgain():
shots = 0
Also I am unsure of what you wanted your code to do with the following:
def startGame():
startGame()
Hope this helps
Related
For example, this code is not working:
from pynput import keyboard
def on_press(key):
global play
if str(key) == "'x'":
play = 'Play'
play = ''
with keyboard.Listener(on_press = on_press, suppress=True) as listener:
while listener.is_alive(): # infinite loop which runs all time
def pump():
num = 0
while True:
yield num # generator
num += 1
if play == 'Play':
next(gen)
listener.join()
No matter how I put the generator function or using a global variable, I always have a StopIteration: error or others.
I want to control the generator, so I can "play" and "pause" with keyboard keys.
While this code works:
def pump():
num = 0
while True:
yield num
num += 1
gen = pump()
next(gen) #play
next(gen)
I'm so bewildered...
I don't use Jupyter notebooks but I tried the VS Code extension and it seems to work in them as well.
Here is some sample code to prove the generator is working.
from pynput import keyboard
import sys
def on_press(key):
global play
if str(key) == "'x'":
play = 'Play'
# added to provide a way of escaping the while loop
elif str(key) == "'q'":
sys.exit(1)
def pump():
num = 0
while True:
# added as proof your generator is working
print(num)
yield num
num += 1
gen = pump()
play = ''
with keyboard.Listener(on_press=on_press, suppress=True) as listener:
while listener.is_alive():
if play == 'Play':
next(gen)
listener.join()
This will infinitely call next(gen) since there is no way to unset play from "Play" in the code. Once it's set, it will continue infinitely looping and if play == 'Play': will always be True.
Now, onto your example.
This line:
next(gen)
will error.
gen is never defined in your code.
I assume this was just a typo and you have gen = pump() somewhere.
Additionally, defining pump in your loop will almost certainly have unintended consequences.
Suppose you do have gen = pump() immediately after the definition.
play will be set to "Play" when you press the x key. You will continuously call next(gen).
However, this time after each loop pump will be redefined and num will be set to 0. It will yield the 0 and continue to do so infinitely.
So what did you mean to do?
Probably something like this:
from pynput import keyboard
import sys
def on_press(key):
global play
if str(key) == "'x'":
play = 'Play'
elif str(key) == "'q'":
sys.exit(1)
def pump():
global play
num = 0
while True:
play = ''
print(num)
yield num
num += 1
gen = pump()
play = ''
with keyboard.Listener(on_press = on_press, suppress=True) as listener:
while listener.is_alive():
if play == 'Play':
next(gen)
listener.join()
Personally, I would avoid the use of globals.
However this, calls the next(gen) once with the x key press. The generator sets play back to "" avoiding subsequent calls of next(gen) until x is pressed again.
I am working on a very simple 'game' where the player gets 5 guesses to guess a random number.
It's not done yet but I have run into a couple of problems.
This is the code that generates a random number and allows the player to guess
Relevant code:
def GuessLoopFunc(guess):
import random
import sys
import time
sum_guesses = 0
rand_num = random.randrange(1, 21)
print(rand_num)
#This is just for test purposes to know the correct number and see what happens when I guess the correct number
while True:
if guess == rand_num:
print("You got it right!")
else:
sum_guesses += 1
if sum_guesses == 4:
guess = input("That's incorrect...final guess: ")
continue
elif sum_guesses == 5:
print("Oh no! You lost!")
while True:
replay = input("Do you want to play again: ")
if replay == "yes" or replay == "Yes":
pass #Temporary while I figure out how to loop back to very start (new random number)
elif replay == "no" or replay == "No":
print("Goodbye")
break
else:
print("I do not understand what you mean...")
continue
else:
guess = input("You got it wrong, guess again: ")
continue
As you can see by the comments I made, I want the game the return to the very start of the program if the player indicates they want to play again (so they get a new random number.
Also, for some reason, the game doesn't register when the correct answer was given and keeps on telling the player that his answer was incorrect...this is the code of the game where the above module is called:
import sys
import random
import time
from GuessLoop import GuessLoopFunc
print("Hello! Welcome to the guess the number game!")
name_player = input("Please enter your name: ")
print("Hello " + str(name_player) + "!")
play = input("Are you ready to play? ")
if play == "Yes" or play == "yes":
print("Great! Let's get started...")
elif play == "No" or play == "no":
print("Too bad...")
sys.exit()
else:
print("I do not understand your response...")
quit1 = input("Do you want to quit? ")
if quit1 == "yes" or quit1 == "Yes":
sys.exit()
elif quit1 == "no" or quit1 == "No":
print("Great! Let's get started!")
else:
print("I do not understand your response...quitting.")
sys.exit()
print("I am going to think of think of a number between 1 and 20...")
print("You will get 5 guesses to guess the number...")
time.sleep(1)
print("Okay, I have a number in mind")
guess = input("What is your guess? ")
GuessLoopFunc(guess)
time.sleep(1)
sys.exit()
Finally, when I try to run the program in Sublime Text it doesn't run further than the "Please enter your name: " part. If I fill in my name and press enter, nothing happens...but no error message displays either. So I have resorted to testing the program in the Python IDLE every time, but it's a bit tedious...anyone know what's up.
Your main problem is that you compare your userinput (a string) with a random number (integer) - they will never be the same as string != int.
Solution:
You need to convert the user input to a number via the int(text) function.
def getInt(text):
while True:
try:
n = input(text)
return int(n)
except ValueError: # if the input is not a number try again
print(f"{n} is not a number! Input a number")
....
guess = getInt("What is your guess?") # now that is an int
....
You have lots of duplicate "yes/no" codeparts that you can streamline:
def YesNo(text):
'''Ask 'test', returns True if 'yes' was answerd else False'''
while True:
answer = input(text).strip().lower()
if answer not in {"yes","no"}:
print("Please answer 'yes' or 'no'")
continue # loop until yes or no was answered
return answer == "yes"
This reduces
quit1 = input("Do you want to quit? ")
if quit1 == "yes" or quit1 == "Yes":
sys.exit()
elif quit1 == "no" or quit1 == "No":
print("Great! Let's get started!")
to
if YesNo("Do you want to quit? "):
sys.exit()
else:
pass # do somthing
and use that in all yes/no questions.
To play again I would move the "Do you want to play again" question out of the game loop:
# do your name questioning and greeting here
# and then enter an endless loop that you break from if not playing again
while True:
GuessLoopFunc() # move the guess input inside the GuessLoopFunk as it has
# to be done 5 times anyhow. If you spend 5 guesses or
# guessed correctly, print some message and return to here
if YesNo("Play again? "):
continue
else:
break # or sys.exit()
To fix the sublime problem: Issue with Sublime Text 3's build system - can't get input from running program
After I finish my hangman game, when I clear the console, it clears everything. However, I want it to not clear the menu. How do I fix this?
Here is my code:
import random, os
import time
print("^^^^^^^^^^THIS IS HANGMAN^^^^^^^^^^")
print("1. Play Game ")
print("2. Quit Game ")
choice = input("Please enter option 1 or 2")
if choice == "1":
words = ["handkerchief", "accommodate", "indict", "impetuous"]
word = random.choice(words)
guess = ['_'] * len(word)
guesses = 7
while '_' in guess and guesses > 0:
print(' '.join(guess))
character = input('Enter character: ')
if len(character) > 1:
print('Only enter one character.')
continue
if character not in word:
guesses -= 1
for i, c in enumerate(word):
if c == character:
guess[i] = character
if guesses == 0:
print('You LOST!')
break
else:
print('You have only', guesses, 'chances left to win.')
else:
print(''.join(guess))
print('You WON, well done')
time.sleep(2)
import os
os.system('clear')
I don't know how to make the code so that it only clears down to the menu
simply wrap your menu in a function
def menu():
print("^^^^^^^^^^THIS IS HANGMAN^^^^^^^^^^")
print("1. Play Game ")
print("2. Quit Game ")
and reprint it after you clear the console
import os
os.system('clear')
menu()
if you want your menu to still work after the clear, just include all the code you use to make your menu work into the menu() function. Good luck on your project
I am making a console app and I would like a loader animation, for example 3 dots that appear one at a time until it reaches the third dot then restarts the loop and does it all over again. Could someone show me how to do this please?
You could run the loop in a background thread:
import threading
import time
import sys
should_quit = False
num_dots = 3
def print_dots():
count = 0
while not should_quit:
time.sleep(.25)
if 0 == count % num_dots:
print(f"\r{' ' * num_dots}\r", end='')
print('.', end='')
sys.stdout.flush()
count += 1
t = None
try:
t = threading.Thread(target=print_dots)
t.daemon = True
t.start()
except:
print("Error: unable to start thread")
try:
input()
except KeyboardInterrupt:
pass
should_quit = True
t.join()
When i went from python 2.7 to python 3.5 I started having problem with ELIF statement.
I am using PyCharm so when i enter elif statement it shows an error and this1
this is what jumps up as error solution
and when I press it this happens but code still doesn't works...
doesn't let me post this pic, it will be in comments
Anyways, i cant post code for some reason so it will be in comments if you need him and please help me if you can because this is not first time happening, I can't find help anywhere and well it's really annoying...
Your first error is not having an initial if statement as well as having game = '1': instead of game == '1':. If you look at my code I have fixed these errors and fixed the indentation as it was causing some bugs
import os
print("\nWelcome, enter Your name please")
name = input("--> ")
def username(name): #NAME
while len(name) < 2:
print("There was an error")
name = input("\nPlease enter Your name again -->")
else:
print("Hello,", name)
username(name)
def menu(): #MENU
print("\nWelcome to the menu")
print("From here You can chose the game")
print("For now, we have only 3 game but there will be plenty more!")
print("Chose game by it's number ")
print("1 - Coin flip| 2 - Horse racing| 3 - Loto|")
menu()
game = int(input("--> "))
def choice(game): #CHOOSING GAME
while game > 3 or game < 1:
print("\nSomething went wrong, enter game you want again (only numbers 1, 2, 3!")
game = int(input("--> "))
if game == '1': #if statement first and two "=" signs
print("You chose Coin flip game")
os.system('python coinflip.py')
elif game == '2': #use tab to indent properly
print("You chose Horse racing game")
os.system('python horseracing.py')
elif game == '3': #keep indentations the same throughout
print("You chose Loto game")
os.system("python loto.py")
choice(game)
You need to firstly type "if" and the "elif". So it should be something like that:
def choice(game): #CHOOSING GAME
while game > 3 or game < 1:
print("\nSomething went wrong, enter game you want again (only numbers 1, 2, 3!")
game = int(input("--> "))
if game == '1': #bug here
print("You chose Coin flip game")
os.system('python coinflip.py')
elif game == '2': #and here
print("You chose Horse racing game")
os.system('python horseracing.py')
elif game == '3': #and here
print("You chose Loto game")
os.system("python loto.py")