2

I'm currently struggling with formatting the count up timer for my code. I want a regular timer that counts up in milliseconds, however, I can't figure out how to visually show this on the timer. At the moment it only shows milliseconds as opposed to minutes, seconds and milliseconds, so once the timer hits 100 milliseconds it simply keeps counting this way instead of 1 second 0 milliseconds. How can I get this to work?

import pygame
pygame.init()

screen = pygame.display.set_mode((450, 600))

timer_font = pygame.font.SysFont("Calibri", 38)
timer_sec = 0
timer_text = timer_font.render("00:00:00", True, (255, 255, 255))


timer = pygame.USEREVENT + 0                                      
pygame.time.set_timer(timer, 10)

running = True
while running:
    screen.fill((0, 0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == timer:
            if timer_sec < 600:
                timer_sec += 1
                timer_text = timer_font.render("00:00:%02i" % timer_sec, True, (255, 255, 255))
            else:
                pygame.time.set_timer(timer, 0)

    screen.blit(timer_text, (300, 20))
    pygame.display.update()

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
Retceps
  • 23
  • 3

1 Answers1

1

Do not use the timer event for this task as it will lead to inaccuracies. Use pygame.time.get_ticks() and calculate the hours, minutes and seconds in each frame. Render a new time text when the time has changed:

import pygame
pygame.init()

screen = pygame.display.set_mode((450, 600))
timer_font = pygame.font.SysFont("Calibri", 38)

start_time = pygame.time.get_ticks()
time_hms = 0, 0, 0
timer_surf = timer_font.render(f'{time_hms[0]:02d}:{time_hms[1]:02d}:{time_hms[2]:02d}', True, (255, 255, 255))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    time_ms = pygame.time.get_ticks() - start_time
    new_hms = (time_ms//(1000*60*60))%24, (time_ms//(1000*60))%60, (time_ms//1000)%60
    if new_hms != time_hms:
        time_hms = new_hms
        timer_surf = timer_font.render(f'{time_hms[0]:02d}:{time_hms[1]:02d}:{time_hms[2]:02d}', True, (255, 255, 255))

    screen.fill(0)
    screen.blit(timer_surf, (300, 20))
    pygame.display.update()

pygame.quit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174