I am making a game in pygame and I want it to spawn a thing multiple times

Viewed 35

I am making a game in pygame and I want it to spawn a thing multiple times in different places but with my code, it spawns the things multiple times but it doesnt remain where it spawned. I know this is happening because it is in a while loop. plz explain in simple words if possible. heres the code:

def spawn_food():
    food = Food(random.randint(3, 797), random.randint(3, 797))
    food.draw()


player1 = Player(250, 200)
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    keys = pygame.key.get_pressed()
    if keys[pygame.K_RIGHT]:
        player1.x += 1
    if keys[pygame.K_LEFT]:
        player1.x -= 1
    if keys[pygame.K_UP]:
        player1.y -= 1
    if keys[pygame.K_DOWN]:
        player1.y += 1
    screen.fill((255, 255, 255))
    player1.draw()
    pygame.display.update()
1 Answers

spawn_food() needs to return the a new Food object:

def spawn_food():
    return Food(random.randint(3, 797), random.randint(3, 797))

You have to add the instances of Food to a list:

food_list = []
for i in range(5):
    food_list.append(spawn_food())

respectively

food_list = [spawn_food() for _ in range(5)]

Draw the elements of food_list in a loop inside the application loop:

while True:
    # [...]

    screen.fill((255, 255, 255))

    for food in food_list:
        food.draw()

    player1.draw()
    pygame.display.update()
Related