# template for "Stopwatch: The Game"
import simplegui
import time

# define global variables
timer_seconds = 0	# number of seconds * 10 since start
timer_running = 0	# boolean to check if timer is running
total_stops = 0		# total no. of times stop button was pressed
good_stops = 0		# no. of times the timer was on an integer second

# add a leading zero
def zero_add(time_val):
    if time_val < 10:
        return "0" + str(time_val)
    return str(time_val)

# in tenths of seconds into formatted string A:BC.D
def format():
    global timer_seconds
    
    # find the number of tenth of seconds
    tenth = str(timer_seconds % 10)

    # find the number of seconds
    seconds = int(timer_seconds / 10)  
    
    # find the number of minutes
    minutes = str(int(seconds / 60))
    
    return minutes + ":" + zero_add(seconds) + ":" + tenth
    
# define event handler for timer with 0.1 sec interval
def update():
    global timer_seconds
    timer_seconds += 1
    
# define event handlers for buttons; "Start", "Stop", "Reset"
def start_button_handler():
    global timer_running
    timer.start()
    timer_running = 1
     
def stop_button_handler():
    global timer_running, total_stops, good_stops, timer_seconds
    timer.stop()
    if (timer_running == 1):
        total_stops += 1
        if ((timer_seconds % 10) == 0):
            good_stops += 1
    timer_running = 0
    
def reset_button_handler():
    global timer_seconds, total_stops, good_stops
    timer_seconds = total_stops = good_stops = 0
    timer.stop()

# define draw handler
def draw_handler(canvas):
    global timer_seconds
    canvas.draw_text(format(), (50, 50), 40, "Red")
    canvas.draw_text(str(good_stops) + "/" + str(total_stops), (260,20), 20, "Red")
    
# create frame
frame = simplegui.create_frame("Stopwatch: The Game", 300, 300)
frame.set_draw_handler(draw_handler)

start_button = frame.add_button("Start", start_button_handler, 80)
stop_button = frame.add_button("Stop", stop_button_handler, 80)
reset_button = frame.add_button("Reset", reset_button_handler, 80)

# register event handlers
timer = simplegui.create_timer(100, update)

# start frame
frame.start()
