순찰 중인 슬라임
Coddy Pygame 여정의 프로젝트 섹션에 포함된 레슨. 31개 중 24번째.
맵의 S 하나하나는 한 프레임에 2픽셀씩 행을 따라 미끄러지며 벽에서 되돌아가는 슬라임입니다.
Enemy 스프라이트는 자체 속도인 dx와 dy를 가지므로, 나중에 같은 클래스로 위아래로 움직이는 몬스터도 만들 수 있습니다. update는 스프라이트를 움직이고, 이제 블록과 겹치면 뒤로 물러난 다음 방향을 바꿉니다.
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.dyrect.collidelist(rects)는 겹치는 목록의 첫 번째 Rect의 인덱스를 반환하며, 겹치는 항목이 없으면 -1을 반환합니다.
슬라임은 Group인 room.enemies에 들어 있습니다. room.enemies.update(room.walls + [room.door])는 해당 목록을 전달해 모든 슬라임에 대해 update를 호출합니다. 문은 항상 목록에 있으므로 슬라임은 열린 문 밖으로 빠져나가지 않습니다.
random.choice([-2, 2])는 각 슬라임이 왼쪽 또는 오른쪽으로 움직이기 시작하게 하므로, 매번 같은 게임이 진행되지 않습니다.
챌린지
중급- 상단에
import random을 추가합니다. class Enemy(pygame.sprite.Sprite)를 작성하고,__init__(self, image, rect, dx, dy)에서 네 값을 모두 속성으로 저장한 다음 위의update메서드를 작성합니다.Room에서self.enemies = pygame.sprite.Group()를 설정합니다.S가 있으면speed = random.choice([-2, 2])로 지정하고Enemy(slime_img, cell_rect(col, row), speed, 0)를 추가합니다.- 매 프레임 문을 그린 다음
room.enemies.update(room.walls + [room.door])를 호출합니다. - 기사보다 먼저
draw(enemy.image, enemy.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")
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)
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)
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
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.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
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)
draw(knight.image, knight.rect)
if room.has_key:
screen.blit(key_img, (136, 6))
pygame.display.flip()
clock.tick(60)
pygame.quit()
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
프로젝트의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드