Python交互小游戏(二):Stopwatch——Canvas,drawing,timers

We will focus on combining text drawing in the canvas with timers to build a simple digital stopwatch that keeps track of the time in tenths of a second. The stopwatch should contain “Start”, “Stop” and “Reset” buttons.

To turn your stopwatch into a test of reflexes, add to two numerical counters that keep track of the number of times that you have stopped the watch and how many times you manage to stop the watch on a whole second (1.0, 2.0, 3.0, etc.). These counters should be drawn in the upper right-hand part of the stopwatch canvas in the form “x/y” where x is the number of successful stops and y is number of total stops.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# from __future__ import division
try:
import simplegui
except ImportError:
import simpleguics2pygame as simplegui


# ================================ my code ================================

# "Stopwatch: The Game"

# define global variables
total_ticks = 0
successful_stops = 0
total_stops = 0
interval_ticks = 10 # manage to stop the watch on 5s
#stop_ticks = None # record the time that user have stopped the watch
is_running = False

# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
tenths = t % 10
seconds = t / 10 % 60
minutes = t / 10 / 60

if(seconds < 10): seconds_text = '0' + str(seconds)
else: seconds_text = str(seconds)

return str(minutes) + ':' + seconds_text + '.' + str(tenths)

# define event handlers for buttons; "Start", "Stop", "Reset"
def start_btn_handler():
global is_running
is_running = True
timer.start()

def stop_btn_handler():
global total_ticks, interval_ticks, total_stops, successful_stops, is_running
timer.stop()
#print 'total_ticks =', total_ticks
if(is_running):
total_stops = total_stops + 1
if(total_ticks % interval_ticks == 0):
successful_stops = successful_stops + 1
is_running = False

def reset_btn_handler():
global total_ticks, successful_stops, total_stops, is_running
timer.stop()
total_ticks = 0
successful_stops = 0
total_stops = 0
is_running = False

# define event handler for timer with 0.1 sec interval
def tick():
global total_ticks
total_ticks = total_ticks + 1

# define draw handler
def draw_handler(canvas):
global total_ticks, total_stops, successful_stops
canvas.draw_text(format(total_ticks), (45, 90), 40, 'White')
canvas.draw_text(str(successful_stops)+'/'+str(total_stops), (150, 30), 25, 'Red')

# create frame
timer = simplegui.create_timer(100, tick)
frame = simplegui.create_frame("Stopwatch", 200, 150)
frame.set_draw_handler(draw_handler)

# register event handlers
frame.add_button('Start', start_btn_handler, 100)
frame.add_button('Stop', stop_btn_handler, 100)
frame.add_button('Reset', reset_btn_handler, 100)

# start frame
frame.start()