기사가 걷는다
Coddy Pygame 여정의 프로젝트 섹션에 포함된 레슨. 31개 중 22번째.
기사는 지도에서 P가 있는 칸에서 시작해 방향키로 한 프레임당 3픽셀씩 이동합니다.
기사 그림은 타일 하나 크기인 48×48이고, 벽 사이의 간격도 마찬가지입니다. 48픽셀 Rect는 정확히 픽셀에 맞춰야만 간격에 들어갈 수 있습니다. 그래서 기사의 Rect는 그림보다 작은 32×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벽은 Moss Caves의 플랫폼과 같은 방식으로 기사의 이동을 막습니다. x축을 따라 이동하고, 겹치는 벽이 있으면 밀어낸 다음, y축을 따라 똑같이 합니다. 한 번에 한 축씩 처리하면 어느 쪽에 부딪혔는지 알 수 있습니다.
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
# 그런 다음 dy에 대해서도 bottom과 top을 사용해 동일하게 처리챌린지
어려움- 위에
draw함수와cell_rect함수를 추가합니다. Room에서 반복문 전에self.start = (72, 72)를 설정하고,P에 대해서는self.start = cell_rect(col, row).center를 설정합니다.class Knight(pygame.sprite.Sprite)를 작성합니다. 이 클래스의__init__(self, center)는self.image = knight_img와center를 중심으로 하는 32 x 32 크기의self.rect를 설정합니다. 위에 나온move(dx, dy, blocks)메서드에 y 부분을 추가합니다.- 방 다음에
knight = Knight(room.start)를 만듭니다. - 매 프레임마다 왼쪽 키를 누르면
dx를 -3으로, 오른쪽 키를 누르면 3으로 설정합니다. 위쪽 키를 누르면dy를 -3으로, 아래쪽 키를 누르면 3으로 설정하고, 그렇지 않으면 0으로 설정한 다음knight.move(dx, dy, room.walls)를 호출합니다. - 벽을 그린 다음 기사를 그립니다.
draw(knight.image, knight.rect)
직접 해보기
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 플레이그라운드