Number Guessing game Computer Playing - python-3.x

I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)

I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.

You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')

Related

Python Word guessing game, cannot get While loop to repeat program

I am trying to create a word guessing game in python. I can get the program to run once,
but I want it to run five times in a row keeping track of wins and losses, and this is where
I am running into issues. I have tried adding a counter and nesting the while loop but this does not seem to work. Any help or suggestions would be greatly appreciated. Thanks.
Here is the code I have written:
import random
print('Welcome to the word guessing game!')
input("What is your name? ")
print('Try to guess the word letter by letter, you have ten guesses, good luck!')
words = ['cowboy', 'alien', 'dog', 'airplane',
'trees', 'bridge', 'snake', 'snow',
'popcorn', 'apples', 'road', 'smelly',
'eagle', 'boat', 'runner']
word = random.choice(words)
print("Guess the word!")
guesses = ''
trys = 5
wins = 0
losses = 0
rounds = 0
while rounds < 5:
while trys > 0:
failed = 0
for char in word:
if char in guesses:
print(char, end=" ")
else:
print("*")
failed += 1
if failed == 0:
print("You Win")
print("The word is: ", word)
wins = wins + 1
rounds = rounds + 1
break
print()
guess = input("Enter your letter:")
guesses += guess
if guess != word:
trys -= 1
print("Plesae try again, You have", + trys, 'more guesses')
if trys == 0:
print("You Loose, better luck next time")
losses = losses + 1
rounds = rounds + 1
print('Wins:', wins )
print('Losses:', losses)

Counting and Error Handling Block Guessing Game

