当事件发生时,我想在pygame中计算时间。我已经阅读了文档中的内容,但我真的不明白如何去做。
在文档中,您可以获得以毫秒为单位的时间,但是在调用pygame.init()时它会开始计数。当布尔值为真时,我想从0开始计数。
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()
感谢您的时间。
答案 0 :(得分:2)
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()