열쇠와 문
Coddy Pygame 여정의 프로젝트 섹션에 포함된 레슨. 33개 중 25번째.
오른쪽 벽에 있는 문은 잠겨 있습니다. 기사는 열쇠 위를 걸어가 열쇠를 줍고, 열쇠를 가지고 있으면 문에 닿을 때 문이 열립니다.
잠긴 문은 기사를 막는 또 하나의 장애물입니다. Room의 메서드는 기사를 막는 Rect 목록을 반환합니다.
def blocks(self):
if self.door_open:
return self.walls
return self.walls + [self.door]문에 닿게 하는 데에는 한 가지 문제가 있습니다. move는 매 프레임 기사를 문 밖으로 밀어내므로, 기사의 Rect는 문과 절대 겹치지 않습니다. knight.rect.inflate(8, 8)은 기사의 Rect를 모든 방향으로 4픽셀씩 키운 복사본이며, 이 복사본은 기사가 맞닿아 있는 문과 겹칩니다.
if room.has_key and knight.rect.inflate(8, 8).colliderect(room.door):
room.door_open = True열린 문 너머에는 창의 가장자리가 있으므로 clamp_ip로 기사가 창 안에 머물게 하세요. 이후 강의에서는 문을 지나 다음 방으로 이동합니다. 기사가 열쇠를 가지고 있는 동안 화면 위쪽에 열쇠를 표시하세요.
챌린지
중급기사가 열쇠를 찾을 때까지 문을 잠가 두세요.
Room에서:self.has_key = False와self.door_open = False를 설정합니다.K는self.key = cell_rect(col, row)를 설정하고,D는self.door를 48×48 타일 Rect로 설정합니다.blocks()를 추가합니다.knight.move(dx, dy, room.blocks())를 호출한 다음knight.rect.clamp_ip(screen.get_rect())를 호출합니다.room.key에 닿으면room.has_key = True로 설정합니다. 그런 다음 위와 같이 문을 엽니다.
‘플레이’를 누르세요. 열쇠를 가져갈 때까지 문은 닫혀 있습니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
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 Room:
def __init__(self, lines):
self.walls = []
self.start = (72, 72)
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
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
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)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
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.walls)
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)
draw(knight.image, knight.rect)
pygame.display.flip()
clock.tick(60)
pygame.quit()
프로젝트의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드