Siguiendo con los minijuegos en python, traigo el cronómetro, el cual consiste en tratar de parar el reloj en el segundo exacto (2.0 y no 2.1).
Os recuerdo que usa una librería concreta del curso donde los hago, por lo que necesitáis copiar el código en CodeSkulptor para hacerlo funcionar.
Cronómetro: Pulsa para ver/ocultar el código
# template for "Stopwatch: The Game"
#import the graphics
import simplegui
# define global variables
#time
miliseconds = 0
#success/attempts
success=0
attempts=0
# format time into formatted string A:BC.D
def format(t):
#take the parts of the time
miliseconds = t % 10
seconds = (t/10) % 60 # 60 seconds is a minute
minutes = (t/600) % 10
#first the minutes
time=str(minutes)+ ":"
#check if neccessary to put another digit(zero)
if seconds<10:
time=time+ "0"
# concat the rest of the formatted string
time=time + str(seconds) + "." + str(miliseconds)
return time
# define event handlers for buttons; "Start", "Stop", "Reset"
# Start
def start():
stopwatch.start()
#Stop
def stop():
#check if is was running before make modifications
if stopwatch.is_running():
global attempts, success
stopwatch.stop()
#the method returns 1 if succes, 0 otherwise
success=success + stop_at_second(miliseconds)
attempts+=1
# Reset
def reset():
global miliseconds, attempts
stopwatch.stop()
miliseconds=0
attempts=0
# define succcess, return 1 if success, 0 otherwise
def stop_at_second(miliseconds):
second = miliseconds % 10
if second==0:
return 1
else:
return 0
# define event handler for timer with 0.1 sec interval
def tick():
global miliseconds
#only count miliseconds if clock is running
if stopwatch.is_running():
miliseconds=miliseconds+1
# define draw handler
def draw(canvas):
#get clock
clock=format(miliseconds)
#show clock and success
canvas.draw_text(clock, [95,200], 54, "White")
canvas.draw_text(str(success)+"/"+str(attempts), [230,30], 26, "Green")
# create frame
frame=simplegui.create_frame("Stopwatch", 300, 300)
# register event handlers
stopwatch=simplegui.create_timer(100, tick)
frame.add_button("Start", start, 200)
frame.add_button("Stop", stop, 200)
frame.add_button("Reset", reset, 200)
frame.set_draw_handler(draw)
# start frame
frame.start()

