Last active
December 27, 2015 18:39
-
-
Save ranlix/7371029 to your computer and use it in GitHub Desktop.
An Introduction to Interactive Programming in Python ——Guess the number!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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