Guess the number, play again - python

I'm making a guess the number game. My code is almost complete but I need to make it so that the program asks the player if they want to play again and then restarts. Could someone help me with how I should go about that? I tried making a new function ex. def game_play_again and then call the game_play() function but it's not reseting the attempts which leads to it not looping correctly.
This is my code right now
import random
MIN = 1
MAX = 100
attempts = 5
win = False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
#print game instructions
def game_start():
print(f"Im thinking of a number between {MIN} and {MAX}. Can you guess it within
{attempts} attempts? ")
input("Press enter to start the game ")
#process user input
def game_play():
global number, attempts, last_hint, win
while attempts > 0:
print()
print(f"You have {attempts} {'attempts' if attempts > 1 else 'attempt'} left.")
if attempts == 1:
print(f"This is your last chance. So i'll give you one more hint. Its's an {last_hint} number.")
while True:
try:
guess = int(input("Try a lucky number: "))
if guess in range(MIN, MAX+1):
break
else:
print(f"Please enter numbers between {MIN} and {MAX} only!")
except ValueError:
print("Plese enter numbers only!")
if guess == number:
win = True
break
if attempts == 1:
break
if guess > number:
if guess-number > 5:
print("Your guess is too high. Try something lower.")
else:
print("Come on you are very close. Just a bit lower.")
else:
if number-guess > 5:
print("Your guess is too low. Try something higher.")
else:
print("Come on you are very close. Just a bit higher.")
attempts -= 1
#print game results
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
game_start()
game_play()
game_finish(win)

You can simply reset your variables to initial values and then call game_play()
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
want_play_again = int(input("Want play again? [1-Yes / 2-No]"))
if want_play_again == 1:
game_play_again()
else:
print("Bye")
/
def game_play_again():
attempts = 0
win = False
game_play()

Within a while(True) loop, write a menu driven statement asking the user if they want to repeat. If they do, initialise values and call game methods. If they do not, break the loop.
pseudocode:
while(True):
choice = input('play again? y/n)
if choice=='y':
attempts, win = 5, False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
game_start()
game_play()
game_finish()
elif choice=='n':
break
else:
print('invalid input')
The above code should be in main, with all methods within its scope.
Better yet, in place of all the initializations, add an init() method declaring them and call them when necessary.
The indentation in the code you have submitted is faulty, so I'm not sure if a related error is involved.

Related

How to loop a simple game to continue until user stops it not using a break?

def set_number():
import random
return random.randint(1,500)
#This function plays the game
def number_guessing_game(number):
guess_counter = 0
guess = int(input("Enter a number between 1 and 500."))
while guess != number:
guess_counter += 1
if guess > number:
print(f"You guessed too high. Try Again!")
guess = int(input("Enter a number between 1 and 500."))
elif guess < number:
print(f"You guessed too low. Try Again!")
guess = int(input("Enter a number between 1 and 500."))
if guess == number:
print(f"You guessed the number! Good Job.!")
again = str(input("would you like to play again? Enter 'y' for yes or 'n' to close the game."))
def main():
print(f"Welcome to the Number Guessing Game!\n" +
f"You will have unlimited guesses. The number is between 1 and 500.\n" +
f"Good Luck!")
number = set_number()
guess_count = number_guessing_game(number)
main()
I am working on a simple game project for my coding class. I am not good at coding at all. I came up with this part of the program, I just cannot figure out how to loop the entire number_guessing_game function until the user enters 'n' to stop it, I can't use a break because we did not learn it in the class and I will receive a 0 if I use a break.
I tried nesting a while loop inside of the function but I know I did it wrong.
Instead of using break use return.
def main():
print(f"Welcome to the Number Guessing Game!\n" +
f"You will have unlimited guesses. The number is between 1 and 500.\n" +
f"Good Luck!")
while True:
number = set_number()
number_guessing_game(number)
again = input("would you like to play again? Enter 'y' for yes or 'n' to close the game.")
if again == 'n':
return
main()
You will probably want to remove the last line of the number_guessing_game function if you use this approach
First, your code is assuming the return of input is an integer that can be converted with int(). If you were to give it 'n' your program will crash.
Instead you could use the string class method isdigit() to see if the input was an integer value and then make a logical decision about it. Also note you do not need to convert the return from input to a str() as it is already a str type. You can confirm this with a print(type(input("give me something")))
guess = input("Enter a number between 1 and 500. 'n' to quit"))
if guess.isdigit():
[your code to check the value]
elif ('n' == guess):
return
else:
print(f"You entered an invalid entry: {guess}. Please re-enter a valid value")
If you dont like the idea of using 'return' you could change your while loop to look something like:
while(('n' != guess) or (guess != number)):
If you want the function body looping continuously you could have some code like:
def number_guessing_game(number):
exit_game = False
guess_counter = 0
while(exit_game != True):
guess = input("Enter a number between 1 and 500.))
guess_counter += 1
if guess.isdigit():
if int(guess) > number:
print("You guessed too high. Try Again!")
elif int(guess) < number:
print("You guessed too low. Try Again!")
elif int(guess) == number:
print("You guessed the number! Good Job.!")
again = input("would you like to play again? Enter 'y' for yes or 'n' to close)
if ('n' == again):
exit_game = True
else:
print("Error, please enter a valid value")

creating a python number guessing game

SUPER new to programming so bear with me, please. I am taking my first ever programming class and for a project, I was given a list of requirements I need to fulfill, creating a simple number guessing game has been the only thing I've not had a lot of trouble with so I decided to give it a go.
(i need 1 class, function, dictionary or list, for loop, and while loop) What I, well at least have tried to make is a guessing game that gives a limit of 2 guesss for a # between 0 and 10, any help would be greatly appreciated. :)
import random
class Player:
player = ""
playerscore = 0
def gamestart(self):
self.number = random.randint(0,7)
self.guesss = 0
self.list = []
self.limit = 3
print()
print("Guess what number I'm thinking off")
print()
print("Might even give you a hit if you do well enough")
print()
while self.limit > 0:
self.player_guess = int(input("Well? What are you waiting for? Start guessing:"))
print()
if self.player_guess > 7 or self.player_guess < 0:
print("Wow that was a terrible guess, think harder or we might be here all week long")
print("also,", self.player_guess , "is not in the range...")
print("Becareful though, you only have", self.limit, "guesss left")
elif self.player_guess > self.number:
self.guesss += 1
self.limit-= 1
print("WRONG")
print(self.player, "You only have", self.limit, "guesss left")
self.list.append(self.player_guess)
elif self.player_guess < self.number:
self.guesss += 1
self.limit -= 1
print("oh oh... wrong again!")
print()
print(self.player, "You only have", self.limit, "guesss left.")
self.list.append(self.player_guess)
else:
self.limit -= 1
self.playerscore += 1
self.list.append(self.player_guess)
print()
print("wow, you actually got it right")
print()
print(self.player_guess, "IS THE CORRECT ANSWER!")
print()
print("you only had",self.limit,"left too...")
print("Lets see all the numbers you guessed")
print()
for i in self.list:
print(i)
self.list.clear()
I found the question confusing, however the following code should work as a number guessing game, hope I answered your question.
import random
game = "true"
guesses = 2
while game == "true":
comp_number = int(random.uniform(1,8))
print("I have randomly selected a number between 1 and 7 (inclusive), you have 2 attempts to guess the number.")
while guesses > 0:
if guesses == 2:
turn = "first"
else:
turn = "final"
guess = int(input("Please submit your "+turn+" guess:"))
while guess < 1 or guess > 7:
print("Invalid guess, remember my number is between 1 and 7 (inclusive)")
guess = int(input("Resubmit a valid guess:"))
if guess == comp_number:
print("Congratulations you guessed my number, you win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break
else:
print("Incorrect number, try again.")
guesses -= 1
print("You where unable to guess my number, I win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break

How do i add a timer that counts down and when it runs out it restarts my program

I'm a very new beginner coder and I don't know much yet. I am trying to create a guessing game, and I want to add a timer to the program.
The way the timer would work would be that I set up a set amount of time i.e. 60 seconds and once the time has run out the program would stop and basically be like "sorry you ran out of time. Would you like to try again?"
I've already searched for some videos on YouTube and on Stackoverflow but I either don't understand it or I'm unable to do it.
https://www.youtube.com/watch?v=Mp6YMt8MSAU
I've watched this video like 4 times and still have no clue how to do it. So if anyone is willing to explain to me/show me how to add time that would be much appreciated
def main():
import random
n = random.randint(1, 99)
chances = 5
guess = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: " ))
while n != "guess":
chances -=1
if chances ==0:
print("out of chances, it is now player 2's turn to play. The number was", n)
break
if guess < n:
print("guess is low you have",chances,"chances left")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high you have",chances, "chances left")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it and have", chances, "chances left")
break
import random
n1 = random.randint(1, 99)
chances1 = 0
guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: "))
while n1 != "guess":
chances1 +=1
if chances1 ==5:
print("out of chances, the number was", n1)
break
if guess1 < n1:
print("guess is low you have",chances1,"chances left")
guess1 = int(input("Enter an integer from 1 to 99: "))
elif guess > n1:
print ("guess is high you have",chances1, "chances left")
guess1 = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it and have", chances1, "chances left")
break
retry=input("would you like to play again? (please choose either 'yes' or 'no' )")
if retry == "yes":
main()
elif retry == "no":
print("Okay. have a nice day! :D ")
else:
print("Invalid input")
main()
This is my code. Any feedback would be appreciated.
(I don't know how much do you know about python and programming so I'll use a really simple language)
Well, if your game don't have to run while the timer is active you could use the sleep function of the time library, and writhing something like this:
import time
time.sleep("time amount")
print("I'me sorry but you run out of time!")
print("Do you wanna retry ?")
Whit the "command" time.sleep, python will stop the entire program for the amount of time you've selected
(So if you have to play the game while the timer is running don't use the time.sleep method)
Instead if the timer have to be active while you're playing the game you should use "threading".
threading is a library that allows you to do really simple timers, but not only.
Making a timer with threading it could be more complex for you but not really.
You have to write a function to call when the timer is over like that:
def time_over():
print("I'm sorry but the time is over !")
print("Do you want to play again ? ")
After that you have to create the timer:
timer_name = threading.timer("time amount", function)
Eventually you have to start the timer writing:
timer_name.start()
In that way python will:
1 - Import the threading Library
2 - Create the timer whit the amount of time do you want
3 - Start the timer
4 - Activate the function you've wrote when the time will run out
If you need more info about one of these methods, write a comment and I will answer to your question as faster as I can.
Have a good day :)
To solve your problem, you will have to use a Thread. I took your code I added the Thread at the beginning, try to have a look.
A Thread is an object that can execute a function (its run function) beside the main program. It is so-called Parallel Programming.
Here you need that because you want to:
Check the Input of the player
Count Down
I do not correct your code or rewrite it, I just added the Thread and make it work. It is pretty easy:
I call sleep for a given amount of time (_TIME_LIMIT]
Make a little noise when the timer ended.
I set a variable to True, that means that the timer ended
With a bit of rewriting, you will be able to interrupt your main loop when the Thread change the variable. But that is out the scope of the initial question, feel free to improve your game.
For the moment, you need to enter a number to know if the time was ended or not. That is why I added the little noise (if not you would have no cue).
Please, be free to ask any questions.
Hope this will help you.
from threading import Thread
from time import sleep
import random
_TIME_OUT = [False, False]
_TIME_LIMIT = 1
class MyThread(Thread):
def __init__(self, time_out, player):
Thread.__init__(self)
self.time_out = time_out
self.player = player
def run(self):
sleep(self.time_out)
_TIME_OUT[self.player - 1] = True
print('\a', end="") # Make a noise
def main():
_TIME_OUT[0] = False
_TIME_OUT[1] = False
tread_1 = MyThread(_TIME_LIMIT, 1)
n = random.randint(1, 99)
chances = 5
tread_1.start()
print(f"You have {_TIME_LIMIT} sec")
guess = int(input("Player 1 please enter an integer from 1 to 99, you have 5 chances: " ))
while n != "guess" and not _TIME_OUT[0]:
print(not _TIME_OUT, _TIME_OUT)
chances -=1
if chances == 0:
print("out of chances, it is now player 2's turn to play. The number was", n)
break
if guess < n:
print("guess is low you have",chances,"chances left")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high you have",chances, "chances left")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it and have", chances, "chances left")
break
if _TIME_OUT[0]:
print("Sorry, out of time!")
tread_2 = MyThread(_TIME_LIMIT, 2)
n1 = random.randint(1, 99)
chances1 = 0
tread_2.start()
print(f"You have {_TIME_LIMIT} sec")
guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: "))
while n1 != "guess" and not _TIME_OUT[1]:
chances1 +=1
if chances1 ==5:
print("out of chances, the number was", n1)
break
if guess1 < n1:
print("guess is low you have",chances1,"chances left")
guess1 = int(input("Enter an integer from 1 to 99: "))
elif guess > n1:
print ("guess is high you have",chances1, "chances left")
guess1 = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it and have", chances1, "chances left")
break
if _TIME_OUT[1]:
print("Sorry, out of time!")
retry=input("would you like to play again? (please choose either 'yes' or 'no' )")
if retry == "yes":
main()
elif retry == "no":
print("Okay. have a nice day! :D ")
else:
print("Invalid input")
if __name__ == "__main__":
main()

Trying to get the number of tries to start at 1 and not 0

Whenever you run the game and start guessing it asks first what is guess #0? I'm trying to get it to display "what is guess #1?" but. at the same time keep the number of guesses equal to the number guessed (if that makes sense). Here's my code so far:
import random
def play_game(name, lower=1, upper=10):
secret = random.randint(lower, upper)
tries = 0
print("-----------------------------\n"
"Welcome, {}!\n"
"I am thinking of a number\n"
"between {} and {}.\n"
"Let's see how many times it\n"
"will take you to guess!\n"
"-----------------------------".format(name, lower, upper))
# Main loop
guessing_numbers = True
while guessing_numbers:
guess = input("What is guess #{}?\n".format(tries))
while not guess.isdigit():
print("[!] Sorry, that isn't a valid input.\n"
"[!] Please only enter numbers.\n")
guess = input("What is guess #{}?\n".format(tries))
guess = int(guess)
tries += 1
if guess < secret:
print("Too low. Try again!")
elif guess > secret:
print("Too high. Try again!")
else:
guessing_numbers = False
if tries == 1:
guess_form = "guess"
else:
guess_form = "guesses"
print("--------------------------\n"
"Congratulations, {}!\n"
"You got it in {} {}!\n"
"--------------------------\n".format(name,tries,guess_form))
if tries < 3:
# Randomly chooses from an item in the list
tries_3 = ["Awesome job!","Bravo!","You rock!"]
print (random.choice(tries_3))
# ---
elif tries < 5:
tries_5 = ["Hmmmmmpff...","Better luck next time.","Ohhh c'mon! You can do better than that."]
print (random.choice(tries_5))
elif tries < 7:
tries_7 = ["You better find something else to do..","You can do better!","Maybe next time..."]
print (random.choice(tries_7))
else:
tries_8 = ["You should be embarrassed!","My dog could do better. Smh...","Even I can do better.."]
print (random.choice(tries_8))
choice = input("Would you like to play again? Y/N?\n")
if "y" in choice.lower():
return True
else:
return False
def main():
name = input("What is your name?\n")
playing = True
while playing:
playing = play_game(name)
if __name__ == "__main__":
main()
I have the number of "tries" set to 0 at the beginning. However, if I set that to 1 then play the game and it only takes me 3 tries it will display that it took me 4 tries. so I'm not sure what to do. Still somewhat new to python so I would love some help
Anywhere that you have input("What is guess #{}?\n".format(tries)), use guess = input("What is guess #{}?\n".format(tries+1)). (adding +1 to tries in the expression, but not changing the variable itself)

Why wont this program stop after I press 'n'?

Why wont this stop when 'n' is entered?
I've tried using break on the bottom else but I get errors doing that. That's a common problem I have with break. I have no idea why I'm thrown off with break.
import random
def game():
secret_num = random.randint(1, 10)
guesses = []
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 and 10: "))
except ValueError:
print("{} isn't a number".format(guess))
else:
if guess == secret_num:
print("You got it! The number was {}.".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower than {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it! My number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/n ")
if play_again.lower() != 'Y':
game()
else:
print("Bye!")
game()
You convert play_again to a lower-case letter but compare it to an upper-case letter.
You could simply change it to:
if play_again.lower() != 'n': # 'y' was wrong, right?
game()
else:
print("Bye!")
return # works also without the explicit return but it makes the intention clearer.

Categories

Resources