Skip to content Skip to sidebar Skip to footer

How To Execute Event Repeatedly In Python?

I'm new to pygame programming. I need that operation increases character's speed (who is represented as moving images on screen) every 10 seconds using 'self.vel+=1'. Probably pyga

Solution 1:

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


Solution 2:

Using Python's time module you can time ten seconds while your code is running and increase the speed after ten seconds have passed.


Post a Comment for "How To Execute Event Repeatedly In Python?"