한 번 재생되는 폭발
Coddy Pygame 여정의 스프라이트와 이미지 섹션에 포함된 레슨. 36개 중 28번째.
일부 애니메이션은 한 번 재생된 뒤 끝납니다. 폭발 애니메이션은 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를 가지므로, 서로 다른 순간에 시작한 폭발 열 개는 각각 처음부터 재생됩니다. 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 플레이그라운드