タイル状の背景
CoddyのPygameジャーニー「ゲームの世界」セクションの一部。レッスン 9/35。
ステージの背後が単色だと、何もないように見えます。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までの値を返します。504は、表示される最後の開始位置です。576は72の倍数なので、最後の画像はウィンドウの端までぴったり収まります。背景画像はscreen.fillの代わりになり、すべてのピクセルを覆います。
描画する順序が重要です。後から描画したものが、その下にあるものを覆います。そのため、まず背景を描画し、その上にタイルを描画します。
チャレンジ
簡単スターターコードでは、assets/backgrounds/clouds.pngをbackgroundに読み込みます。
- ゲームループで、
screen.fillの代わりに、yを0から360まで72刻みで変化させるたびに、xを0から576まで72刻みで変化させながら、backgroundをblitします。 - 背景の後にタイルを描画します。
自分で試してみよう
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プレイグラウンド