Search code examples
pythontimersecondspygame-clockpygame-tick

how do you display time in the format 00:00? Currently, it displays the time in a decimal format


the timer works but i am having trouble displaying it in the format 00:00 - Currently, it displays the time in a decimal format for exapmle: 2.547959356:688.9846939

while True: # main game loop
        mouseClicked = False

        DISPLAYSURF.fill(BGCOLOR) # drawing the window
        drawBoard(mainBoard, revealedBoxes)

        counting_time = pygame.time.get_ticks() - start_time

        # change milliseconds into minutes, seconds
        counting_seconds = str(counting_time/1000 ).zfill(2)
        counting_minutes = str(counting_time/60000).zfill(2)

        counting_string = "%s:%s" % (counting_minutes, counting_seconds)

        counting_text = font.render(str(counting_string), 1, (0,0,0))

        DISPLAYSURF.blit(counting_text,(350,3))

        pygame.display.update()

        clock.tick(25)

Solution

  • while True: # main game loop
        mouseClicked = False
    
        DISPLAYSURF.fill(BGCOLOR) # drawing the window
        drawBoard(mainBoard, revealedBoxes)
    
        ########TIMER######
        # Calculate total seconds
        total_seconds = frame_count // frame_rate
        # Divide by 60 to get total minutes
        minutes = total_seconds // 60
        # Use modulus (remainder) to get seconds
        seconds = total_seconds % 60
        # Use python string formatting to format in leading zeros
        output_string = "Time: {0:02}:{1:02}".format(minutes, seconds)
        text = font.render((output_string), True, (0,0,0))
        DISPLAYSURF.blit(text,(350,3))
        frame_count += 1
        # Limit frames per second
        clock.tick(20)
        #update the screen with timer.
        pygame.display.flip()
    

    never mind I figure it out. however, it takes 4-5 seconds for the timer to increment by 1 second. I have already tried increasing and decreasing the clock ticks but it doesn't seem to help. Any suggestions to solve this?