Menu
CoddyTech

기사

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

기사는 지도에서 P가 있는 곳에서 시작합니다.

기사의 그림은 타일 하나와 같은 크기인 48 x 48이며, 벽 사이의 틈도 마찬가지입니다. 48픽셀 Rect는 정확한 픽셀 위치에 맞춰야만 틈에 들어갑니다. 그래서 기사의 Rect는 그림보다 작은 32 x 32이고, 그림은 Rect의 가운데에 그려집니다. 충돌하는 것은 Rect이고, 보이는 것은 그림입니다.

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

cell_rect(col, row)는 타일 가운데에 있는 32 x 32 Rect입니다. 기사는 Sky Runner의 러너처럼 한 지점에 만들어지는 스프라이트입니다.

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
challenge icon

챌린지

중급

첫 번째 방에서 기사가 P 위에 서 있도록 하세요.

  1. 위에 draw 함수와 cell_rect 함수를 추가하세요.
  2. Room에서 self.start = (72, 72)로 설정하고, P가 있으면 self.start = cell_rect(col, row).center로 설정하세요.
  3. 위에 Knight 클래스를 작성하고, 방을 만든 다음 knight = Knight(room.start)를 작성하세요.
  4. 벽을 그린 다음 draw(knight.image, knight.rect)를 호출하세요.

‘플레이’를 누르세요. 기사가 P 위에 서 있습니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

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")


class Room:
    def __init__(self, lines):
        self.walls = []
        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))


room = Room(MAP)

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

    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)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

프로젝트의 모든 레슨

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