Menu
CoddyTech

검 휘두르기

Coddy Pygame 여정의 프로젝트 섹션에 포함된 레슨. 31개 중 26번째.

스페이스바를 누르면 기사가 바라보는 방향으로 12프레임 동안 검을 휘두릅니다. 칼날에 닿은 슬라임은 사라집니다.

기사는 마지막으로 걸었던 방향을 knight.facing에 기억합니다. (1, 0)은 오른쪽, (0, -1)은 위쪽입니다. 칼날은 기사의 중앙에서 그 방향으로 34픽셀 떨어진 곳에 있는 36 x 36 상자입니다.

def sword(self):
    box = pygame.Rect(0, 0, 36, 36)
    box.centerx = self.rect.centerx + self.facing[0] * 34
    box.centery = self.rect.centery + self.facing[1] * 34
    return box

knight.swing은 휘두르는 동작의 프레임 수를 0까지 줄여 가며 세고, 0일 때만 스페이스바를 눌러 새 동작을 시작하므로 스페이스바를 계속 누르고 있어도 칼날이 계속 나와 있지 않습니다. 동작이 진행되는 동안 상자에 닿는 모든 적은 enemy.kill()로 제거됩니다. 이 함수는 스프라이트가 속한 모든 그룹에서 해당 스프라이트를 제거합니다.

sword.png는 위쪽을 향합니다. pygame.transform.rotate는 방향에 따른 각도만큼 시계 반대 방향으로 회전시킵니다.

ANGLES = {(0, -1): 0, (-1, 0): 90, (0, 1): 180, (1, 0): -90}
challenge icon

챌린지

어려움
  1. 그림 아래에 ANGLES를 추가하세요.
  2. 기사에 self.facing = (1, 0), self.swing = 0과 위에 나온 sword 메서드를 추가하세요.
  3. 각 방향키를 누를 때 knight.facing도 설정하세요: 왼쪽 (-1, 0), 오른쪽 (1, 0), 위쪽 (0, -1), 아래쪽 (0, 1).
  4. state == "playing"이고 knight.swing == 0일 때 스페이스바의 KEYDOWN 이벤트가 발생하면 knight.swing = 12로 설정하세요.
  5. 피격 여부를 확인하기 전에, knight.swing > 0인 동안 값을 1만큼 줄이고, rect가 knight.sword()와 충돌하는 모든 적에게 kill()을 호출하세요.
  6. 휘두르는 동안 기사 뒤에 pygame.transform.rotate(sword_img, ANGLES[knight.facing])를 knight.sword()의 중앙에 맞춰 그리세요.

직접 해보기

import random
import pygame

TILE = 48
MAP = [
    "##############",
    "#............#",
    "#.P......K...#",
    "#............#",
    "#....##......D",
    "#....##......#",
    "##.#######.###",
    "#............#",
    "#...S....H...#",
    "##############",
]

pygame.init()
screen = pygame.display.set_mode((672, 480))
pygame.display.set_caption("Rune Keep")
clock = pygame.time.Clock()
font = pygame.font.Font("assets/fonts/pixel.ttf", 32)


def load(name):
    return pygame.image.load("assets/images/" + name).convert_alpha()


floor_img = load("floor.png")
wall_img = load("wall.png")
knight_img = load("knight.png")
door_img = load("dungeon_door.png")
key_img = load("key.png")
slime_img = load("slime.png")
spider_img = load("spider.png")
heart_img = load("heart.png")
empty_img = load("heart_empty.png")
sword_img = load("sword.png")
potion_img = load("potion_red.png")


def draw(image, rect):
    screen.blit(image, image.get_rect(center=rect.center))


def cell_rect(col, row):
    rect = pygame.Rect(0, 0, 32, 32)
    rect.center = (col * TILE + 24, row * TILE + 24)
    return rect


