random int doesnt add up in my while loop - python

Subtracting or adding doesnt work in this loop
Tried changing into return but it didnt work for me . Im a noob ...
from random import randint
import time
def Guess2(n):
randomNo=randint(0,n)
print("This time you will choose a number, and the Computer will attempt to guess your number!")
print("Hello, what is your name:")
myName=str(input())
print("Alright "+myName+", "+"I will start to guess your number now!"+"\nchoose it, I will close my eyes.")
number=int(input())
time.sleep(2)
print("Okay, I will open my eyes now!")
time.sleep(2)
print("Can I start guessing now? Just answer with 'no' , 'yes'")
Answer=str(input())
if Answer[0:]=="no":
time.sleep(1)
print("all this for nothing.. bye")
if Answer[0:]=="yes":
time.sleep(1)
print("Alright let's go!")
time.sleep(1)
print("my first guess is: ",randomNo)
while number !=randomNo:
Userinput=input()
if Userinput=="too big":
print("okay, ",randomNo-1)
if Userinput=="too small":
print("okay, ",randomNo+1)
if Userinput=="richtig":
print("I win!")
It should add up +1 or -1 to the result from before. Maybe you could give me some advice aswell how to get to the number to be guessed faster :)

This is the refined version, but with a zoning algorithm. Try it.
import time
from random import randint
def Guess2():
toosmall = []
toobig = []
print("This time you will choose a number, and the Computer will attempt to guess your number!")
print("Hello, what is your name:")
myName=str(input())
print("Alright "+myName+", "+"I will start to guess your number now!"+"\nchoose it, I will close my eyes.")
number = int(input())
time.sleep(2)
print("Okay, I will open my eyes now!")
time.sleep(2)
print("Can I start guessing now? Just answer with 'no' , 'yes'")
Answer=str(input())
if Answer[0:]=="no":
time.sleep(1)
print("all this for nothing.. bye")
if Answer[0:]=="yes":
time.sleep(1)
print("Alright let's go!")
time.sleep(1)
if number > 0:
randomNo = randint(-1 * number, number + int(number/2))
elif number > -14 and number < 0:
randomNo = randint(0, number + (-2 * number))
else:
randomNo = randint(number - int(number/2), -1 * number)
print("my first guess is: ",randomNo)
while number !=randomNo:
Userinput=input()
toobig.append(number + 10000)
toosmall.append(number - 10000)
if min(toobig) - 2 == max(toosmall):
print(f"Your number is {max(toosmall) + 1}")
exit()
else:
if Userinput=="too big":
toobig.append(randomNo)
randomNo = randomNo - randint(1, int(abs(number/2)))
if randomNo <= max(toosmall):
randomNo = max(toosmall) + 2
print("okay, ", randomNo)
else:
print("okay, ", randomNo)
if min(toobig) - 2 == max(toosmall):
print(f"Your number is {max(toosmall) + 1}")
exit()
elif Userinput=="too small":
toosmall.append(randomNo)
randomNo = randomNo + randint(1, int(abs(number/2)))
if randomNo >= min(toobig):
randomNo = min(toobig) - 2
print("okay, ", randomNo)
else:
print("okay, ", randomNo)
if min(toobig) - 2 == max(toosmall):
print(f"Your number is {max(toosmall) + 1}")
exit()
elif Userinput=="richtig":
print("I win!")
Guess2()

nvm it works now. I overwrote my randomNo after each loop and now it finally takes the new RandomNo each time now.
from random import randint
import time
def Guess2(n):
randomNo=randint(0,n)
print("This time you will choose a number, and the Computer will attempt to guess your number!")
print("Hello, what is your name:")
myName=str(input())
print("Alright "+myName+", "+"I will start to guess your number now!"+"\nchoose it, I will close my eyes.")
number=int(input())
time.sleep(2)
print("Okay, I will open my eyes now!")
time.sleep(2)
print("Can I start guessing now? Just answer with 'no' , 'yes'")
Answer=str(input())
if Answer[0:]=="no":
time.sleep(1)
print("all this for nothing.. bye")
if Answer[0:]=="yes":
time.sleep(1)
print("Alright let's go!")
time.sleep(1)
print("my first guess is: ",randomNo)
while number!=randomNo:
Userinput=input()
if Userinput=="too big":
x1=randomNo-1
print(x1)
randomNo=x1
if Userinput=="too small":
x1=randomNo+1
print(x1)
randomNo=x1
if Userinput=="richtig":
print("I win!")

Related

Python guessing game code keeps crashing after 1 guess. How would i fix this?

