Totem
Totem

Reputation: 7369

spritecollide and killing sprites

I have two sprite groups, ship_list has 20 ship sprites, and all_sprites has those 20 sprites, plus the player sprite. In the main loop, when a collision is detected between the player and anything in ships_list, I understand that the ship sprite that collided with player is removed from ships_list. When I run the program, all sprites appear and by moving the player into a ship sprite it vanishes. All well and good, except.. I don't understand why they are vanishing. The reason being that though I know the ships are removed from ships_list after a collision, It is the all_sprites list that is actually being redrawn each frame, and I haven't explicitly removed anything from it at any point, so is it the case that the collision is also removing the ship sprite from all_sprites?

ship_list = pygame.sprite.Group() # just ship sprites
all_sprites = pygame.sprite.Group() # ship sprites + player sprite

while not done:

    for event in pygame.event.get():
        if event.type == pygame.QUIT or score == 20:
            done = True

    screen.fill(BLACK)

    pos = pygame.mouse.get_pos()

    player.rect.x = pos[0]
    player.rect.y = pos[1]

    **# is this line removing sprites from all_sprites??**
    ships_hit_list = pygame.sprite.spritecollide(player, ship_list, True) # detect collisions
    for ship in ships_hit_list:
        score += 1
        print score

    all_sprites.draw(screen) # seems to lose sprites when ships_list does..
    ship_list.update() # updating the position

    pygame.display.flip()

    clock.tick(24)

# properly quit
pygame.quit()

From https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.spritecollide

pygame.sprite.spritecollide()

Find sprites in a group that intersect another sprite.

spritecollide(sprite, group, dokill, collided = None) -> Sprite_list

Return a list containing all Sprites in a Group that intersect with another Sprite. Intersection is determined by comparing the Sprite.rect attribute of each Sprite.

The dokill argument is a bool. If set to True, all Sprites that collide will be removed from the Group. (It doesn't mention it removing it from any other group..)

Upvotes: 3

Views: 4358

Answers (1)

Bartlomiej Lewandowski
Bartlomiej Lewandowski

Reputation: 11190

If you look at what is shown when a sprite is printed, you will see that it shows in how many groups the sprite exists.

A Sprite has a method called kill:

remove the Sprite from all Groups

kill() -> None

The Sprite is removed from all the Groups that contain it. This won’t change anything about the state of the Sprite. It is possible to continue to use the Sprite after this method has been called, including adding it to Groups.

It seems that what sprite_collide does, it just calls kill() on the sprite if a collision has taken place.

Upvotes: 7

Related Questions