I wrote this code for a guessing game against the computer using the random method. The programme work but when it turns to the user for the second round it can not continue. Can you help, please?
import random
global rand_val
rand_val=random.randint(10,50)
def start():
ans=int(input("Enter a number between 10 and 50: "))
if ans>=10 and ans<=50:
new_rand_val=rand_val-ans
if new_rand_val<=0:
print("You guessed too far, try again\n")
main()
else:
print("Amount left is,",new_rand_val," Now its the Computer turn\n")
comput_turn(new_rand_val)
def comput_turn(new_rand_val):
comp_guess=random.randint(0,new_rand_val) #the comupter is playing by guessing a number
checking(comp_guess, new_rand_val)
def checking(comp_guess, new_rand_val):
print("\n The computer chose:", comp_guess)#this is for me to follow up
remain_rand_val=new_rand_val-comp_guess
if remain_rand_val<=0:
print("Computer guessed too far, now its trying again:")
comput_turn(new_rand_val)
userturn(remain_rand_val)
print("Amount left is:", remain_rand_val," \n\n Now its your turn\n")
userturn(remain_rand_val)
def userturn(remain_rand_val):
ans=int(input("Enter a number between 0 and"))
print(remain_rand_val)
if ans>=10 and ans<=remain_rand_val:
user_rand_val=remain_rand_val-ans
print("Amount left is,",user_rand_val," Now its the Computer turn\n")
comput_turn(user_rand_val)
def main():
start()
Related
I have been working on this project for the past 2 days and I am nearly finished but I would really like to add a working scoring system but I couldn't find any answers on google. Pls Send Help.
import random
score = 0
def main():
bet = input("Place Your Bet On A Number From 1-10 (quit to exit): ")
number = random.randint(1, 10)
if(bet == number):
global score
score+=1
print("Correct!, ", score)
print(" ")
else:
score-=1
print("Incorrect!, ", score)
print(" ")
print("Your Bet: ", bet)
print("The ACTUAL number: ", number)
print(" ")
if(bet == "quit"):
exit()
while True:
main()
I tried adding a scoring system to my game but it kept deducting points even though I was right. I searched on google but all of the answers were outdated and didn't work on 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()
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!
I am trying to make a guessing game in python 3 using jupyter notebook whereby two people take turns to guess a number between 1 and 10. What I don't want is that the answer is immediately given like this:
from random import randint
rand_num = randint(1,10)
players = ['player_1', 'player_2']
for player in players:
player_input = int(input('What is your guess {}? '.format(player)))
if player_input == rand_num:
print('You won!')
else:
print('You lost!')
print('The random number was: {}'.format(rand_num))
Instead I want everyone to guess and then the answer is given so that everyone has a fair chance at guessing the number. I tried the following here but this doesn't seem to work because I think the player_input doesn't account for every single player. So when one player got the number right, python prints that every player got the number right.
from random import randint
rand_num = randint(1,10)
players = ['player_1', 'player_2']
for player in players:
player_input = int(input('What is your guess {}? '.format(player)))
for player in players:
if player_input == rand_num:
print('You won {}!'.format(player))
else:
print('You lost {}!'.format(player))
print('The random number was: {}'.format(rand_num))
How can I make this work using lists and for loops?
Loops are probably not suitable for what you want to achieve, you better go with simple case selection by storing the answers of both players:
from random import randint
rand_num = randint(1,10)
players = ['player_1', 'player_2']
player_inputs = []
for player in players:
player_input = int(input('What is your guess {}? '.format(player)))
player_inputs.append(player_input)
if rand_num in player_inputs:
if player_inputs[0] == player_inputs[1]:
print('You both won!')
elif player_inputs[0] == rand_num:
print('You won {}!'.format(players[0]))
print('You lost {}!'.format(players[1]))
elif player_inputs[1] == rand_num:
print('You won {}!'.format(players[1]))
print('You lost {}!'.format(players[0]))
else:
print('You both lost')
print('The random number was: {}'.format(rand_num))
So I have recently started programming python and I have one issue with this code. When the player gets the answer incorrect after using all their lives it should print the answer which it does but only the first time the layer plays i they play again they don't get told the correct answer if the get it wrong. It also does this when the player gets the answer correct. Plus the number the computer chooses stays the same when you use the play again function. Please try and help me but bear in mind my understanding cane be very limited in some aspects of python. I've included lots of comments to help others understand whats going on. I have included my code and what I get in the shell.
Code:
#imports required modules
import random
from time import sleep
#correct number variable created
num = 0
#generates number at random
comp_num = random.randint(1,10)
print('I\'m thinking of a number guess what it is...\n')
#main game code
def main():
#lives created
lives = 3
#correct number variable reset
num = 0
while lives >= 1:
#player guesses
guess = int(input('Guess: '))
if comp_num == guess:
#if correct says well done
input('\nWell Done! You guessed Correctly!\n')
#player doesn't get told what the number is if there right
num = num +1
break
elif comp_num >= guess:
#if guess is too low tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo low!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
elif comp_num <= guess:
#if guess is too high tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo high!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
def end():
#asks player if they want to play again
play_again = input('Would you like to play again?[Y/N] ')
while play_again.lower() == 'y':
#if they do game resets and plays again
if play_again.lower() == 'y':
comp_num = random.randint(1,10)
print('\nI\'m thinking of a number guess what it is...\n')
main()
play_again = input('Would you like to play again?[Y/N] ')
if play_again.lower() == 'n':
break
if play_again.lower() == 'n':
#if they don't game ends
input('\nOk, Press enter to exit')
exit()
main()
if num != 1:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
end()
SHELL:
I'm thinking of a number guess what it is...
Guess: 5
Well Done! You guessed Correctly!
The number I was thinking of was... 5 !
Would you like to play again?[Y/N] y
I'm thinking of a number guess what it is...
Guess: 5
Well Done! You guessed Correctly!
Would you like to play again?[Y/N] y
I'm thinking of a number guess what it is...
Guess: 5
Well Done! You guessed Correctly!
Would you like to play again?[Y/N] y
I'm thinking of a number guess what it is...
Guess: 5
Well Done! You guessed Correctly!
The problem with your function is that you have a global variable named num, but your main function also has a local variable named num. The num += 1 line inside main only changes the local variable. But the if num != 1 at the end checks the global variable.
To fix this, add a global statement:
def main():
global num
# the rest of your code
Why does this work?
In Python, any time you write an assignment statement (like num = 0 or num += 1) in a function, that creates a local variable—unless you've explicitly told it not to, with a global statement.* So, adding that global num means that now, there is no local variable num, so num += 1 affects the global instead.
This is explained in more detail in the tutorial section on Defining Functions.
* Or a nonlocal statement, but you don't want to learn about that yet.
However, there's a better way to fix this. Instead of using a global variable, you can return the value in the local variable. Like this:
def main():
# your existing code
return num
# your other functions
score = main()
if score != 1:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
Ok so my friend looked at my code and we solved it together. We have fixed both the number staying the same and being told the correct answer by doing this.
#imports required modules
import random
#correct number variable created
num = 0
#generates number at random
comp_num = random.randint(1,10)
print('I\'m thinking of a number guess what it is...\n')
#main game code
def main():
#generates number at random
comp_num = random.randint(1,10)
#set num as a global variable
global num
#lives created
lives = 3
while lives >= 1:
#player guesses
guess = int(input('Guess: '))
if comp_num == guess:
#if correct says well done
print('\nWell Done! You guessed Correctly!\n')
break
elif comp_num >= guess:
#if guess is too low tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo low!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
elif comp_num <= guess:
#if guess is too high tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo high!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
def end():
#asks player if they want to play again
play_again = input('Would you like to play again?[Y/N] ')
while play_again.lower() == 'y':
#if they do game resets and plays again
if play_again.lower() == 'y':
comp_num = random.randint(1,10)
print('\nI\'m thinking of a number guess what it is...\n')
main()
play_again = input('Would you like to play again?[Y/N] ')
if play_again.lower() == 'n':
break
if play_again.lower() == 'n':
#if they don't game ends
input('Ok, Press enter to exit')
exit()
#calls main section of game
main()
#calls end of game to give option of playing again and reseting game
end()
I would like to thank everyone that helped out as with out I still wouldn't be able to see the problem within my code let alone fix it. For this reason I will me marking #abarnert 's answer as the accepted answer as he found the bug.
You can try this code. I did it as a school assignment
import random
print "Welcome to guess my number!"
number = random.randint(1,100)
count = 1
while count <= 5:
guess = int(raw_input("Guess an integer between 1 and 100 (inclusive): "))
if guess == number:
print "Correct! You won in",count,"guesses!"
break
if guess > number:
print "Lower!"
else:
print "Higher!"
count += 1
if count == 6:
print "Man, you really suck at this game. The number was", number