Menu
CoddyTech

接住它

Coddy 用 Pygame 制作游戏 课程的第 12 课,共 41 课。

两个矩形重叠时,就会发生碰撞。当矩形 a 和矩形 b 重叠时,即使只重叠 1 个像素,a.colliderect(b) 的结果也是 True。

if block.colliderect(basket):
    block.y = -20
    block.x = random.randint(0, 460)

接住的方块会像没接住的方块一样回到顶部。测试是否重叠比测试精确位置更安全:每次移动 3 个像素的方块可能会直接越过你要检测的那个 y 值。

challenge icon

挑战

简单

让篮子接住方块。

  1. 在检测方块是否错过之后,检测 block.colliderect(basket)。
  2. 如果条件为真,就像处理错过的方块一样,让方块回到顶部:block.y = -20,并设置一个随机的 block.x。

按“运行”并接住一个方块:它会回到顶部。然后按“检查”。

亲手试试

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Catch the Blocks")
clock = pygame.time.Clock()

basket = pygame.Rect(200, 330, 80, 16)
block = pygame.Rect(220, 0, 20, 20)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        basket.x -= 8
    if keys[pygame.K_RIGHT]:
        basket.x += 8
    basket.clamp_ip(screen.get_rect())

    block.y += 3
    if block.top > 360:
        block.y = -20
        block.x = random.randint(0, 460)

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 160, 255), basket)
    pygame.draw.rect(screen, (235, 80, 80), block)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

用 Pygame 制作游戏中的所有课

自己练习: Pygame 在线编辑器