How to periodically spawn objects in Pygame

282 Views Asked by At

elif x1 == foodx2 and y1 == foody2:

        foodx2 = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
        foody2 = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
        Length_of_snake += 2

this is the code for food gen after it has been eaten once how do I delay its spawning by 10 seconds For eg. I want a food type to spawn 10 seconds after being eaten by the snake but am unable to do so without also stopping the snake.

I tried using the sleep() function but it also froze the snake on the spot for 10 seconds rather than letting the snake move freely but not spawning the food for 10 seconds.

1

There are 1 best solutions below

0
On

you can use pygame timer function to set the spawn time for particular objects like food, enemies etc. It has a particular time frame to be triggered. In below example, food is triggered every 250ms.

# Create a custom event for adding a new food
ADDFOOD = pygame.USEREVENT + 1
pygame.time.set_timer(ADDFOOD, 250)