How to delete used numbers in computer guessing game? - python

I am trying to create a computer vs computer guessing game and the problem is that the computer will guess the same number twice. I tried the .remove() with a variable but the computer would still guess where the variable was so I would get an error. I reverted the code back to where it worked somewhat.
print 'Get ready for some action!'
time.sleep(1)
firstname = raw_input('Enter in a name for computer 1... ')
time.sleep(1)
secondname = raw_input('Enter in a name for computer 2... ')
time.sleep(1)
howlittle = int(raw_input('Enter in the min... '))
time.sleep(1)
howmuch = int(raw_input('Enter in the max... '))
computernumber = random.randint(howlittle,howmuch)
print firstname + 'choses %s as its lucky number.' %computernumber
time.sleep(1)
print '%s is thinking...'%secondname
time.sleep(1)
firsts=random.randint(howlittle,howmuch)
if firsts == computernumber:
print 'The %s won!'%secondname
guessers = 0
computers=[]
while firsts != computernumber:
guessers += 1
if firsts == computernumber:
print 'The computer won in %s guesses'%guessers
elif firsts > computernumber:
firsts = random.randint(howlittle,firsts)
computers.append(firsts)
elif firsts < computernumber:
firsts = random.randint(firsts, howmuch)
computers.append(firsts)
print secondname + " took %s guesses to guess the number" %guessers
print computers
I am still adding features to it but I just needed to get this problem out of the way first. Thanks!

Add an if condition in your elif such that :
if number_guessed is in computer_guesses_list:
generate a random number again

Maybe the problem is that random.randint(a,b) returns a number x in [a,b], i.e. a <= x <= b.
So in your code, random.randint(howlittle,firsts) its possible for firsts to be returned, change it to random.randint(howlittle,firsts-1)
and random.randint(firsts,howmuch) to random.randint(firsts+1,howmuch)
You should have posted the code that isn't working.

Related

Unsupported operand types (int)+(var) error

P1Roundx=int (0)
P2Roundx=int(0)
P1Scorex=int(0)
P2Scorex=int(0)
P1Total=int(0)
P2Total=int(0)
number=int(0)
P1R1=int(0)
P2R1=int(0)
P1R2=int(0)
P2R2=int(0)
import time
Username=input("what is player 1’s username")
Username=str(Username)
if Username == ("1"):
print ("hello",Username,)
elif Username == ("2"):
print ("welcome",Username,)
else:
print("LEAVE!")
exit()
# This module determines if player 1 is authenticated or if they are not. If they are not they are forced to exit the programme
Username2=input("what is player 2's username")
Username2=str(Username2)
if Username2 == ("2"):
print ("hello,",Username2,)
elif Username2 == ("1"):
print ("welcome",Username2,)
else:
print("LEAVE!")
exit()
# This module determines if player 2 is authenticated or not and exits the programme if they are not
import random
P1R1= random.randint(1,6)
P1R1=("Your first roll is",P1R1)
P1R2=random.randint(1,6)
P1R2=("Your second roll is",P1R2)
print("Your total is",P1R1+P1R2)
P1total=P1R1+P1R2
if P1Total % 2 == 0:
P1Total=(P1Total)+P1R1
else:
P1Total=(P1Total)-5+P1R1+P1R2
print("Player 1's total score is",P1Total)
import random
P2R1= random.randint(1,6)
P2R1=("Your first roll is",P2R1)
P2R2=random.randint(1,6)
P2R2=("Your second roll is",P2R2)
print("Your total is",P2R1+P2R2)
P2total=P2R1+P2R2
if P2Total % 2 == 0:
P2Total=(P2Total)+ P2R1+P2R2
else:
P2Total=(P2Total)-5+P2R1
print("Player 2's total score is",P2Total)
time.sleep(6)
as an error, but I don't understand where the var + int is. I need help.
BTW IM NOT VERY GOOD AT THIS SNAKEY TING
When your code does this
P1R1= random.randint(1,6)
P1R1 is a number between 1 and 6; let's imagine it is 4. But then the code does
P1R1=("Your first roll is",P1R1)
It appears your intent is to print this out as a message. But what it actually does is change the value of P1R1 to the tuple ("Your first roll is",4). Then your code carries on as if P1R1 still had the value 4 because it does addition on it.
If you look at the output of this line:
print("Your total is",P1R1+P1R2)
you will see that it is
Your total is ('Your first roll is', 4, 'Your second roll is', 1)
when it is clear that you are expecting
Your total is 5
It should be easy for you to see why the code goes wrong after that.
hi remove the below lines which are assigning tuple to P1R1 and P2R2
P1R1=("Your first roll is",P1R1)
P2R2=("Your second roll is",P2R2)

Not allowing me to use a > between a function and int

