Menu
CoddyTech

使用 spritecollide 捕捉

本课属于 Coddy Pygame 学习旅程的“精灵与图像”单元。第 20 课,共 39 课。

硬币从天而降,飞船应该接住它们。让一个精灵与整个精灵组碰撞,只需调用一次函数:

caught = pygame.sprite.spritecollide(player, coins, True)
score += len(caught)

spritecollide(sprite, group, dokill)会返回精灵组中rect与该精灵的rect重叠的精灵列表。如果没有碰到任何精灵,列表就是空的,因此len(caught)就是这一帧接住的硬币数。

第三个参数dokill决定碰到的精灵会怎样处理。设为True会将它们销毁,效果和逐个调用kill()相同,因此每枚硬币只会被接住一次。设为False则会让它们留在原处:对于只会与你碰撞一下的敌人,这样做是对的;对于硬币则不对,因为只要硬币与飞船重叠,每一帧都会加一分。

在循环的更新部分进行碰撞检测,放在精灵移动之后。

challenge icon

挑战

中等

让玩家接住硬币。

  1. 在 coins.update() 之后,使用 pygame.sprite.spritecollide 收集与玩家接触的硬币,并将它们销毁。
  2. 将接住的硬币数量加到 score 中。入门代码已经会显示它。

按“开始”并接住一枚硬币:会显示 Score: 1。然后按“检查”。

亲手试试

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Coin Catcher")
clock = pygame.time.Clock()

ship_image = pygame.image.load("assets/images/ship.png").convert_alpha()
coin_image = pygame.image.load("assets/images/coin.png").convert_alpha()
font = pygame.font.Font(None, 32)


class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = ship_image
        self.rect = self.image.get_rect(midbottom=(320, 470))

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.rect.x -= 6
        if keys[pygame.K_RIGHT]:
            self.rect.x += 6
        self.rect.clamp_ip(screen.get_rect())


class Coin(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = coin_image
        self.rect = self.image.get_rect(center=(random.randint(20, 620), random.randint(-400, -20)))

    def update(self):
        self.rect.y += 2
        if self.rect.top > 480:
            self.rect.center = (random.randint(20, 620), -20)


player = Player()
coins = pygame.sprite.Group()
for i in range(6):
    coins.add(Coin())
score = 0

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

    player.update()
    coins.update()

    screen.fill((20, 22, 40))
    coins.draw(screen)
    screen.blit(player.image, player.rect)
    text = font.render(f"Score: {score}", True, (240, 240, 240))
    screen.blit(text, (10, 10))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

精灵与图像中的所有课

自己练习: Pygame 在线编辑器