mini project : stopwatch

是在coursea上一门课程的作业,挺简单,还是有点意思的。老外的教学方式很值得国内高校学习。

任务也蛮简单的,就是写下面一个界面,和平常用的秒表功能相似。


mini project : stopwatch_第1张图片

我的代码如下(http://www.codeskulptor.org/#user12_CqTdPE3RLq_0.py):

# template for "Stopwatch: The Game"

import simplegui

# define global variables
# how much tenths second have passed
total_time = 0
win_number = 0
total_number = 0
display_string = "0:00.0"
running = False

# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):    
    result = ""
    tenth = t%10
    seconds = ((t-tenth)/10)%60
    minutes = ((t-tenth)/10 - seconds)/60
    minutes = minutes%10
    result += str(minutes)+":"
    if seconds < 10:
        result += "0"+str(seconds)
    else:
        result += str(seconds)
    result += "."+str(tenth)
    return result
    
# define event handlers for buttons;
# start watch handler
def start_watch():
    global running
    running = True
    timer.start()
    return 0

# stop watch handler
def stop_watch():
    global running
    global total_number
    global win_number
    global total_time
    
    if running == False:
        return 0
    if total_time%10 == 0:
        win_number += 1
    total_number += 1
    timer.stop()
    return 0

# reset watch handler
def reset_watch():
    
    global total_number
    global win_number
    global total_time
    global display_string
    global running
    
    total_number = 0
    win_number = 0
    total_time = 0
    display_string = "0:00.0"
    if running == True:
        running = False
        timer.stop()
    return 0

# define event handler for timer with 0.1 sec interval
def timer_process():
    global running
    global total_time
    global display_string
    
    if running == True:
        total_time += 1
        display_string = format(total_time)
    return 0

# define draw handler
def draw_frame(canvas):
    global total_time
    global win_number
    global total_number
    canvas.draw_text(format(total_time), [130, 150], 50, "White")
    canvas.draw_text(str(win_number)+"/"+str(total_number), [350, 30], 30, "White")
    return 0
    
# create frame
frame = simplegui.create_frame("Stopwatch", 400, 300)

# set draw handler for frame
frame.set_draw_handler(draw_frame)

# create a new timer
timer = simplegui.create_timer(100, timer_process)

# add butttons to frame
start_button = frame.add_button("Start", start_watch, 100)
stop_button = frame.add_button("Stop", stop_watch, 100)
reset_button = frame.add_button("Reset", reset_watch, 100)

# register event handlers


# start frame
frame.start()

# Please remember to review the grading rubric


你可能感兴趣的:(mini project : stopwatch)