[Solved] How to execute event repeatedly in Python?


Here’s a simple example using a timer. The screen is filled with a color that changes every 0.4 seconds.

import pygame
import itertools

CUSTOM_TIMER_EVENT = pygame.USEREVENT + 1
my_colors = ["red", "orange", "yellow", "green", "blue", "purple"]
# create an iterator that will repeat these colours forever
color_cycler = itertools.cycle([pygame.color.Color(c) for c in my_colors])

pygame.init()
pygame.font.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([320,240])
pygame.display.set_caption("Timer for Dino Gržinić")
done = False
background_color = next(color_cycler)
pygame.time.set_timer(CUSTOM_TIMER_EVENT, 400)  
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == CUSTOM_TIMER_EVENT:
            background_color = next(color_cycler)
    #Graphics
    screen.fill(background_color)
    #Frame Change
    pygame.display.update()
    clock.tick(30)
pygame.quit()

The code to create the timer is pygame.time.set_timer(CUSTOM_TIMER_EVENT, 400). This causes an event to be generated every 400 milliseconds. So for your purpose, you’ll want to change that to 10000. Note you can include underscores in numeric constants to make it more obvious, so you could use 10_000.

Once the event is generated, it needs to be handled, so that’s in the elif event.type == CUSTOM_TIMER_EVENT: statement. That’s where you’ll want to increase the velocity of your sprite.

Finally, if you want to cancel the timer, e.g. on game over, you supply zero as the timer duration: pygame.time.set_timer(CUSTOM_TIMER_EVENT, 0).

Let me know if you need any clarifications.

Running Example

solved How to execute event repeatedly in Python?