Menu
CoddyTech

하위 클래스

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

일부 적은 지그재그로 움직여야 합니다. 다른 적들처럼 떨어지면서 옆으로 미끄러지고, 창 가장자리에서 방향을 바꿉니다. 한 메서드를 바꾸려고 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.dx

class Zigzag(Enemy)는 Zigzag가 Enemy라는 뜻입니다. 직접 작성하지 않아도 draw를 사용할 수 있습니다. Zigzag의 update는 부모 클래스의 메서드를 대체하고, super().update()는 부모 클래스의 버전을 먼저 실행하므로 떨어지는 동작과 맨 위로 돌아가는 동작을 두 번 작성할 필요가 없습니다. super().__init__(...)도 초기 설정을 같은 방식으로 처리합니다.

Zigzag도 다른 적들과 같은 목록에 들어갑니다. 루프는 enemy.update()를 호출하고 각 객체는 자신만의 방식으로 업데이트를 실행합니다.

challenge icon

챌린지

중급

노란 적이 지그재그로 움직이게 하세요.

  1. class Zigzag(Enemy)를 작성하세요. __init__은 super().__init__(image, x, y)를 호출하고 self.dx = 3을 설정합니다.
  2. update는 super().update()를 호출하고, self.dx를 self.rect.x에 더한 다음, Rect가 왼쪽 또는 오른쪽 가장자리 밖으로 삐져나오면 self.dx의 방향을 바꿉니다.
  3. 노란 적을 Zigzag로 만드세요.

‘플레이’를 누르세요. 노란 적이 지그재그로 움직입니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

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()
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

스프라이트와 이미지의 모든 레슨

직접 연습해 보세요: Pygame 플레이그라운드