python 學習 : 一個簡單的秒表


 
游戲說明:綠色數字(左邊表示成功停止在整秒的次數,右邊表示停止的總次數)
點擊stop,如果小數點后為0,即你停止的時間是整秒數,右上方斜杠左邊數字加一

把代碼復制到這個網頁 code run here ,把原來的代碼覆蓋掉,然后點擊左上角的三角 運行就可以了。

import simplegui
import random
import math

time = 0 
message = "0:00.0"
success = 0 
total = 0
def forBC(t):
    if t < 10 :
        return "0" + str(t)
    else:
        return str(t)
def format(t):
    """ covert int to string a:bc:d """
    a = t // 600 
    t = t - a * 600 
    b = t // 10 
    d = t % 10 
    return str(a)+":"+forBC(b)+"."+str(d) 

#define event handler for buttons: start stop reset    
def start():
    timer.start()

def stop():    
    global success, total 
    if timer.is_running():
        timer.stop()
        total += 1 
        if (time % 10 == 0) :
           success += 1 
def reset():
    global time, message,success, total 
    timer.stop()
    time = 0
    success = 0; total = 0
    message = format(time)
def timer_handler():
    global time, message
    time += 1 
    message = format(time )
def draw_handler(canvas):
    canvas.draw_text(message, [20, 122], 40, "Red")
    canvas.draw_text(str(success)+"/"+str(total),[120,60],30,"Green")

frame = simplegui.create_frame("Stop Watch", 200, 200)
frame.add_button("start", start)
frame.add_button("stop", stop)
frame.add_button("reset",reset)
timer = simplegui.create_timer(100, timer_handler)
frame.set_draw_handler(draw_handler)

frame.start()
View Code

游戲詳細設計說明在這里 here 

學習總結:

學習使用timer 控制時間, 學習簡單的繪圖功能。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM