I'm trying to randomly create an obstacle in a simple game every 0.5 - 2 seconds. I already have a function for creating my obstacle, but I can't time the instantiation. I've tried researching this, but I haven't come up with anything relevant. Could you guys help me out?
2 Answers
You can schedule your own events with pygame.time.set_timer
Here's a minimal example that changes the background color every 0.5-2 seconds:
import pygame, random
pygame.init()
screen, bg = pygame.display.set_mode((200, 200)), pygame.color.Color('Grey')
pygame.time.set_timer(pygame.USEREVENT, random.randint(500, 2001))
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT: break
if e.type == pygame.USEREVENT:
bg = random.choice(pygame.color.THECOLORS.values())
pygame.time.set_timer(pygame.USEREVENT, random.randint(500, 2001))
else:
screen.fill(bg)
pygame.display.flip()
continue
break

- 99,095
- 21
- 171
- 219
There are a lot of ways you can do this. You didn't submit your code so I am going to give a simple sample program that accomplishes this.
import pygame
pygame.init()
import random
clock = pygame.time.Clock()
milliseconds_until_event = random.randint(500, 2001)
milliseconds_since_event = 0
frames_per_second = 20
while True:
milliseconds_since_event += clock.tick(frames_per_second)
# handle input here
if milliseconds_since_event > milliseconds_until_event:
# perform your random event
milliseconds_until_event = random.randint(500, 2001)
milliseconds_since_event = 0
# draw screen here
The milliseconds_until_event
variable is going to store a number between 500 and 2000. This represents what you asked regarding an event happening every .5 to 2 seconds.
The milliseconds_since_event
variable is used to tell us how long it has been since our last random event. You can think of it as a counter in a loop if that helps.
The magic is happening at clock.tick(frames_per_second)
line. The tick function will return how long it has been in milliseconds since the tick function was called. We add that number to milliseconds_since_event
so we can get a total of how long it has been since our last event.
When we are past the threshold stored in milliseconds_until_event
we perform the random event and then set milliseconds_until_event
to .5 to 2 seconds again and milliseconds_since_event
to zero.
Rinse and repeat.

- 827
- 6
- 10