class Enemy(pygame.sprite.Sprite):
    def __init__(self, image, rect, dx, dy):
        super().__init__()
        self.image = image
        self.rect = rect
        self.dx = dx
        self.dy = dy

    def update(self, blocks):
        self.rect.x += self.dx
        self.rect.y += self.dy
        if self.rect.collidelist(blocks) != -1:
            self.rect.x -= self.dx
            self.rect.y -= self.dy
            self.dx = -self.dx
            self.dy = -self.dy


class Room:
    def __init__(self, lines):
        self.walls = []
        self.enemies = pygame.sprite.Group()
        self.start = (72, 72)
        self.has_key = False
        self.door_open = False
        for row, line in enumerate(lines):
            for col, char in enumerate(line):
                if char == "#":
                    self.walls.append(pygame.Rect(col * TILE, row * TILE, TILE, TILE))
                elif char == "P":
                    self.start = cell_rect(col, row).center
                elif char == "K":
                    self.key = cell_rect(col, row)
                elif char == "D":
                    self.door = pygame.Rect(col * TILE, row * TILE, TILE, TILE)
                elif char == "S":
                    speed = random.choice([-2, 2])
                    self.enemies.add(Enemy(slime_img, cell_rect(col, row), speed, 0))

    def blocks(self):
        if self.door_open:
            return self.walls
        return self.walls + [self.door]


class Knight(pygame.sprite.Sprite):
    def __init__(self, center):
        super().__init__()
        self.image = knight_img
        self.rect = pygame.Rect(0, 0, 32, 32)
        self.rect.center = center
        self.hearts = 3
        self.hurt = 0

    def move(self, dx, dy, blocks):
        self.rect.x += dx
        for block in blocks:
            if self.rect.colliderect(block):
                if dx > 0:
                    self.rect.right = block.left
                elif dx < 0:
                    self.rect.left = block.right
        self.rect.y += dy
        for block in blocks:
            if self.rect.colliderect(block):
                if dy > 0:
                    self.rect.bottom = block.top
                elif dy < 0:
                    self.rect.top = block.bottom


room = Room(MAP)
knight = Knight(room.start)
state = "playing"

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    if state == "playing":
        keys = pygame.key.get_pressed()
        dx = 0
        dy = 0
        if keys[pygame.K_LEFT]:
            dx = -3
        if keys[pygame.K_RIGHT]:
            dx = 3
        if keys[pygame.K_UP]:
            dy = -3
        if keys[pygame.K_DOWN]:
            dy = 3
        knight.move(dx, dy, room.blocks())
        knight.rect.clamp_ip(screen.get_rect())

        if not room.has_key and knight.rect.colliderect(room.key):
            room.has_key = True
        if room.has_key and knight.rect.inflate(8, 8).colliderect(room.door):
            room.door_open = True

        room.enemies.update(room.walls + [room.door])

        if knight.hurt > 0:
            knight.hurt -= 1
        elif pygame.sprite.spritecollide(knight, room.enemies, False):
            knight.hearts -= 1
            knight.hurt = 60
            if knight.hearts == 0:
                state = "lost"

    for row in range(10):
        for col in range(14):
            screen.blit(floor_img, (col * TILE, row * TILE))
    for wall in room.walls:
        screen.blit(wall_img, wall)
    if not room.door_open:
        screen.blit(door_img, room.door)
    if not room.has_key:
        draw(key_img, room.key)
    for enemy in room.enemies:
        draw(enemy.image, enemy.rect)
    if knight.hurt % 10 < 5:
        draw(knight.image, knight.rect)
    for i in range(3):
        if i < knight.hearts:
            screen.blit(heart_img, (8 + i * 40, 6))
        else:
            screen.blit(empty_img, (8 + i * 40, 6))
    if room.has_key:
        screen.blit(key_img, (136, 6))
    if state == "lost":
        message = font.render("Game over", True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(336, 240)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz icon실력 점검

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

프로젝트의 모든 레슨

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