How do I timeout only a specific function while the rest of the game loop continues to run

Question:

I’m making a basic pygame where you need to shoot some ships that are spawning every few seconds, so here is the problem :
I have a function that spawns my ship at a random x and y position. How do I make this function timeout every 4 seconds so that it doesn’t spawn the ships too quickly but while also not interrupting the main game loop.

E.G :

def spawn_ship():
    # functions that spawn the ship
    # How do I make this run once every 5 seconds while not interrupting the main game loop


def main():
   while True:
      spawn_ship()
Asked By: Grejuc Andrei

||

Answers:

If you want to control something over time in Pygame you have two options:

  1. Use pygame.time.get_ticks() to measure time and and implement logic that controls the object depending on the time.

  2. Use the timer event. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. Change object states when the event occurs.

For a timer event you need to define a unique user events id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). In this case pygame.USEREVENT+1 is the event id for the timer event.
Receive the event in the event loop:

def spawn_ship():
    # [...]

def main():
    spawn_ship_interval = 5000 # 5 seconds
    spawn_ship_event_id = pygame.USEREVENT + 1 # 1 is just as an example
    pygame.time.set_timer(spawn_ship_event_id, spawn_ship_interval)

    run = True
    while run:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

             elif event.type == spawn_ship_event_id:
                 spawn_ship()

Also see Spawning multiple instances of the same object concurrently in python and How to run multiple while loops at a time in Pygame.

Answered By: Rabbid76

You could try making spawn_ship async, then use a thread so it doesn’t affect the main loop

import threading

def main():
   threading.Timer(5.0, spawn_ship).start()

async def spawn_ship():
   # ...

Answered By: jayer
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.