Remove with kill()
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 18 of 36.
Press Space and the ship fires: each press adds a Laser sprite to the lasers group, and the counter at the top left says how many the group holds. Fire a few and watch it climb. The lasers fly off the top and are never seen again, but the group still holds every one of them, and still updates and draws them all. After a few minutes of play that is thousands of invisible lasers.
A sprite that is done removes itself with kill():
def update(self):
self.rect.y -= 10
if self.rect.bottom < 0:
self.kill()kill() takes the sprite out of every group it is in. Nothing updates or draws it any more, and Python frees it once no variable refers to it. Test bottom, not top: the laser goes once its last pixel has left the window, never while part of it still shows.
sprite.alive() is True while a sprite is in at least one group.
Challenge
EasyIn Laser.update, after moving, call self.kill() when the laser's rect.bottom is above the top of the window (less than 0). The counter should drop back to 0 once every laser has left.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Lasers")
clock = pygame.time.Clock()
ship_image = pygame.image.load("assets/images/ship.png").convert_alpha()
laser_image = pygame.image.load("assets/images/laser.png").convert_alpha()
font = pygame.font.Font(None, 32)
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = ship_image
self.rect = self.image.get_rect(midbottom=(320, 470))
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.rect.x -= 6
if keys[pygame.K_RIGHT]:
self.rect.x += 6
self.rect.clamp_ip(screen.get_rect())
class Laser(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = laser_image
self.rect = self.image.get_rect(midbottom=(x, y))
def update(self):
self.rect.y -= 10
player = Player()
lasers = pygame.sprite.Group()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
lasers.add(Laser(player.rect.centerx, player.rect.top))
player.update()
lasers.update()
screen.fill((20, 22, 40))
lasers.draw(screen)
screen.blit(player.image, player.rect)
count = font.render(f"Lasers: {len(lasers)}", True, (240, 240, 240))
screen.blit(count, (10, 10))
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Sprites and Images
4Sprites and Groups
The Sprite ClassGroupsRemove with kill()Catch with spritecollideGroup Against Group3Classes for Game Objects
Your First ClassMethodsSelf Is the ObjectA List of ObjectsObjects with ImagesA SubclassPractice on your own: Pygame playground