My code keeps crashing after I put in the 1st guess I make. I've looked at syntax and dont think that's a problem how do I make it so it goes past the 1st guess and executes it. When I put the guess in it just puts in all the prompts at once, and how do I call the function properly at the end? Any help would be appreciated.
Import time,os,random
def get_int(message):
while True:
user_input = input(message)
try:
user_input = int(user_input)
print('Thats an integer!')
break
except:
print('That does not work we need an integer!')
return user_input
def game_loop():
fin = False
while not fin:
a = get_int('give me a lower bound:')
b = get_int('give me a upper bound:')
if a < 0:
print("that doesn't work")
if a > b:
a, b = b, a
print(a,b)
os.system('clear')
print("The number you guess has to be between " + str(a) + "and " + str(b) + '.')
num_guesses = 0
target = random.randint(a,b)
time_in = time.time()
while True:
print('You have guessed ' + str(num_guesses) + " times.")
print()
guess_input = get_int('guess a number')
if guess_input == target:
print("Congrats! You guessed the number!")
time_uin = time.time()
break
elif guess_input < a or guess_input > b:
print("guess was out of range... + 1 guess")
elif guess_input < target:
print("Your guess was too low")
else:
print("Your guess was to high")
num_guesses = num_guesses + 1
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
while True:
play_again = input ('Type y to play again or n to stop')
print()
if play_again == 'n':
fin = True
print('Thank God')
time.sleep(2)
os.system('clear')
break
elif play_again == 'y':
print('here we go again')
time.sleep(2)
os.system('clear')
break
else:
print('WRONG CHOCICE')
break
game_loop()
If guess_input != target on the first iteration of the loop, time_uin is referenced before assignment. Hence the error:
UnboundLocalError: local variable 'time_uin' referenced before assignment
Solution is to run the following only if guess_input == target.
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
Please follow coppereyecat's link to learn how to debug a basic Python program.

I am trying to replay the game when I run out of guesses (Play again when I run out of gusses or find the right answer)

I am trying to reply to this game and store the count in the passed memory but, any time I run the code again the game starts from scratch and the previous score is lost.
How can I store and continue from the past round.
import random
MAX_GUESSES = 5 #max number of guesses allowed
MAX_RANGE = 20 #highest possible number
#show introductionpygame
print("welcome to my franchise guess number game")
print("guess any number between 1 and", MAX_RANGE)
print("you will have a range from", MAX_GUESSES, "guesses")
#choose random target
target = random.randrange(1, MAX_RANGE + 1)
#guess counter
guessCounter = 0
#loop fovever
while True:
userGuess = input("take a guess:")
userGuess =int(userGuess)
#increment guess counter
guessCounter = guessCounter + 1
#if user's guess is correct, congratulate user, we're done
if userGuess == target:
print("you got it la")
print("it only took you",guessCounter, "guess(es)")
break
elif userGuess < target:
print("try again, your guess is too low.")
else:
print(" your guess was too high")
#if reached max guesses, tell answer correct answer, were done
if guessCounter == MAX_GUESSES:
print(" you didnt get it in ", MAX_GUESSES, "guesses")
print("the number was", target)
break
print("Thanks for playing ")
#main code
while True:
playOneRound() #call a function to play one round of the game
goAgain = input("play again?(press ENTER to continue, or q to quit ):")
if goAgain == "q":
break
you forgot to mention the function name playOneRound. The code below works fine.
import random
MAX_GUESSES = 5 # max number of guesses allowed
MAX_RANGE = 20 # highest possible number
# show introductionpygame
print("welcome to my franchise guess number game")
print("guess any number between 1 and", MAX_RANGE)
print("you will have a range from", MAX_GUESSES, "guesses")
def playOneRound():
# choose random target
target = random.randrange(1, MAX_RANGE + 1)
# guess counter
guessCounter = 0
# loop fovever
while True:
userGuess = input("take a guess:")
userGuess = int(userGuess)
# increment guess counter
guessCounter = guessCounter + 1
# if user's guess is correct, congratulate user, we're done
if userGuess == target:
print("you got it la")
print("it only took you", guessCounter, "guess(es)")
break
elif userGuess < target:
print("try again, your guess is too low.")
else:
print(" your guess was too high")
# if reached max guesses, tell answer correct answer, were done
if guessCounter == MAX_GUESSES:
print(" you didnt get it in ", MAX_GUESSES, "guesses")
print("the number was", target)
break
print("Thanks for playing ")
# main code
while True:
playOneRound() # call a function to play one round of the game
goAgain = input("play again?(press ENTER to continue, or q to quit ):")
if goAgain == "q":
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()

Im trying to add a countdown timer in the background so that when time runs out the program is terminated

