가시와 하트
Coddy Pygame 여정의 게임 월드 섹션에 포함된 레슨. 35개 중 32번째.
게임에는 위험 요소가 필요합니다. 탐험가는 하트로 표시되는 생명 3개를 가지고 있습니다. 가시에 닿거나 동굴 밖으로 떨어지면 생명을 하나 잃습니다.
가시는 타일의 아래쪽 절반만 차지하므로, 가시의 Rect는 아래쪽 절반입니다: pygame.Rect(rect.x, rect.y + 18, TILE, 18). 이미지는 타일의 모서리에 맞춰 18픽셀 위쪽에 그립니다.
여러 위험 요소가 같은 동작을 합니다. 생명을 하나 잃고 탐험가를 시작 지점으로 돌려보냅니다. 이 요소들에 공통 플래그 하나를 지정하고, 그 플래그에 따라 동작하는 블록을 하나 만듭니다:
hurt = False
if player.top > HEIGHT:
hurt = True
for spike in spikes:
if player.colliderect(spike):
hurt = True
# 나중에
if hurt:
lives -= 1
player.midbottom = start
vel_y = 0하트 세 개는 화면 왼쪽 위에 가로로 나란히 표시합니다. 남은 생명마다 채워진 하트를, 잃은 생명마다 빈 하트를 표시합니다.
for i in range(3):
if i < lives:
screen.blit(heart_img, (10 + i * 40, 8))
else:
screen.blit(heart_empty_img, (10 + i * 40, 8))챌린지
중급spikes.png,heart.png및heart_empty.png를spikes_img,heart_img및heart_empty_img에 불러옵니다.spikes = []와lives = 3을 설정하고, 각^에 대해 Rect의 아래쪽 절반을 추가합니다.- 떨어졌을 때의 초기화 코드를
hurt = True로 바꿉니다. 플레이어가 가시에 닿았을 때도hurt를 설정합니다. 동전 처리 뒤에if hurt:블록을 둡니다. - 가시는
(spike.x - camera_x, spike.y - 18)위치에 그린 다음, 화면 왼쪽 위에 하트를 세 개 그립니다.
직접 해보기
import pygame
TILE = 36
WIDTH, HEIGHT = 576, 360
SPEED = 4
GRAVITY = 1
JUMP = -15
MAX_FALL = 12
LEVEL = [
"................................................................",
"................................................................",
"................................................................",
"................................................................",
"#..............................................................#",
"#....................C.........................#####...........#",
"#......CC...C................CC.....CC.........#####.....CC....#",
"#....................#.........................D...............#",
"#.P.........#...E....#...^.......K......E......D.C....^......F.#",
"#######..####################..##########################..#####",
]
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Moss Caves")
clock = pygame.time.Clock()
font = pygame.font.Font("assets/fonts/pixel.ttf", 24)
def load(name):
return pygame.image.load("assets/images/" + name).convert_alpha()
background = pygame.image.load("assets/backgrounds/forest.png").convert_alpha()
grass_img = load("grass.png")
grass_left_img = load("grass_left.png")
grass_right_img = load("grass_right.png")
dirt_img = load("dirt.png")
player_img = load("player.png")
coin_img = load("coin.png")
def solid(row, col):
if row < 0 or row >= len(LEVEL) or col < 0 or col >= len(LEVEL[0]):
return False
return LEVEL[row][col] == "#"
walls = []
tiles = []
coins = []
for row, line in enumerate(LEVEL):
for col, char in enumerate(line):
rect = pygame.Rect(col * TILE, row * TILE, TILE, TILE)
if char == "#":
if solid(row - 1, col):
image = dirt_img
elif not solid(row, col - 1) and solid(row, col + 1):
image = grass_left_img
elif solid(row, col - 1) and not solid(row, col + 1):
image = grass_right_img
else:
image = grass_img
walls.append(rect)
tiles.append((image, rect))
elif char == "P":
start = rect.midbottom
elif char == "C":
coins.append(rect)
level_width = len(LEVEL[0]) * TILE
player = player_img.get_rect(midbottom=start)
vel_y = 0
on_ground = False
camera_x = 0
coins_collected = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and event.key in (pygame.K_SPACE, pygame.K_UP):
if on_ground:
vel_y = JUMP
elif event.type == pygame.KEYUP and event.key in (pygame.K_SPACE, pygame.K_UP):
if vel_y < -4:
vel_y = -4
keys = pygame.key.get_pressed()
dx = 0
if keys[pygame.K_LEFT]:
dx -= SPEED
if keys[pygame.K_RIGHT]:
dx += SPEED
player.x += dx
for wall in walls:
if player.colliderect(wall):
if dx > 0:
player.right = wall.left
elif dx < 0:
player.left = wall.right
vel_y = min(vel_y + GRAVITY, MAX_FALL)
player.y += vel_y
on_ground = False
for wall in walls:
if player.colliderect(wall):
if vel_y > 0:
player.bottom = wall.top
on_ground = True
elif vel_y < 0:
player.top = wall.bottom
vel_y = 0
if player.top > HEIGHT:
player.midbottom = start
vel_y = 0
for coin in coins[:]:
if player.colliderect(coin):
coins.remove(coin)
coins_collected += 1
camera_x = player.centerx - WIDTH // 2
camera_x = max(0, min(camera_x, level_width - WIDTH))
shift = camera_x // 3 % 72
for y in range(0, HEIGHT, 72):
for x in range(-shift, WIDTH, 72):
screen.blit(background, (x, y))
for image, rect in tiles:
screen.blit(image, (rect.x - camera_x, rect.y))
for coin in coins:
screen.blit(coin_img, (coin.x - camera_x, coin.y))
screen.blit(player_img, (player.x - camera_x, player.y))
text = font.render(f"Coins: {coins_collected}", True, (255, 255, 255))
screen.blit(text, text.get_rect(topright=(WIDTH - 12, 14)))
pygame.display.flip()
clock.tick(60)
pygame.quit()
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
게임 월드의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드