하위 클래스
Coddy Pygame 여정의 스프라이트와 이미지 섹션에 포함된 레슨. 36개 중 15번째.
일부 적은 지그재그로 움직여야 합니다. 다른 적들처럼 떨어지면서 좌우로 미끄러지고, 창 가장자리에서 방향을 바꿉니다. 메서드 하나를 바꾸기 위해 Enemy 클래스를 통째로 복사하면 버그를 두 번씩 수정해야 합니다. 하위 클래스는 부모 클래스의 모든 것을 물려받고 다른 부분만 바꿉니다:
class Zigzag(Enemy):
def __init__(self, image, x, y):
super().__init__(image, x, y)
self.dx = 3
def update(self):
super().update()
self.rect.x += self.dx
if self.rect.left < 0 or self.rect.right > 640:
self.dx = -self.dxclass Zigzag(Enemy)는 Zigzag가 Enemy라는 뜻입니다. 코드를 작성하지 않아도 draw를 사용할 수 있습니다. 자체 update가 부모 클래스의 메서드를 대체하고, super().update()가 부모 클래스의 버전을 먼저 실행하므로 떨어지는 동작과 위쪽으로 돌아가는 동작을 두 번 작성하지 않아도 됩니다. super().__init__(...)도 설정을 위해 같은 역할을 합니다.
Zigzag도 다른 적들과 같은 목록에 들어갑니다. 루프가 enemy.update()를 호출하면 각 객체가 자신만의 방식으로 업데이트를 실행합니다.
챌린지
중급class Zigzag(Enemy)를 작성합니다.__init__에서super().__init__(image, x, y)를 호출하고self.dx = 3을 설정합니다.update에서super().update()를 호출하고,self.dx를self.rect.x에 더한 다음, Rect가 왼쪽이나 오른쪽 가장자리 밖으로 튀어나오면self.dx의 부호를 반전합니다.enemies의 노란색 적을 Zigzag로 만들고, 빨간색과 초록색은 Enemy로 유지합니다.
직접 해보기
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Enemy Rain")
clock = pygame.time.Clock()
red = pygame.image.load("assets/images/enemy_red.png").convert_alpha()
green = pygame.image.load("assets/images/enemy_green.png").convert_alpha()
yellow = pygame.image.load("assets/images/enemy_yellow.png").convert_alpha()
class Enemy:
def __init__(self, image, x, y):
self.image = image
self.rect = image.get_rect(center=(x, y))
self.speed = 2
def update(self):
self.rect.y += self.speed
if self.rect.top > 480:
self.rect.bottom = 0
def draw(self, screen):
screen.blit(self.image, self.rect)
enemies = [Enemy(red, 160, 100), Enemy(green, 320, 100), Enemy(yellow, 480, 100)]
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
for enemy in enemies:
enemy.update()
screen.fill((20, 22, 40))
for enemy in enemies:
enemy.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
스프라이트와 이미지의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드