한 번 재생되는 폭발
Coddy Pygame 여정의 스프라이트와 이미지 섹션에 포함된 레슨. 39개 중 29번째.
일부 애니메이션은 한 번 재생되고 끝납니다. 폭발 애니메이션은 explosion_1.png부터 explosion_4.png까지 보여 준 뒤 사라집니다. 스프라이트 자체의 카운터를 사용해 재생할 수 있으며, 그림이 모두 소진되면 스프라이트를 제거할 수 있습니다.
def update(self):
self.timer += 1
if self.timer == 5:
self.timer = 0
self.index += 1
if self.index == len(explosion_frames):
self.kill()
else:
self.image = explosion_frames[self.index]각 폭발 애니메이션은 자체 timer와 index를 가지므로 서로 다른 시점에 시작한 폭발 10개도 각각 처음부터 재생됩니다. self.image만 변경하면 됩니다. 그룹은 스프라이트가 현재 가지고 있는 그림을 그립니다.
목록을 읽기 전에 끝인지 확인하세요. explosion_frames[4]는 존재하지 않으며, 마지막 그림이 5프레임 동안 표시된 뒤에는 kill()이 폭발을 그룹에서 제거합니다. 창 안의 아무 곳이나 클릭해 폭발을 일으키세요.
챌린지
중급Explosion에 한 번만 재생되는 update 메서드를 추가하세요.
- 5프레임마다
explosion_frames의 다음 그림으로 이동하세요. - 네 번째 그림이 5프레임 동안 표시된 후
self.kill()을 호출하세요.
‘플레이’를 누르고 클릭하세요. 폭발 애니메이션이 재생된 뒤 사라집니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Explosions")
clock = pygame.time.Clock()
explosion_frames = []
for n in range(1, 5):
explosion_frames.append(pygame.image.load(f"assets/images/explosion_{n}.png").convert_alpha())
class Explosion(pygame.sprite.Sprite):
def __init__(self, center):
super().__init__()
self.index = 0
self.timer = 0
self.image = explosion_frames[0]
self.rect = self.image.get_rect(center=center)
explosions = pygame.sprite.Group()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
explosions.add(Explosion(event.pos))
explosions.update()
screen.fill((20, 22, 40))
explosions.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
스프라이트와 이미지의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드