Menu
CoddyTech

타일 배경

Coddy Pygame 여정의 게임 월드 섹션에 포함된 레슨. 35개 중 9번째.

레벨 뒤에 단색만 있으면 허전해 보입니다. assets/backgrounds/clouds.png는 반복해서 타일링하도록 만든 72×72 그림입니다. 왼쪽 가장자리가 오른쪽 가장자리에 맞고, 위쪽 가장자리가 아래쪽 가장자리에 맞습니다. 창을 덮도록 격자 형태로 블리트하세요.

for y in range(0, 360, 72):
    for x in range(0, 576, 72):
        screen.blit(background, (x, y))

range(0, 576, 72)는 0, 72, 144 등으로 이어져 마지막으로 화면에 표시되는 시작 위치인 504까지 값을 생성합니다. 576은 72의 배수이므로 마지막 타일이 창의 가장자리에서 끝납니다. 배경은 screen.fill을 대신합니다. 모든 픽셀을 덮습니다.

그리는 순서가 중요합니다. 나중에 블리트한 것은 이미 그려진 것을 덮으므로, 배경을 먼저 그린 다음 그 위에 타일을 그리세요.

challenge icon

챌린지

쉬움

시작 코드는 assets/backgrounds/clouds.png를 background에 불러옵니다.

  1. 게임 루프에서 screen.fill 대신, y가 0부터 360까지 72씩 증가할 때마다 x가 0부터 576까지 72씩 증가하는 각 위치에 background를 블릿합니다.
  2. 배경을 그린 다음 타일을 그립니다.

직접 해보기

import pygame

TILE = 36

LEVEL = [
    "###.............",
    "###.............",
    "..........C.....",
    ".........####...",
    "..C.............",
    ".####......C....",
    "..........###...",
    "#....C.........#",
    "###..##...###.##",
    "######..########",
]

pygame.init()
screen = pygame.display.set_mode((576, 360))
pygame.display.set_caption("Tiles")
clock = pygame.time.Clock()

grass_img = pygame.image.load("assets/images/grass.png").convert_alpha()
grass_left_img = pygame.image.load("assets/images/grass_left.png").convert_alpha()
grass_right_img = pygame.image.load("assets/images/grass_right.png").convert_alpha()
dirt_img = pygame.image.load("assets/images/dirt.png").convert_alpha()
coin_img = pygame.image.load("assets/images/coin.png").convert_alpha()
background = pygame.image.load("assets/backgrounds/clouds.png").convert_alpha()


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] == "#"


tiles = []
for row, line in enumerate(LEVEL):
    for col, char in enumerate(line):
        x, y = col * TILE, row * 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
            tiles.append((image, pygame.Rect(x, y, TILE, TILE)))
        elif char == "C":
            tiles.append((coin_img, pygame.Rect(x, y, TILE, TILE)))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((140, 200, 240))
    for image, rect in tiles:
        screen.blit(image, rect)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

게임 월드의 모든 레슨

직접 연습해 보세요: Pygame 플레이그라운드