코인 모으기
Coddy Pygame 여정의 게임 월드 섹션에 포함된 레슨. 35개 중 31번째.
동전은 탐험가가 쫓을 거리를 만들어 줍니다. 몇 개는 구덩이 위에 걸려 있어, 손에 넣으려면 위험을 감수해야 합니다.
모든 C를 Rect 목록에 넣으세요. coin.png에는 자체적인 빈 테두리가 있으므로 타일 전체를 사용합니다. 플레이어가 동전에 닿으면 목록에서 제거하고 개수를 셉니다.
for coin in coins[:]:
if player.colliderect(coin):
coins.remove(coin)
coins_collected += 1coins[:]는 목록의 복사본입니다. 반복문이 목록을 순회하는 동안 항목을 제거하면 항목이 반복문 아래에서 이동해 하나를 건너뛰게 됩니다. 복사본을 순회하면 이를 피할 수 있습니다.
개수를 오른쪽 위 모서리에 표시하세요. 개수는 레벨이 아니라 창에 속하므로 카메라 없이 그립니다.
font = pygame.font.Font("assets/fonts/pixel.ttf", 24)
# 루프 안에서
text = font.render(f"Coins: {coins_collected}", True, (255, 255, 255))
screen.blit(text, text.get_rect(topright=(WIDTH - 12, 14)))챌린지
중급coin.png을coin_img에 불러오고, 크기 24로assets/fonts/pixel.ttf에서font를 만드세요.coins = []와coins_collected = 0을 만들고, 맵 루프에서 각C에 해당하는 타일 Rect를 추가하세요.- 매 프레임 이동 후, 플레이어가 닿는 코인을 각각 제거하고
coins_collected에 1을 더하세요. - 각 코인을 x에서
camera_x를 뺀 위치에 그린 다음, 오른쪽 위에 표시된 것처럼Coins:텍스트와 개수를 그리세요.
직접 해보기
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()
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")
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 = []
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
level_width = len(LEVEL[0]) * TILE
player = player_img.get_rect(midbottom=start)
vel_y = 0
on_ground = False
camera_x = 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
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))
screen.blit(player_img, (player.x - camera_x, player.y))
pygame.display.flip()
clock.tick(60)
pygame.quit()
게임 월드의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드