-3

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?

2 Answers2

0

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

Bob Smith
  • 220
  • 4
  • 21
0

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

import random
  • 3,054
  • 1
  • 17
  • 22