收集金币
本课属于 Coddy Pygame 学习旅程的“游戏世界”单元。第 31 课,共 36 课。
金币能给探险者一个前进的目标:有几枚金币悬在坑上方,想要拿到它们就得冒险。
把每个 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;创建font(assets/fonts/pixel.ttf,大小为 24)、coins = []和coins_collected = 0。 - 每个
C都会将其图块 Rect 添加到coins。 - 移动后,移除每个碰到的硬币,并将
coins_collected加 1。 - 通过摄像机绘制硬币,并按图示在右上角显示
Coins: 0。
按“开始”并捡起一枚硬币:计数会增加。然后按“检查”。
亲手试试
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 在线编辑器