One of the simplest two-player games is “Guess the number”. The first player thinks of a secret number in some known range while the second player attempts to guess the number. After each guess, the first player answers either “Higher”, “Lower” or “Correct!” depending on whether the secret number is higher, lower or equal to the guess. In this project, you will build a simple interactive program in Python where the computer will take the role of the first player while you play as the second player.
You will interact with your program using an input field and several buttons. For this project, we will ignore the canvas and print the computer’s responses in the console. Building an initial version of your project that prints information in the console is a development strategy that you should use in later projects as well. Focusing on getting the logic of the program correct before trying to make it display the information in some “nice” way on the canvas usually saves lots of time since debugging logic errors in graphical output can be tricky.
# 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 import simplegui import random # initialize global variables used in your code number = random.randrange(0, 10); count = 0 maxNumber = 100; # helper function to start and restart the game def new_game(): global number, count, maxNumber number = random.randrange(0, maxNumber); if(maxNumber == 100): count = 7 else: count = 11 print "" print "New Game. Range is from 0 to " + str(maxNumber) print "Number of remaining guesses is " + str(count) # define event handlers for control panel def range100(): # button that changes range to range [0,100) and restarts global count count = 100 new_game() def range1000(): # button that changes range to range [0,1000) and restarts global count count = 1000 new_game() def input_guess(guess): # main game logic goes here global number, count print "" print "Guess was " + guess print "Number of remaining guesses is " + str(count) if( count == 0): print "You ran out of guesses. The number is "+str(number) new_game() return count = count - 1 if(int(guess)<number): print "Higher" elif(int(guess)>number): print "Lower" else: print "Correct!" new_game() # create frame frame = simplegui.create_frame('Guess the number', 200, 300) # register event handlers for control elements frame.add_button('Range is [0 ,100)', range100,150) frame.add_button('Range is [0 ,1000)', range1000,150) frame.add_input('Enter a guess', input_guess, 150) # call new_game and start frame new_game() # always remember to check your completed program against the grading rubric