Could you, please, help me to understand how should I use try/except block and count tries at the same time.
Here is the code without try/except block (it seems it's working fine):
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while tries != 0:
choice = int(input('Your choice: '))
tries -= 1
if choice > number:
print('My number is less!')
elif choice < number:
print('My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print('No problem! Let\'s make it another time...')
This one is with try/except block.. Not sure where should I place 'choice' variable and where count 'tries', it keeps looping and looping:
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while True:
try:
choice = int(input('Your choice: '))
if 0 < choice < 11:
while tries != 0:
tries -= 1
if choice > number:
print(f'My number is less!')
elif choice < number:
print(f'My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print(f'Hey {name}, I said, print a number from 1 to 10!')
except ValueError:
print('Please, enter a number!')
else:
print('No problem! Let\'s make it another time...')
Thanks!

Number guessing game that requires suggestions for completion

how do I get the difficulty level to work? I have found other codes similar but the difficulty is based on the group of number that it will choose the number from i.e. easy(1,10), medium (1,50), hard (1,100). I need to know how to make it work for the number of guesses. It keeps telling me I don't have easy,medium, or hard defined. how do I define them in way to make this code work?
I can get through it asking for my name then it will ask for the difficulty level and when I type e,m,or,h this is what it gives me: Traceback (most recent call last): File "C:\Users\ajohn\OneDrive - Fairmont State University\BISM3800\Assign2.py", line 58, in guesses = get_guesses(level) File "C:\Users\ajohn\OneDrive - Fairmont State University\BISM3800\Assign2.py", line 50, in get_guesses if diffuculty == hard: NameError: name 'diffuculty' is not defined
here is the objectives for the code:
You are to ask the user if they wish to play the game or continue playing the game after they have guessed the number
You are to ask the user if they want easy, medium or HARD (Easy = unlimited guesses, Medium = 10 guesses, HARD = 5 guesses)
Once the game begins play you are to tell the user that you have picked a number and they are to guess what that number is
your application is to accept the players guess and if their guess is larger than the number you had picked then tell them that, if their guess is smaller then tell them that as well.
The game continues to play until the player picks the number you had originally picked or they have ran out of guesses. I also need to have an exception.
Here is my code so far:
This is a guessing the number game.
import random
this statement will allow the options for playing and quiting the game.
play = True
while play:
difficulty = 0
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
easy = random.randint (1,100)
easy = random.randint (1,100)
easy = random.randint (1,100)
prompts the user to select a difficulty to play on
def select_level():
while True:
level = str(input("Would you like to play on easy, medium, or hard? \n"
"Type 'e' for easy, 'm' for medium, or 'h' for hard!\n"))
if level != "e" and level != "m" and level != "h":
print("Invalid input!\n")
if level == "e" or level == "m" or level == "h":
break
return level
function that prompts the user to guess depending on chosen difficulty
def guess_number(level):
if level == "e":
(easy == 500)
if level == "m":
(medium == 10)
if level == "h":
(hard == 5)
return guesses
selects number of guesses depending on difficulty selected
def get_guesses(level):
if difficulty == easy:
print ("Okay, " + myName + ". You have unlimited guesses")
if difficulty == medium:
print ("Okay, " + myName + ". You have 10 guesses.")
if diffuculty == hard:
print ("Okay, " + myName + ". You have 5 guesses.")
elif level != "e" and level != "m" and level != "h":
print ("Invalid input!")
get_guesses()
return guesses
level = select_level()
guesses = get_guesses(level)
print('Well, ' + myName + ', I am thinking of a number can you guess it?')
while guessesTaken < level:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed the number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
Here's the object oriented approach :
from random import randint
class Guessing_Game () :
def __init__ (self, users_name) :
self.difficulty = 10
self.name = users_name
self.start_the_game ()
def start_the_game (self) :
my_secret_number = randint (1, self.difficulty)
print ('Well, ' + self.name + ', I am thinking of a ', end = '')
print ('between 1 and ' + str (self.difficulty) + '.')
print ('Can you guess it?')
self.guess_the_number (my_secret_number)
def guess_the_number (self, the_secret_number) :
still_playing = True
while still_playing == True :
answer = int (input ('Take a guess : '))
if answer == the_secret_number :
print ('That is exactly correct! You win!')
still_playing = False
else :
if answer > the_secret_number :
print ('Sorry, you are too high.')
if answer < the_secret_number :
print ('Sorry, you are too low.')
if self.play_again () == True :
self.start_the_game ()
def play_again (self) :
self.difficulty = self.difficulty * 2
answer = input ('Would you like to play again? ')
if answer [0].lower () == 'y' : return True
return False
users_name = input ('Please enter your name : ')
my_game = Guessing_Game (users_name)

Python number guessing game not displaying feedback correctly. What's the problem?

So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()

Unable to record how many times my while loop runs- Python3

I am working on a number guessing game for python3 and the end goal of this is to show the user if they play more than one game that they'll receive an average number of guesses. However, I am unable to record how many times the game actually runs. Any help will do.
from random import randint
import sys
def guessinggame():
STOP = '='
a = '>'
b = '<'
guess_count = 0
lowest_number = 1
gamecount = 0
highest_number = 100
while True:
guess = (lowest_number+highest_number)//2
print("My guess is :", guess)
user_guess = input("Is your number greater than,less than, or equal to: ")
guess_count += 1
if user_guess == STOP:
break
if user_guess == a:
lowest_number = guess + 1
elif user_guess == b:
highest_number = guess - 1
print("Congrats on BEATING THE GAME! I did it in ", guess_count, "guesses")
PLAY_AGAIN = input("Would you like to play again? y or n: ")
yes = 'y'
gamecount = 0
no = 'n'
if PLAY_AGAIN == yes:
guessinggame()
gamecount = gamecount + 1
else:
gamecount += 1
print("thank you for playing!")
print("You played", gamecount , "games")
sys.exit(0)
return guess_count, gamecount
print('Hello! What is your name?')
myname = input()
print('Well', myname, ', I want you to think of number in your head and I will guess it.')
print("---------------------------------------------------------------------------------")
print("RULES: if the number is correct simply input '='")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is GREATER then the output, input '>'")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is LESS then the output, input '<'")
print("---------------------------------------------------------------------------------")
print(" ALRIGHT LETS PLAY")
print("---------------------------------------------------------------------------------")
guessinggame()
guess_count = guessinggame()
print(" it took me this many number of guesses: ", guess_count)
## each game the user plays is added one to it
## when the user wants to the game to stop they finish it and
## prints number of games they played as well as the average of guess it took
## it would need to take the number of games and add all the guesses together and divide it.
It is because you are either calling guessinggame() everytime user wants to play again or you are exiting the program. Also you are setting gamecount to 0 every time you call guessinggame(). You should move gamecount declaration and initialization out of your function. Also increment gamecount before you call guessinggame().

Resources