Menu
CoddyTech

左右墙壁

本课属于 Coddy Pygame 学习旅程的“游戏世界”单元。第 15 课,共 36 课。

方块已经画出来了,但玩家会直接穿过它们。墙必须挡住玩家。先移动,再修正移动:如果玩家现在与墙重叠,就从玩家来的那一侧把它推出来。

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

dx 表示这一帧的水平移动量:正数表示向右移动。向右移动时,玩家撞上墙的左侧,因此玩家的右边缘移到那里。向左移动时,玩家的左边缘移到墙的右侧。

地图内置在 walls 中,它是一个由 Rect 组成的列表,构建方式与《文本地图》中的相同。地面仍然是位于 FLOOR 的那条线,玩家仍然可能掉到方块顶部,接下来会处理落在墙上的情况。

challenge icon

挑战

中等

让墙挡住玩家。

  1. 在 player.x += dx 之后,遍历 walls。
  2. 对于玩家碰到的每一堵墙:当 dx > 0 时,设置 player.right = wall.left;当 dx < 0 时,设置 player.left = wall.right。

按下“开始”,然后走向一堵墙:玩家会停在墙边。接着点击“检查”。

亲手试试

import pygame

TILE = 36
SPEED = 4
GRAVITY = 1
JUMP = -15
MAX_FALL = 12
FLOOR = 324

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

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

background = pygame.image.load("assets/backgrounds/clouds.png").convert_alpha()
block_img = pygame.image.load("assets/images/block.png").convert_alpha()
player_img = pygame.image.load("assets/images/player.png").convert_alpha()

walls = []
for row, line in enumerate(LEVEL):
    for col, char in enumerate(line):
        if char == "#":
            walls.append(pygame.Rect(col * TILE, row * TILE, TILE, TILE))
        elif char == "P":
            start = (col * TILE + TILE // 2, row * TILE + TILE)

player = player_img.get_rect(midbottom=start)
vel_y = 0
on_ground = False

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

    vel_y = min(vel_y + GRAVITY, MAX_FALL)
    player.y += vel_y
    on_ground = False
    if player.bottom > FLOOR:
        player.bottom = FLOOR
        vel_y = 0
        on_ground = True

    for y in range(0, 360, 72):
        for x in range(0, 576, 72):
            screen.blit(background, (x, y))
    for wall in walls:
        screen.blit(block_img, wall)
    screen.blit(player_img, player)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

游戏世界中的所有课

自己练习: Pygame 在线编辑器