1

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?

I.A.S.
  • 81
  • 2
  • 11
  • Does random help? https://docs.python.org/2/library/random.html – luoluo Jul 31 '15 at 04:29
  • possible duplicate of [Executing periodic actions in Python](http://stackoverflow.com/questions/8600161/executing-periodic-actions-in-python) – wwii Jul 31 '15 at 04:56

2 Answers2

3

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
sloth
  • 99,095
  • 21
  • 171
  • 219
2

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.

Eric Bulloch
  • 827
  • 6
  • 10