GUESSING GAME
from random import randint
from time import sleep
def get_user_guess():
guess = int(input('What is your guess: '))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print ("The maximum value you can roll is %d" % max_val)
get_user_guess()
if get_user_guess > 13:
print ("invalid guess, please try again")
else:
print ("Rolling...")
sleep(2)
print ("%d" % first_roll)
sleep(1)
print ("%d" % second_roll)
sleep(1)
total_roll = first_roll + second_roll
print ("%d" % total_roll)
print ("Result...")
sleep(1)
if get_user_guess == total_roll:
print ("Congratulations, you've won!")
else:
print ("sorry sucker, you lose!")
roll_dice(6)
Here is the code. I made a running version in python 2, but translating it to python 3 has been a headache. I have defined that get_user_guess, where guess = an int. But further down in the roll_dice section, after I have called on the previous function and its answer I'm getting error messages.
That's not how you access the return value of a function. You should assign the return value to a new name, then use that in the following comparisons.
guess = get_user_guess()
if guess > 13:
print("invalid guess")
else:
...
if guess == total_roll:
print("Congratulations")
else:
print("sorry")
So, this seems like a small logic error and a syntax error as well. First the syntax error. You're not really initializing or calling the function in the comparison by doing:
if get_user_guess > 12
rather than doing:
if get_user_guess() > 12
So there is nothing for the ">" operator to compare against.
Second, seeing as you're trying to reuse the variable for the next comparison.You will need to store it as well otherwise it would prompt the user again for a new value again. Note the changes in lines 13,14 and 28 will fix it:
from random import randint
from time import sleep
def get_user_guess():
guess = int(input('What is your guess: '))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print ("The maximum value you can roll is %d" % max_val)
guess = get_user_guess()
if guess > 13:
print ("invalid guess, please try again")
else:
print ("Rolling...")
sleep(2)
print ("%d" % first_roll)
sleep(1)
print ("%d" % second_roll)
sleep(1)
total_roll = first_roll + second_roll
print ("%d" % total_roll)
print ("Result...")
sleep(1)
if get_user_guess == total_roll:
print ("Congratulations, you've won!")
else:
print ("sorry sucker, you lose!")
roll_dice(6)

Self teaching python. Having trouble with score incrementing after each round

TL:DR Trying to set up a scoring system, it doesn't seem to go up when you get than answer right
As the title says I'm teaching myself python, thus this is only the second code I have written (hints in why I'm learning python). I'm more than happy to take criticism on everything from syntax to how to better comment. With that being said, let's get to my issue.
This is a small guessing game. The book I'm reading taught the "for guessTaken" and subsequent code. My problem is in one small aspect of my code. The scoring system won't increment.
I set up the code in the for loop called games then try to have it display at that start of each round and go up with each correct guess. However, it will display 0 for the first few rounds then it will show 2 ( or whatever your current score is I think...). I think the problem is I'm calling the score +1 int in an if statement but I've moved the code around and can't figure it out.
I am aware that it's not beautiful! There are also a few bugs (number of games played isn't what you enter.)Right now I'm only working on the scoring system.
#this is a guess the number game.
import random
#Get's user's name
print("Hello. Welcome to Print's guessing game. Please enter your name: ")
userName = input()
#askes if they are ready
print("Are you ready to play " + userName + "?")
ready = input().lower()
if ready == 'yes' :
print("Let's get started")
else:
while ready != 'yes':
print("Let me know when you are ready")
ready = input().lower()
#Game start
#number of games
games = int(input("How many games would you like to play?"))
if games >= 1:
print("Let's get started")
for games in range (int(games), 1, -1):
while games != 1:
print("I am thinking of a number between 1 and 20 ")
secretNumber = random.randint(1, 20)
score = 0
print("Current score: " + str(score))
print("Debug: " + str(secretNumber))
for guessTaken in range (7, 1, -1):
print("you have " + str(guessTaken - 1 ) + " guesses left")
guess = int(input())
if guess < secretNumber:
print("Your guess is to low. Please guess again")
elif guess > secretNumber:
print("Your guess is too high. Maybe something a little lower?")
else:
break # This conditon is for the right guess.
if guess == secretNumber:
print("good Job " + userName + "! you guessed the number right!")
score = int(score + 1)
print("your score is " + str(score))
games = int(games - 1)
else:
print("Nope, the number I was thinking of was " + str(secretNumber))
print("you have " + str(games) + " games left")
elif games == 0:
while games == 0:
print("Would you like to exit? Yes or No ")
exit = input().lower()
if exit == 'yes':
quit()
else:
games = int(input("How many games would you like to play?"))
else:
print("wtf")
Your score variable is being initialized to zero every time your code goes through the while loop. If you want it to track the total score for all of the games, initialize it right after your print("Let's get started"). This will reset their score whenever they tell you how many games they want to play.
If you don't want their score to reset until they quit your program, you will have to initialize it at the beginning of your program. Up by your import random would work well.

PYTHON - Reverse Number Guessing Game -

