How to code a reverse 'Guess my Number' game in python? - python

I've written a game where a player tries to guess a random number (see code below). Suggestions such as 'Too low...' and 'Too High...' are also provided. But what about reversing it and letting the computer guess a number that a player has selected. I have difficulty with this and I dont know why. I think I need a 'push' from someone but not the actual code as I need to attempt this myself. I would appreciate it if some would help me on this.
Here is the code(Python 3) where the player has to guess the number:
#Guess my Number - Exercise 3
#Limited to 5 guesses
import random
attempts = 1
secret_number = random.randint(1,100)
isCorrect = False
guess = int(input("Take a guess: "))
while secret_number != guess and attempts < 6:
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = int(input("Take a guess: "))
attempts += 1
if attempts == 6:
print("\nSorry you reached the maximum number of tries")
print("The secret number was ",secret_number)
else:
print("\nYou guessed it! The number was " ,secret_number)
print("You guessed it in ", attempts,"attempts")
input("\n\n Press the enter key to exit")
Thanks for your help.

at each iteration through your loop, you'll need a new random.randint(low,high). low and high can be figured out by collecting your computers guesses into 2 lists (low_list) and (high_list) based how the user responds when the computer tells the user it's guess. Then you get low by max(low_list)+1 and you get high by min(high_list)-1. Of course, you'll have to initialize low_list and high_list with the lowest and highest numbers allowed.
You could just keep the lowest of the "too high" guesses and the highest of the "too_low" guesses instead of the lists. It would be slightly more efficient and probably the same amount of work to code, but then you couldn't look back at the computer's guesses for fun :).

You begin with a range from the minimum allowed number to the maximum allowed number, because the unknown number could be anywhere in the range.
At each step, you need to choose a number to query, so dividing the space into two blocks; those on the wrong side of your query number will be dropped. The most efficient way to do this in the minimum number of queries is to bisect the space each time.
I suggest you restrict the game to integers, otherwise you'll end up with a lot of messing about with floating point values regarding tolerance and precision and so on.

Assuming you know the range of numbers it could be is (a,b).
Think about how you would narrow down the range. You'd start by guessing in the middle. If your guess was low, you'd guess between your last guess and the top value. If it was high you'd guess between the lowest possible value and the last guess. By iteratively narrowing the range, eventually you'd find the number.
Here's some pseudo code for this:
loop{
guess = (a+b)/2
if high:
b = guess - 1
else if low:
a = guess + 1
else:
guess = answer
}

