Advertisement
ansakoy

Guess the Number

Sep 27th, 2014
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | None | 0 0
  1. """
  2. Guess the number
  3. Mini-project for Interactive Programming in Python, Coursera
  4. Week 2
  5. THIS CODE WORKS IN CODESCULPTOR (http://www.codeskulptor.org/) ONLY!
  6. """
  7. # input will come from buttons and an input field
  8. # all output for the game will be printed in the console
  9.  
  10. import simplegui
  11. import random
  12. import math
  13.  
  14. low = 0
  15. high = 100
  16.  
  17. # helper function to start and restart the game
  18. def new_game():
  19.     # initialize global variables used in your code here
  20.     global secret_number, count
  21.     secret_number = random.randrange(low, high)
  22.     print "\nNew game. Range is from", low, "to", high
  23.     count = int(math.ceil(math.log(high + 1, 2)))
  24.     print "Number of remaining guesses is", count
  25.  
  26. # define event handlers for control panel
  27. def range100():
  28.     # button that changes the range to [0,100) and starts a new game
  29.     global low, high
  30.     low = 0
  31.     high = 100
  32.     new_game()
  33.  
  34. def range1000():
  35.     # button that changes the range to [0,1000) and starts a new game    
  36.     global low, high
  37.     low = 0
  38.     high = 1000
  39.     new_game()
  40.    
  41. def input_guess(guess):
  42.     global count
  43.     guess = int(guess)
  44.     print "\nGuess was", guess
  45.     count -= 1
  46.     if count > 0:
  47.         print "Number of remaining guesses is", count
  48.         if guess == secret_number:
  49.             print "Correct!"
  50.             new_game()
  51.         elif guess < secret_number:
  52.             print "Higher!"
  53.         else:
  54.             print "Lower!"
  55.     elif count == 0 and guess == secret_number:
  56.         print "Correct!"
  57.         new_game()
  58.     else:
  59.         print "You ran out of guesses. Number was", secret_number
  60.         new_game()
  61.    
  62. # create frame
  63. frame = simplegui.create_frame('Guess the Number', 100, 200)
  64.  
  65. # register event handlers for control elements and start frame
  66. button100 = frame.add_button("Range is [0, 100)", range100, 200)
  67. button1000 = frame.add_button("Range is [0, 1000)", range1000, 200)
  68. inp = frame.add_input('Your Guess:', input_guess, 50)
  69.  
  70. frame.start()
  71.  
  72. # call new_game
  73. new_game()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement