# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
try:
import simplegui
except ModuleNotFoundError:
import simplequi as simplegui
import random
import math
secret_number_range = 100
secret_number: int
remaining_guesses: int
# we do not have to initialize the last two, because they have to be set in
# `new_game()` anyway.
# Just introduce these global variables and annotate them according to PEP 526
# variable annotation syntax
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code here
global secret_number
global remaining_guesses
secret_number = random.randrange(secret_number_range)
remaining_guesses = math.ceil(math.log2(secret_number_range-0+1))
print(f'New game. Range is [0, {secret_number_range})')
print('Number of remaining guesses is', remaining_guesses)
print()
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
global secret_number_range
secret_number_range = 100
new_game()
def range1000():
# button that changes the range to [0,1000) and starts a new game
global secret_number_range
secret_number_range = 1000
new_game()
def input_guess(guess):
global remaining_guesses
guess = int(guess)
# main game logic goes here
print('Guess was', guess)
remaining_guesses -= 1
print('Number of remaining guesses is', remaining_guesses)
if guess == secret_number:
print('Correct')
new_game()
elif remaining_guesses > 0:
if guess > secret_number:
print('Lower')
else:
print('Higher')
print()
else:
print('You ran out of guesses. The number was', secret_number)
print()
new_game()
# create frame
f = simplegui.create_frame('Guess the number', 100, 200)
# register event handlers for control elements and start frame
f.add_button('Range 100', range100)
f.add_button('Range 1000', range1000)
f.add_input('Guess!', input_guess, 100)
# call new_game
new_game()
# always remember to check your completed program against the grading rubric