I am creating a 2 player number guessing game in python 3.8. I want a countdown timer to run in the background so that the program is terminated when time runs out, but its not working. I have tried using a solution I found online but the program does not get terminated.
declaring all the variable and modules
import random
guess=""
Gamewinner=0
n = random.randint(1, 99)
lives = 8
answer = "yes"
print("You have a total of 8 lives. A wrong guess would result in one less life.")
SingleOrDouble=input("Do you want single player or double player?")
from time import *
import threading
The solution that I found online
def countdown():
global my_timer
my_timer=5
for x in range(5):
my_timer=my_timer-1
sleep(1)
print("Out of time")
countdown_thread=threading.Thread(target=countdown)
countdown_thread.start()
main program
while my_timer>0:
if SingleOrDouble=="Single":
while answer=="yes" or answer=="Yes":
while lives!=0 and n!=guess:
guess = int(input("Enter an integer from 1 to 99: "))
if guess < n:
print("guess is low")
lives-=1
print("You have "+ str(lives) +" lives left.")
elif guess > n:
print ("guess is high")
lives-=1
print("You have "+ str(lives) +" lives left.")
else:
print("You guessed it!")
print("You won with "+ str(lives) +" lives left.")
break
print("Game over, the number was "+ str(n))
answer = input("Do you want to play again?")
if answer=="yes" or answer=="Yes":
lives=8
else:
lives=16
while answer=="yes"or answer=="Yes":
while lives!=0 and n!=guess:
if lives%2==0:
guess = int(input("Player 1 please Enter an integer from 1 to 99: "))
else:
guess = int(input("Player 2 please Enter an integer from 1 to 99: "))
if guess < n:
print("guess is low")
lives-=1
print("You have "+str(lives//2)+" lives left.")
elif guess > n:
print ("guess is high")
lives-=1
print("You have "+ str(lives//2) +" lives left.")
else:
if lives%2==0:
print("Player 1 guessed it!")
print("You won with "+ str(lives//2) +" lives left.")
Gamewinner=2
else:
print("Player 2 guessed it!")
print("You won with "+ str(lives//2) +" lives left.")
Gamewinner=1
break
if Gamewinner>0:
print("Game Over! Player "+str(Gamewinner)+"the number was "+ str(n))
else:
print("Game Over! The number was "+ str(n))
answer = input("Do you want to play again?")
if answer=="yes" or answer=="Yes":
lives=8
sleep(1)
if my_timer==0:
break
The code for the countdown timer is working just fine. What you could do is - Use a system exit when the timer hits zero so that you could stop the execution of your program.
You would need to use os._exit(1) to terminate your Python program. The modified code would look something like this -
from time import *
import os
import random
import threading
guess=""
Gamewinner=0
n = random.randint(1, 99)
lives = 8
answer = "yes"
print("You have a total of 8 lives. A wrong guess would result in one less life.")
SingleOrDouble=input("Do you want single player or double player?")
def countdown():
global my_timer
my_timer=5
for x in range(5):
my_timer=my_timer-1
sleep(1)
print("Out of time")
os._exit(1)
countdown_thread=threading.Thread(target=countdown)
countdown_thread.start()
I would put the game in a function called game and run it in a daemon thread so that it terminates when the main thread terminates. If N_SECONDS is the number of seconds allotted to the game then the main thread becomes simply:
from threading import Thread
import sys
N_SECONDS = some_value
t = Thread(target=game)
t.daemon = True
t.start()
t.join(N_SECONDS) # block for N_SECONDS or until the game ends by returning
if t.is_alive(): # the game has not returned and is still running
print('Out of time!')
sys.exit(0) # exit and the thread terminates with us
No additional timing is required!

Breaking a loop for basic python

I have been working on this for a while now. I have been able to get parts of this to work, but never the whole thing. The end goal is to loop the user back into another game if they so choose. I think the issue is with my break statement, but I am not sure how to route around it. I have included all my code so that any mistakes can be found. Apologies if this has already been answered, I couldn't find a page with this kind of problem.
def game():
import random
from random import randint
n = randint(1, 10)
print('Enter a seed vlaue: ')
the_seed_value = input(' ')
random.seed(the_seed_value)
guessesTaken = 0
print("what is your name?")
myName = input("")
guess = int(input("Enter an integer from 1 to 99: "))
while n != "guess":
if guess < n:
print ("guess is low")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
else:
print ("Congradulations " + myName + " you guessed it in " + str(guessesTaken) + " guesses!")
break
print('Want to play agian? y/n')
answer = input(" ")
if answer == "n":
print ("Ok, See you next time!")
elif answer == "y":
print("Starting new game!")
game()
def main():
game()
if __name__ == "__main__":
main()
For one, #kerwei notes correctly that your while line has an issue, and needs to be changed from while n != "guess": to while n != guess:.
For two, your while loop is satisfied when the player guesses correctly, bypassing the Congrats line.
Since the game is currently structured to stay in the loop until the player guesses correctly, a simple fix would be to remove the else: line from the loop and place the victory statement afterwards. That is,
def game()
...
while n != guess:
if guess < n:
...
elif guess > n:
...
print('Congrats!')
print('play again?')
...

Categories

Resources