I have this piece of code in the end of my main function in a python pygame script. This seems to be the correct way to handle an exit with a simple keypush.
running = True
while running == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
break
elif event.type == pygame.KEYDOWN:
running = False
break
if running == False:
break
draw(screen, background)
pygame.quit() # quits pygame
sys.exit()
However in this draw
function I also have the following line right before the closing accolade:
pygame.time.delay(randint(2,5) * 1000)
This line of code makes the game wait anywhere from 2 till 5 seconds. Apparently this delay code creates an extra delay of about 3 loops in detecting the key pushes.
My question is: how do I properly execute an immediate exit with a key push without waiting for the delay?
Edit: Solution (credit to Håken Lid)
animate_event = pygame.USEREVENT
pygame.time.set_timer(animate_event, 1000)
while True:
if pygame.event.get(pygame.QUIT): break
if pygame.event.get(pygame.KEYDOWN): break
for event in pygame.event.get():
if event.type == animate_event:
animate(screen, background)
# reset event
pygame.time.set_timer(animate_event, randint(2,5)*1000)
pygame.quit()
sys.exit()