I just did this with a different person, use a while loop and use print("<,>,="), then do an if statement. You need a max point, middlepoint and low point and to get the middle point you need to do midpoint=((highpoint=lowpoint)//2) and in the if statement you have to do change the maxpoint and lowpoint.

Related

How to make my while loop work in Python?

This is my code:
import random
Random = random.randint(1, 10)
print("Number:" + str(Random))
Number = int(input("Guess the number I am thinking of from 1-10"))
while int(Random) != Number:
if(Random > Number):
Number = input("Too low. Guess again!")
elif(Number > Random):
Number = input("Too high. Guess again!")
print("You guessed it!")
When the correct number is guessed, this happens, which is what is supposed to happen.
Number:8
Guess the number I am thinking of from 1-10 8
You guessed it!
But, when the number isn't guessed correctly, it loops though the elif statement only.
Number:10
Guess the number I am thinking of from 1-10 6
Too low. Guess again! 7
Too high. Guess again! 6
Too high. Guess again! 5
Too high. Guess again! 4
Too high. Guess again! 3
Too high. Guess again! 2
Too high. Guess again! 1
Too high. Guess again! 10
Too high. Guess again! 9
Too high. Guess again! 8
Have you tried casting int onto the input within both input lines in the while loop? It seems to work for me when it's like:
if(Random > Number):
Number = int(input("Too low. Guess again!"))
elif(Number > Random):
Number = int(input("Too high. Guess again!"))
import random
number=random.randint(1,10)
guess=int(input("Guess the number I am thinking of from 1-10")
while guess !=number:
if guess < number:
print("Your answer was too low...")
else:
print("Your number was too high...")
guess= int(input("Please try again...")
print("Congratulations! Correct answer!")
you can use this as your reference. thank you...
This is an improved version of your code:
import random
answer = random.randint(1, 10)
print("Number:" + str(answer))
guess = int(input("Guess the number I am thinking of from 1-10"))
while answer != guess:
if guess < answer:
guess = int(input("Too low. Guess again!"))
elif guess > answer:
guess = int(input("Too high. Guess again!"))
print("You guessed it!")
Some remarks on the changes:
The main thing is the int() around the input(). input() gets you a value as a string, but you want to compare the values of the numbers, not the strings. For example '12' < '2' but 12 > 2.
Your variables' names had capital letters in them, that's a bad idea in Python, since that signals to editors and other programmers that they're classes instead of variables.
Your variable Random had the same name as the module you're using, making it easy to get confused, answer seemed like a better choice.
Your code was indented with 2 spaces, but most editors default to 4 and that's also inline with standard Python style guidelines.
Instead of flipping the order of variables, it's often best to make your code read as close as possible to what it means; for example, if guess < answer is exactly what you're saying: "too low".

How to implement a numeric guessing game with loops in Python

So I'm creating this game where the computer guesses a number, and based on the reply, it splits and re-selects a number. I've had little problems so far, but now I'm quite stuck on the loop. I know what I have to do, I just can't figure out how to do it properly, and have it function.
lowest = int(input( "What is the lowest number you will think of?: "))
highest = int(input( "What is the highest number you will think of?: "))
print("So you're thinking of a number between",lowest,"and",highest)
x=[]
for number in range(lowest,highest):
x.append(number)
middleIndex = (len(x))//2
print ("is it "+str(x[middleIndex])+"?")
answer = input("")
if answer == "lower":
x = (x[:len(x)//2])
else:
x = (x[len(x)//2:])
I know it has to go after the
x.append(number)
but I can't get it to work using for or while loops.
The entire for loop is kind of pointless, with the x.append line especially so. range() gives you a list anyway (in Python 3 it gives you a range object which can be converted to a list using the list function).
You could replace that with:
x=list(range(lowest, highest))
Also, this is more convention than anything technically incorrect, but in Python I think camel case is generally reserved for class names; for this reason, I would rename middleIndex to middle_index.
And finally, you don't have anything for the case when the computer guesses the right number!
What you're looking for is basically an interactive binary search algorithm that runs over a range of numbers. You don't actually need to use range or a list, because you can calculate the average of your min and max values instead of finding the middle_index.
Here is an example implementation:
def main():
print("What range will your guessed number fall within?")
min = int(input("Min: "))
max = int(input("Max: "))
print("Ok; think of a number between {0} and {1}.".format(min, max))
while min <= max:
mid = (min + max) // 2
if input("Is it {0}? (Y/N) ".format(mid)) == "Y":
print("It is!? Well, that was fun.")
return
elif input("Darn. Is it higher than {0}? (Y/N) ".format(mid)) == "Y":
min = mid + 1
else:
max = mid - 1
print("Well, it looks like you were dishonest somewhere along the line.")
print("I've exhausted every possibility!")
main()

Increasing the difficulty of the guess the number game every time the user wins (python)

So my friends and I are all currently in a python class and we were looking through a book called "Invent Your Own Computer Games with Python". We found an example where the book explains how to create a Guess the Number Game and decided to mess around with it.
We want to create a function that increases the difficulty every time the user successfully guesses the correct number generated by the computer.
I was thinking that perhaps we could need a counter to keep track of how many times the user successfully wins a round and then (if they won) increases range of numbers.
For example:
easy = (1, 5)
medium = (1, 10)
hard = (1, 20)
Here's what I've done:
# This is a guess the number game.
import random
# create function for level difficulty
# The difficulty will be multiplied by 2 each time the user passes a level
def puzzle(difficulty):
while counter <= 3:
return difficulty * 2
counter = 0
guessestaken = 0
while guessestaken < 3:
while counter < 3:
level = puzzle(3)
number = random.randint(1, level)
print("I am thinking of a number between 1 and " + str(level))
print("Take a guess.")
guess = input()
guess = int(guess)
guessestaken += 1
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
counter += 1
if guess == number:
guessestaken = str(guessestaken)
print ("Fantastic! You guessed my number in " + guessestaken + " guesses!")
if guess != number:
number = str(number)
print("Sorry, The number I was thinking of was " + number)
I'm new to python and just barely learned about functions like two days ago. Any kind of help is welcomed.
This could work:
Make a variable called, say, times_won at the beginning. Each time the person wins,
times_won += 1
BONUS: Do the same thing, but with a variable called times_lost and tick that up each time they lose.
Now it is up to you. You could change the difficulty like this:
level = puzzle(times_won+1*2)
This would make it so that it automatically goes up the more the player wins. Or how about this:
curr_dificulty = 5
if #player_won:
curr_dificulty += 4
This and other variations would increase it based on wins as well, but in a different way. You could also make it so that losing eases up the difficulty. This part is really up to you.
P.S. The tag "pygame" you used is actually referring to games made using a down-loadable library that you can import into your code, not games made with python in general. It makes games with actual graphics, you should try it out!
P.P.S. in case you didn't know, the weird syntax I made above with the #player_won and the fact that the assignment of curr_dificulty is out of place is because I used pseudo-code. It basically gives the idea, but you need to do the actual code yourself.

Basic Python code not Working

I am newbie to Python.
Here is my Code that implements binary search to find the guessed number .I cant figure it out correctly how to make my code work.
Any help would be appreciated. Thanks.
print"Please think of a number between 0 and 100!"
guessed=False
while not guessed:
lo=0
hi=100
mid=(lo+hi)/2
print'Is you Secret Number'+str(mid)+'?'
print"Enter 'h' to indicate the guess is too high.",
print"Enter'l' to indicate the guess is too low",
print"Enter'c'to indicate I guessed correctly"
x=raw_input()
if(x=='c'):
guessed=True
elif(x=='h'):
#Too High Guess
lo=mid+1
elif(x=='l'):
lo=mid-1
else:
print("Sorry, I did not understand your input.")
print'Game Over','Your Secret Number was'+str()
Following points need to apply code:
Define lower and upper limit outside of for loop becsue if we define inside while loop, every time lo and hi variable will create with 0 and 100 value respectively.
Give variable name according to variable work.
lower = 0
higher = 100
God practice to Write function to wrap your code.
As guess number is higher then set Max Number to guess number.
As guess number is lower then set Min Number to guess number.
Demo:
import time
def userNoInput(msg):
""" Get Number into from the user. """
while 1:
try:
return int(raw_input(msg))
except ValueError:
print "Enter Only Number string."
continue
def guessGame():
"""
1. Get Lower and Upeer Value number from the User.
2. time sleep to guess number for user in between range.
3. While infinite loop.
4. Get guess number from the Computer.
5. User can check guess number and tell computer that guess number if correct ror not.
6. If Correct then print msg and break While loop.
7. If not Correct then
Ask Computer will User that guess number is Greate or Lower then Actual number.
7.1. If Greater then Set Max limit as guess number.
7.2. If Not Greater then Set Min limit as guess number.
7.3. Continue While loop
"""
min_no = userNoInput("Please input the low number range:")
max_no = userNoInput("Please input the high number range:")
print "Guess any number between %d and %d."%(min_no, max_no)
time.sleep(2)
while True:
mid = (min_no+max_no)/2
print'Is you Secret Number'+str(mid)+'?'
print"Enter 'h' to indicate the guess is too high.",
print"Enter'l' to indicate the guess is too low",
print"Enter'c'to indicate I guessed correctly"
x=raw_input().lower()
if(x=='c'):
print'Game Over','Your Secret Number was'+str(mid)
break
elif(x=='h'):
#- As guess number is higher then set max number to guess number.
max_no=mid - 1
elif(x=='l'):
#- As guess number is lower then set min number to guess number.
min_no = mid + 1
else:
print("Sorry, I did not understand your input.")
guessGame()
Output:
vivek#vivek:~/Desktop/stackoverflow$ python guess_game.py
Please input the low number range:1
Please input the high number range:100
Guess any number between 1 and 100.
Is you Secret Number50?
Enter 'h' to indicate the guess is too high. Enter'l' to indicate the guess is too low Enter'c'to indicate I guessed correctly
h
Is you Secret Number25?
Enter 'h' to indicate the guess is too high. Enter'l' to indicate the guess is too low Enter'c'to indicate I guessed correctly
h
Is you Secret Number12?
Enter 'h' to indicate the guess is too high. Enter'l' to indicate the guess is too low Enter'c'to indicate I guessed correctly
l
Is you Secret Number18?
Enter 'h' to indicate the guess is too high. Enter'l' to indicate the guess is too low Enter'c'to indicate I guessed correctly
h
Is you Secret Number15?
Enter 'h' to indicate the guess is too high. Enter'l' to indicate the guess is too low Enter'c'to indicate I guessed correctly
l
Is you Secret Number16?
Enter 'h' to indicate the guess is too high. Enter'l' to indicate the guess is too low Enter'c'to indicate I guessed correctly
l
Is you Secret Number17?
Enter 'h' to indicate the guess is too high. Enter'l' to indicate the guess is too low Enter'c'to indicate I guessed correctly
c
Game Over Your Secret Number was17

Python - Random number guessing game - Telling user they are close to guessing the number

I have a quick question.
I want to make my number guessing game tell the user if they are 2 numbers away from guessing the random number.
I do not want the program to say how many numbers away the user is.
The way I'm thinking is this. I just can't put this into proper code.
Random_number = 5
guess = 3
print('you are close to guessing the number!')
guess = 7
print('you are close to guessing the number!')
guess = 2 #more than 2 away from the number
print('you are NOT close to guessing the number')
I am going to start by saying my python is rusty and someone please fix it if im off alittle.
All you need to do if use an if statement.
random = 5
guess = 3
if( guess == random ):
print('your right!')
elif ( abs (guess - random) <= 2 ):
print('you are close to guessing the number!')
else:
print('you are not close enough!')
Edited the elseif logic according to #9000's suggestion.
Try this:
for number in range (2):
if guess == Random_number:
print('you guessed the number!')
if guess - number == Random_number or guess + number == Random_number:
print('you are close to guessing the number!)
Here is the explanation. The first line is saying "for the numbers in the range of 0 to 2 set number equal to that number." So the next if part will run 3 times: for number equaling 0, 1, and 2. So, if your guess is within 2 of the random number, it will print you are close to the random number. If you have the correct guess, it will obviously print you guessed it correctly.

Categories