I want to start my program, measure the time when the program starts and then wait some seconds, push a button (K_RIGHT) and messure the time when I push the button. I am using Pygame to registrate the Keydown. But in my code below it does not registrate my Keydown. What I am doing wrong here?
start = time.time()
for e in pygame.event.get():
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_RIGHT:
end= time.time()
diff = end-start
解决方案
Here's a minimal, complete example that prints the correct time difference. The passed time is just the difference between time.time() (now) and the start time.
You could use pygame.time.get_ticks instead of time.time as well (it returns the time in milliseconds instead of seconds).
import time
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
start = time.time()
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_RIGHT:
diff = time.time() - start
print(diff)
screen.fill(BG_COLOR)
pg.display.flip()
clock.tick(60)
pg.quit()