Friday, October 2, 2015

Stop Watch game - Python

# template for "Stopwatch: The Game"
import simplegui

# define global variables
width = 300
height = 300
interval = 100
running = False
gameplayed = 0
gamewon = 0
time = 0
position = [80, 150]
text_position = [260, 20]

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

def stop():
    global running, gameplayed, gamewon, time
    timer.stop()
    if running == True:
        gameplayed += 1
        if time%10 == 0:
            gamewon += 1
    running = False

def reset():
    global time, gameplayed, gamewon, running
    time = 0
    timer.stop()
    running = False
    gameplayed = 0
    gamewon = 0

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

# define draw handler
def draw(canvas):
    global gamewon, gameplayed
    canvas.draw_text(format(time), position, 48, "Red")
    canvas.draw_text(str(gamewon)+"/"+str(gameplayed), text_position, 20, "Green")
    
# create frame
frame = simplegui.create_frame("Stopwatch", width, height)

# register event handlers
frame.set_draw_handler(draw)
timer = simplegui.create_timer(100, tick)
frame.add_button("Start", start, 100)
frame.add_button("Stop", stop, 100)
frame.add_button("Reset", reset, 100)

# start frame
frame.start()
#timer.start()




# Please remember to review the grading rubric

No comments:

Post a Comment