加上这一次的作业,这门莱斯大学的python课程的所有project都已经完成了。
这次作业中,收获最大的是关于编程风格的问题。
在运算符前后和逗号后面都要添加空格,除非紧邻着括号。类名要使用CamelCase,但方法和函数要使用lower_case_with_underscores。参考链接。
另外,python中的全局变量的用法和局部变量一样。在子函数中要对全局变量赋值,要事先使用global在子函数中声明。如果忘记了,错误很难被发现。
我的答案链接为这里,这个网站暂时只能在域名/save这个链接上保存代码。
答案代码如下:
# 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 random, simplegui, math
# initialize global variables used in your code
canvas_width = 100
canvas_height = 300
control_width = 200
object_width = 100
num_range_low = 0
num_range_high = 100
real_num = 0
remain_guess_times = 0
# helper function to start and restart the game
def new_game():
global real_num, remain_guess_times
real_num = random.randrange(num_range_low, num_range_high)
remain_guess_times = int(math.ceil(math.log(num_range_high - num_range_low + 1, 2)))
print ''
print 'New game start, number range is [', num_range_low, ',', num_range_high, ').'
print 'You have ', remain_guess_times, ' chances to guess.'
# define event handlers for control panel
def range100():
# button that changes range to range [0,100) and restarts
global num_range_low, num_range_high
num_range_low = 0
num_range_high = 100
new_game()
def range1000():
# button that changes range to range [0,1000) and restarts
global num_range_low, num_range_high
num_range_low = 0
num_range_high = 1000
new_game()
def input_guess(guess):
# main game logic goes here
global remain_guess_times
remain_guess_times -= 1
guess_num = int(guess)
print 'You guessed: ', guess_num, '. ',
print 'Your remained ', remain_guess_times, 'guess chances.',
if guess_num == real_num:
print 'Correct!'
new_game()
elif guess_num > real_num:
print 'Higher'
e