Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

pygame - 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 pygame.time.set_timer) would do it but I don't know how to use it. Because I use window with moving images, time.sleep wouldn't be good idea because then window would freeze. What should be the best option and how to use it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...