I'm attempting to set up a if statement to remove a sprite while the image disappears the sprite stays around (keeps activating the if statement

Viewed 36

I added an If statement to my project to allow it to have one of the entities be eaten but it doesn't seem to want to work as while the image disappears the actual entity doesn't

if prey.is_collided_with(carrot):
    print('works')
    carrot.kill()
    all_sprites.remove(carrot)

when it deletes the carrot it causes the word "works to constantly be printed I'm not sure if its because the entity doesnt move after it has "eaten" the carrot but it doesn't seem to work how I intended it too

1 Answers

See pygame.sprite.Sprite.kill:

The Sprite is removed from all the Groups that contain it. This won't change anything about the state of the Sprite.

The variable carrot is still valid. Create a Group for the carrots and use the Group rather than the variable:

pygame.init()#setsup pygame
screen = pygame.display.set_mode((1000,800))#setsup screen
clock = pygame.time.Clock()#tells program how fast to update

timmer = 1#how long program has gone on for
#setsup the classes
predator = Predator()
prey = Prey()
carrot = Carrot()

#setsup the classes as sprites
all_sprites = pygame.sprite.Group()
all_sprites.add(predator)
all_sprites.add(prey)
all_sprites.add(carrot)

carrot_group = pygame.sprite.Group()
carrot_group.add(carrot)

#start of program
running=True
while running:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False

    movementx, movementy = Track(predator.x, prey.x, predator.y, prey.y)#how the predators move
    predator.move(movementx, movementy)

    carrots = carrot_group.sprites()
    if len(carrots) > 0:
        movementx, movementy = Track(prey.x, carrots[0].x, prey.y, carrots[0].y)#how the prey move
        prey.move(movementx, movementy)

    screen.fill((0,128,0))#background
    all_sprites.draw(screen)#makes the sprites
    pygame.display.update()#updates screen
    timmer=timmer+1

    for carrot in carrots:
        if prey.is_collided_with(carrot):
            print('works')
            carrot.kill()
    
pygame.quit()
exit()
Related