Skip to content

Instantly share code, notes, and snippets.

@ranlix
Last active December 27, 2015 18:39
Show Gist options
  • Save ranlix/7371029 to your computer and use it in GitHub Desktop.
Save ranlix/7371029 to your computer and use it in GitHub Desktop.
An Introduction to Interactive Programming in Python ——Guess the number!
# 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
import math
# initialize global variables used in your code
num_range = 0
num_guess = 0
guess_count = 0
guess_count_flag = 1
# helper function to start and restart the game
def new_game():
global guess_count
if guess_count_flag:
guess_count = int(math.log(100,2)) + 1
else:
guess_count = int(math.log(1000,2)) + 1
# else:
# print "Please select 'range100' or 'range1000'."
# define event handlers for control panel
def range100():
# button that changes range to range [0,100) and restarts
global num_range
num_range = random.randint(1,100)
def range1000():
# button that changes range to range [0,1000) and restarts
global num_range,guess_count_flag
guess_count_flag = 0
num_range = random.randint(1,1000)
def input_guess(guess):
# main game logic goes here
global num_range,num_guess,guess_count
num_guess = int(guess)
guess_count-=1
print ""
print "Your guess is "+ guess
if guess_count:
if num_guess==num_range:
print "Corrent!"
elif num_guess>num_range:
print "Lower!"
else:
print "Higher!"
print "Guess count is "+ str(guess_count)
else:
print "You have no chance to guess."
# create frame
f = simplegui.create_frame("Game",300,300)
# register event handlers for control elements
f.add_button("Guess 100",range100,200)
f.add_button("Guess 1000",range1000,200)
inp = f.add_input("Input your guess",input_guess,200)
# call new_game and start frame
new_game()
f.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment