Saturday, May 11, 2013

A not so exciting game in Python: Stop Watch

Another week and another assignment. The game itself is not very exciting. You can start and stop the timer, every start is an attempt and every stop exactly at 0 is a win.



#  Author: RK
# "Stopwatch: The Game"

import simplegui
#import random

# global variables
width = 400
height = 200
time = 0
message = "StopWatch Game"
attempts = 0
wins = 0
started = False

# Helper Function
def format_time(t):
    """converts tenths of seconds to A:BC.D"""
    #global message
    i = t % 10
    j = int ( t / 10)
    k = j % 60
    l = int (j / 60)
    
    if k < 10:
        game_string = "0" + str(k)  
    else:
        game_string = str(k)
    return str(l) + ":" + game_string + "." + str(i) 
    
# define event handlers for buttons; "Start", "Stop", "Reset"
def start_timer():
    global started
    timer.start()
    started = True
    
def stop_timer():
    timer.stop();
    global time, wins, attempts, started
    if started:
        if time % 10 == 0:
            wins = wins + 1
        not started 
        attempts = attempts + 1 

def reset_timer():
    global time, started, attempts, wins
    timer.stop()
    time = 0
    wins = 0
    attempts = 0

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

# define draw handler
def draw_handler(canvas):
    canvas.draw_text(format_time(time), (120,120), 50, "White")
    canvas.draw_text("wins/attemps: " + str(wins) + "/" + str(attempts), (200,30), 20, "Yellow")
    
    
# create frame
f = simplegui.create_frame(message, width, height)

# register event handlers
f.add_button("Start", start_timer, 100);
f.add_button("Stop", stop_timer, 100);
f.add_button("Reset", reset_timer, 100);
timer = simplegui.create_timer(100, timer_handler)
f.set_draw_handler(draw_handler)

# start frame
f.start()

# Please remember to review the grading rubric