So I've been trying to figure out a way to write a program where the computer tries to guess the number I am thinking of, instead of the other way around where you are guessing a computer's chosen number. It works most of the time however in some situations it does repeat numbers down the chain even though I've told it before that for example the value I am thinking of is higher than '7'. In some cases it also repeats the same number again even though I tell it its higher or lower. If someone more experienced could have a look at this and tell me what am I missing in these loops it would help a great deal.
#computer enters a value x
#lower - computer guesses lower than x
#higher - computer guesses higher than x
#when string "You got it!" - game over
import random
lowBound = 0
highBound = 100
randomNumber = random.randint(lowBound,highBound)
print ("Is it ", randomNumber, " ?")
response = input()
while response != "You got it!":
if response == "higher":
lowBound = randomNumber
randomNumber = random.randint (lowBound, highBound)
print ("Is it ", randomNumber, " ?")
response = input()
elif response == "lower":
highBound = randomNumber
randomNumber = random.randint (lowBound, highBound)
print ("Is it ", randomNumber, " ?")
response = input()
if response == "You got it!":
print ("Woohooo, I'm so bitchin'")
random.randint is inclusive, so:
if response == 'higher':
lowBound = randomNumber + 1
and
if response == 'lower':
highBound = randomNumber - 1
Also, if the user does not enter a valid response, input() will never be called again and the program will hang in an infinite loop.
Something more robust, but doesn't handle liars:
import random
lowBound = 0
highBound = 100
response = ''
randomNumber = random.randint(lowBound,highBound)
while response != "yes":
print ("Is it ", randomNumber, " ?")
response = input()
if response == "higher":
lowBound = randomNumber + 1
randomNumber = random.randint(lowBound,highBound)
elif response == "lower":
highBound = randomNumber - 1
randomNumber = random.randint(lowBound,highBound)
elif response == "yes":
print ("Woohooo, I'm so bitchin'")
break
else:
print ('Huh? "higher", "lower", or "yes" are valid responses.')
random.randint(a, b) returns a number between and including a and b. When generating a new random number you should use random.randint(lowBound+1, highBound-1)
One of your problems, among the others mentioned, is on these lines:
highBound = randomNumber
randomNumber = random.randint (lowBound, highBound)
You're setting a new bound, which is good, but then you're choosing another random number!
What you should be doing, is halving the bound, and asking the user higher or lower from there. Have a look at binary search algorithms.
highBound = randomNumber
randomNumber = randomNumber / 2
Your program is still going to work (with the other changes mentioned here), but this will guess your number quicker most of the time.
There is actually an example of this game on Wikipedia.
Here is my version of this exercise from Michael Dawson's book, I was trying to minimize number of tries, that computer uses. I know code looks dodgy, it is just my 2nd day:)
answer=""
guess=50
counter=3
x=25
print("hi, guess the number from 1 too 100")
input("\n")
print ("i will try to guess it")
print ("is it ", guess, "?")
while answer not in ("y","l","s"):
print ("sorry, i didn't understand \n")
answer=input("type in: (Y) for yes, or (L) if it is to large, or (S) if it is to small:")
if answer in ("s","l"):
while answer!="y":
if answer=="l":
guess=int(guess-x)
print ("how about", guess,"?")
answer=input("\nis it? type in: (Y) for yes, or (L) if it is to large, or (S) if it is to small:")
x=100/2**counter
counter=counter+1
if x<1:
x=1
elif answer=="s":
guess=int(guess+x)
print ("how about", guess,"?")
answer=input("\nis it? type in: (Y) for yes, or (L) if it is to large, or (S) if it is to small:")
x=100/2**counter
counter=counter+1
if x<1:
x=1
elif answer=="y":
break
else:
pass
print("\ngreat! the number that you guessed is", guess)
print("i can read your mind with no guesses!")
input("\n")
You get numbers twice because random.randint's boundaries are inclusive; random.randint(1, 3) can return 1,2, or 3. Note that you should also continue to ask the human if the response is neither "higher", nor "lower" nor "You got it!":
import random
lowBound = 0
highBound = 100
while True:
randomNumber = random.randint(lowBound, highBound)
print ("Is it ", randomNumber, " ?")
response = input()
if response == "higher":
lowBound = randomNumber + 1
elif response == "lower":
highBound = randomNumber - 1
if response == "You got it!":
print ("Woohooo, I'm so bitchin'")
break

Python variable increment while-loop

I'm trying to make the variable number increase if user guessed the right number! And continue increase the increased one if it is guessed by another user. But it's seem my syntax is wrong. So i really need your help. Bellow is my code:
#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it. The number is now increase'
number += 1 # Increase this so the next user won't know it!
running = False # this causes the while loop to stop
elif guess < number:
print 'No, it is a little higher than that.'
else:
print 'No, it is a little lower than that.'
else:
print 'The while loop is over.'
# Do anything else you want to do here
print 'Done'
You can do it without "running" variable, it's not needed
#!/usr/bin/python
# Filename: while.py
number = 23
import sys
try:
while True:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it. The number is now increase')
number += 1 # Increase this so the next user won't know it!
elif guess < number:
print('No, it is a little higher than that.')
else:
print('No, it is a little lower than that.')
except ValueError:
print('Please write number')
except KeyboardInterrupt:
sys.exit("Ok, you're finished with your game")
#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it. The number is now increase'
number += 1 # Increase this so the next user won't know it!
running = False # this causes the while loop to stop
elif guess < number:
print 'No, it is a little higher than that.'
else:
print 'No, it is a little lower than that.'
# Do anything else you want to do here
print 'Done'

Categories