边缘图块
本课属于 Coddy Pygame 学习旅程的“游戏世界”单元。第 8 课,共 36 课。
平台的两端变圆后,看起来就完整了。素材包中有 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 在线编辑器