가장자리 타일
Coddy Pygame 여정의 게임 월드 섹션에 포함된 레슨. 36개 중 8번째.
플랫폼은 양 끝이 둥글면 완성된 것처럼 보입니다. 팩에는 풀이 있는 표면의 양 끝에 사용할 grass_left.png와 grass_right.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] == "#"맵 바깥은 빈 공간으로 간주합니다. 도우미 함수를 사용하면 선택 규칙을 그대로 읽을 수 있습니다.
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)))양쪽 모두에 땅이 있거나 양쪽 모두에 땅이 없는 타일은 기본 풀 이미지를 유지합니다. 맵의 왼쪽 가장자리인 열 0에서는 왼쪽 타일이 맵 바깥에 있으므로 빈 공간으로 간주되며, 그곳의 땅은 grass_left_img로 시작합니다.
챌린지
중급각 잔디 발판의 끝을 둥글게 마무리하세요.
solid(row, col)을 작성하세요. 맵 밖에서는False, 맵 안에서는LEVEL[row][col] == "#"입니다.- 각
#에 대해, 위 타일이 단단하면dirt_img를 사용하고, 그렇지 않고 오른쪽 이웃만 단단하면grass_left_img를 사용하고, 왼쪽 이웃만 단단하면grass_right_img를 사용하고, 그 외에는grass_img를 사용하세요.
‘플레이’를 누르세요. 각 발판의 잔디 끝이 둥글게 표시됩니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
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()
tiles = []
for row, line in enumerate(LEVEL):
for col, char in enumerate(line):
x, y = col * TILE, row * TILE
if char == "#":
if row == 0 or LEVEL[row - 1][col] != "#":
image = grass_img
else:
image = dirt_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 플레이그라운드