Menu
CoddyTech

使用 kill() 移除

本课属于 Coddy Pygame 学习旅程的“精灵与图像”单元。第 19 课,共 39 课。

按下空格键,飞船就会发射:每按一次,都会向 lasers 组添加一个 Laser 精灵,左上角的计数器会显示这个组中有多少个精灵。发射几次,看看计数如何增加。激光会飞出窗口顶部,再也不会出现,但这个组仍然保留着每一个激光精灵,并继续更新和绘制它们。玩几分钟后,就会有数千个不可见的激光精灵。

精灵完成任务后,会用 kill() 将自己移除:

def update(self):
    self.rect.y -= 10
    if self.rect.bottom < 0:
        self.kill()

kill() 会将精灵从它所属的所有组中移除。它不再被更新或绘制;一旦没有变量引用它,Python 就会释放它。检查 bottom,而不是 top:激光要等到最后一个像素离开窗口后才会移除,不会在它仍有一部分显示时移除。

当精灵至少属于一个组时,sprite.alive() 的值为 True。

challenge icon

挑战

简单

每束激光离开窗口后都将其移除。

  1. 在 Laser.update 中,移动后检查 self.rect.bottom < 0。
  2. 如果条件成立,就调用 self.kill()。

按“开始”并发射几束激光:它们消失后,计数器会归零。然后按“检查”。

亲手试试

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()

精灵与图像中的所有课

自己练习: Pygame 在线编辑器