Counting time in pygame

2019-08-02 18:12发布

I want to count time in pygame, when an event occurs. Ive read something in the documentation but I dont really understand on how to do it.

In the documentation you can get time in miliseconds but it starts counting when the pygame.init() is called. I want to count from 0 when the boolean is true.

import pygame
pygame.init()

loop = True

boolean = False

while loop:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.RETURN:
                boolean = True

     screen.fill((255, 255, 255))

     if boolean:
        # start counting seconds

     pygame.display.update()

Thanks for your time.

1条回答
Animai°情兽
2楼-- · 2019-08-02 18:41

To determine the time that has passed since a certain event, you just measure the time at that event and subtract it from the current time.

Here's a working example:

import pygame

pygame.init()

FONT = pygame.font.SysFont("Sans", 20)
TEXT_COLOR = (0, 0, 0)
BG_COLOR = (255, 255, 255)

loop = True
start_time = None
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
while loop:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                start_time = pygame.time.get_ticks()

    screen.fill(BG_COLOR)

    if start_time:
        time_since_enter = pygame.time.get_ticks() - start_time
        message = 'Milliseconds since enter: ' + str(time_since_enter)
        screen.blit(FONT.render(message, True, TEXT_COLOR), (20, 20))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
查看更多
登录 后发表回答