하트와 피격
Coddy Pygame 여정의 프로젝트 섹션에 포함된 레슨. 33개 중 27번째.
기사에게는 하트가 3개 있습니다. 슬라임에게 닿으면 하트가 하나 줄어들고, 하트가 0개가 되면 게임이 끝납니다.
pygame.sprite.spritecollide(knight, room.enemies, False)는 기사와 접촉한 적들의 목록입니다. False는 적들을 그룹에 그대로 둡니다.
기사를 스쳐 지나가는 슬라임은 약 30프레임 동안 기사와 접촉합니다. 매 프레임 하트를 하나씩 잃는다면 0.5초 만에 게임이 끝나겠죠. 그래서 공격을 받은 뒤 기사는 60프레임, 즉 1초 동안 무적입니다. knight.hurt가 남은 프레임 수를 세고, 이 값이 0보다 큰 동안에는 접촉해도 하트가 줄어들지 않습니다.
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"기사가 안전한 상태라는 것을 플레이어에게 보여 주세요. 피해를 입은 동안에는 knight.hurt % 10 < 5일 때만 기사를 그립니다. 기사가 깜빡이며 5프레임 동안 보이고 5프레임 동안 보이지 않습니다.
state는 Sky Runner와 같은 방식으로 작동합니다. 움직이는 모든 요소를 if state == "playing": 아래에 두면, "lost" 상태일 때 요새가 멈춰 있습니다.
챌린지
중급슬라임에게 기사의 하트를 깎게 하세요.
- 기사에
self.hearts = 3과self.hurt = 0을 지정하세요. state = "playing"으로 설정하세요. 업데이트 코드는if state == "playing":아래에, 피격 여부 검사는 적 처리 뒤에 넣으세요.knight.hurt % 10 < 5일 때 기사와 하트를 그리세요."lost"상태일 때 (336, 240)에Game over를 가운데 정렬해 표시하세요.
‘플레이’를 누르고 슬라임에 닿아 보세요. 하트 하나가 비워집니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
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
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
room.enemies.update(room.walls + [room.door])
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)
draw(knight.image, knight.rect)
if room.has_key:
screen.blit(key_img, (136, 6))
pygame.display.flip()
clock.tick(60)
pygame.quit()
프로젝트의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드