Mini-project # 2 - "Guess the number" game"
第三周的作业,大致就是两个给定的上下界,在其中随机一个数,让用的人输入猜的数字,告知他实际的数字比猜的大还是小,一共有[log(upper) / log(2)]次机会,策略是二分。
这次是带界面的,库是老师写的simplegui,在下面的链接里(科学上网)
现在完成了第一部分。输出还是在控制台而不是在画布。。
思路大致是这样:
用全局变量存上下界,通过按钮的动作给出。每次一开始调用newgame做各种预处理,随机出给定的数,计算剩余剩余猜的次数等等。每次按按钮也要记得调用newgame
打分的时候发现有人一开始没调用。。貌似是不行的吧?
接下来输入的时候获取输入值判断什么的。。次数没了要重新开始。
用了try防止不合法输入。。自己玩起来还没有什么问题。除了不太方便。。。。。= =
体会是:
python的全局变量。。。是要在函数里声明的。。
开发貌似很练码力。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
1 # template for "Guess the number" mini-project 2 # input will come from buttons and an input field 3 # all output for the game will be printed in the console 4 5 import simplegui 6 import random 7 import math 8 guess_num = 0 9 secret_number = 0 10 11 upper = 100 12 remain_chance = 7 13 14 # helper function to start and restart the game 15 def new_game(): 16 # initialize global variables used in your code here 17 global secret_number, remain_chance 18 # remove this when you add your code 19 secret_number = random.randrange(0, upper) 20 remain_chance = int(math.ceil(math.log(upper)/math.log(2))) 21 print "New game start:","Range is [0,", upper,")" 22 print "Number of remaining guesses is", remain_chance 23 24 # define event handlers for control panel 25 def range100(): 26 # button that changes the range to [0,100) and starts a new game 27 global upper, remain_chance 28 # remove this when you add your code 29 upper = 100 30 remain_chance = 7 31 new_game() 32 33 def range1000(): 34 # button that changes the range to [0,1000) and starts a new game 35 global upper 36 remain_chance = 10 37 upper = 1000 38 new_game() 39 40 41 def input_guess(guess): 42 # main game logic goes here 43 global guess_num, remain_chance 44 # remove this when you add your code 45 try: 46 guess_num = int(guess) 47 except: 48 print "an integer please" 49 return 50 print "Guess was", guess 51 remain_chance -= 1 52 print "Number of remaining guesses is", remain_chance 53 #judge 54 if guess_num == secret_number: 55 print "Correct" 56 new_game() 57 return 58 elif guess_num > secret_number: print "Lower" 59 elif guess_num < secret_number: print "Higher" 60 61 #if run out of chance 62 63 if remain_chance == 0: 64 print "You ran out of chances" 65 new_game() 66 67 68 # call new_game 69 new_game() 70 71 72 # create frame 73 f = simplegui.create_frame("Guess", 200, 200) 74 75 76 # register event handlers for control elements and start frame 77 input_guess = f.add_input("enter what you guess", input_guess, 100) 78 reset = f.add_button("reset", new_game) 79 Range_100 = f.add_button("Range is [0,100)", range100) 80 Range_1000 = f.add_button("Range is [0,1000)", range1000) 81 f.start() 82 83 # always remember to check your completed program against the grading rubric