Menu
CoddyTech

kill()로 제거하기

Coddy Pygame 여정의 스프라이트와 이미지 섹션에 포함된 레슨. 36개 중 18번째.

스페이스바를 누르면 우주선이 발사합니다. 누를 때마다 lasers 그룹에 레이저 스프라이트가 하나 추가되고, 왼쪽 위의 카운터에는 그룹에 몇 개가 있는지 표시됩니다. 몇 발 발사하고 카운터가 올라가는 것을 지켜보세요. 레이저는 화면 위쪽으로 날아가 다시는 보이지 않지만, 그룹에는 여전히 모든 레이저가 남아 있고 계속해서 모두 업데이트하고 그립니다. 몇 분 동안 플레이하고 나면 보이지 않는 레이저가 수천 개에 달합니다.

역할을 마친 스프라이트는 kill()로 자신을 제거합니다.

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

kill()은 해당 스프라이트가 속한 모든 그룹에서 스프라이트를 제거합니다. 더 이상 업데이트하거나 그리지 않으며, 어떤 변수도 참조하지 않게 되면 Python이 메모리를 해제합니다. top이 아니라 bottom을 확인하세요. 레이저의 마지막 픽셀이 화면을 벗어났을 때 사라지도록 해야 하며, 레이저의 일부가 여전히 보이는 동안에는 사라지면 안 됩니다.

sprite.alive()는 스프라이트가 하나 이상의 그룹에 속해 있는 동안 True입니다.

challenge icon

챌린지

쉬움

Laser.update에서 레이저를 이동한 후, 레이저의 rect.bottom이 창의 위쪽보다 위에 있을 때(0보다 작을 때) self.kill()을 호출하세요. 모든 레이저가 화면을 벗어나면 카운터가 다시 0으로 내려가야 합니다.

직접 해보기

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 플레이그라운드