#!/usr/bin/env python3 """ number_guessing_game2-commented.py This version of the Number Guessing Game makes things a bit more challenging for the guesser--actually *impossible*--by NOT actually selecting the expected `secret_number` until after the user has tried to guess what it is. """ __author__ = "Richard White" __version__ = "2022-01-22" import random def main(): ######################################################### # # # Introductions and Initializations # # # # The `lower` and `upper` variables are used to keep # # track of the possible range of values that haven't # # yet been eliminated by an intelligent guessing # # strategy. # # # ######################################################### print("Number Guessing Game!") print("I'm thinking of a number from 1-10. You have three guesses. GO!") guess_number = 1 lower = 1 upper = 10 ######################################################### # # # The guessing loop, which only allows three # # three guesses. No need to check to see if # # they've guessed the number. They never will! # # # ######################################################### while guess_number <= 3: print("Guess #" + str(guess_number) + ": ", end='') user_guess = int(input()) ##################################################### # # # The if-else statement here chooses one # # half of the range to place the secret # # number, depending on which half is larger. # # # # Once an `upper` or `lower` has been set, # # it won't be readjusted in the "wrong" # # direction by subsequent guesses, which # # could happen if we don't check the range # # of the user's guess, as is done in lines # # 65 and 69. Without that check, the range # # will vary and given incorrect results. # # # ##################################################### if user_guess - lower > upper - user_guess: print("Sorry, you guessed too high!") if user_guess - 1 < upper: upper = user_guess - 1 else: print("Sorry, you guessed too low. :(") if user_guess + 1 > lower: lower = user_guess + 1 guess_number += 1 ######################################################### # # # At end of game, calculate `secret_number` # # using a random function (selecting a random # # value between `lower` and `upper`) to disguise # # the fact that we've been deceiving them. # # # ######################################################### print("You're all out of guesses!") secret_number = random.randrange(lower, upper + 1) print("The secret number was " + str(secret_number)) print("Better luck next time! lol!") if __name__ == "__main__": main()