Python/Pygame Help?

DTCuber

Member
Hello,

I am creating a speedcubing timer with Python and Pygame. I need some help with making the timer portion of it. This is what I have so far. My idea is to record the time.time() when space is first pressed. Then, when space is pressed again, it records the time.time() again. By finding the elapsed time, I can see how long a solve took. However, my code doesn't seem to work. Any tips? Are there any other ways to record the time?

Code:
def timer():
timer_font = pygame.font.SysFont("monospace", 48)
running = timer_font.render("running", 1, (255, 255, 0))
screen.fill((0, 0, 0))
key = pygame.key.get_pressed()
if key[pygame.K_SPACE]:
start_time = time.time()
screen.fill((0, 0, 0))
screen.blit(running, (150, 200))
if key[pygame.K_SPACE]:
stop_time = time.time()
elapsed_time = stop_time - start_time
solve_time = timer_font.render(str(elapsed_time), 1, (255, 255, 0))
screen.fill((0, 0, 0))
screen.blit(solve_time, (175, 200))
Thanks in advance for any help!

Sincerely,
DTCuber

AlphaSheep

Member
Using time.time() is a correct way to do it. A good idea is to have a boolean flag that stores the current state of the timer (running vs not running), and then in your main loop, you check whether or not space has been pressed.
Code:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if isRunning:
# Stop the timer and display the time
else:
# Start the timer
An important point is that you'll want your main loop to run at a time that's faster than your timer accuracy, so if you want to measure the time accurate to 0.01 seconds, then you'll wan't the main loop to run at more than 100fps. If you're also updating the display, then that may be overkill, so you may want to have the main loop running at say 120fps, and then have the display update only every second or even fourth iteration.