PyGame 精灵是什么,它们有什么作用?

What are PyGame sprites, and what do they do?

我找到了很多关于如何以及何时使用 sprite 的教程,但我仍然不太清楚它们是什么或它们有什么作用。 默认想法似乎是将 pygame.sprite.Sprite class 子class 并向 class 添加 rectimage 属性。 但是为什么我需要subclass the Sprite class,这对我的代码有什么影响? 无论如何我都可以这样做:

class MySprite:  # No subclassing!
    def __init__(self, image):
        self.image = image
        self.rect = image.get_rect()

它似乎工作得很好。 我也尝试过查看源代码,但是 couldn't find a sprite file.

当你subclass时,你继承了class中的方法和函数。 pygame.sprite class 包含许多预先编写的方法,您可以调用这些方法而无需手动重新编码所有内容。

如果您决定像上面那样创建一个 orphaned/independent MySprite class,您将无法使用任何预先编写的代码。只要您愿意自己完全充实 class 的所有功能,就可以了。

精灵只是游戏中可以与其他精灵或其他任何东西互动的对象。这些可以包括游戏对象中的角色、建筑物或其他对象。

Sprites 有一个 subclass 的原因是更方便。当一个对象继承自 sprite.Sprite class 时,它们可以被添加到精灵组中。

示例:

import pygame

class car(sprite.Sprite):
    def __init__(self):
        sprite.Sprite.__init__() # necessary to initialize Sprite class
        self.image = image # insert image
        self.rect = self.image.get_rect() #define rect
        self.rect.x = 0 # set up sprite location
        self.rect.y = 0 # set up sprite location
    def update(self):
        pass # put code in here

cars = pygame.sprite.Group()# define a group

pygame.sprite.Group.add(car())# add an instance of car to group

我无法将精灵添加到精灵组,除非它们继承自精灵 class。这很有用,因为我现在可以做一些事情,比如更新组中的所有精灵并用一个函数绘制它们:

cars.update() #calls the update function on all sprites in group
cars.draw(surface) #draws all sprites in the group

我也可以使用群组进行碰撞检测:

# check to see if sprite collides with any sprite in the car group
collided = pygame.sprite.Sprite.spritecollide(sprite, cars, False)

note: In the above code pygame.sprite.Sprite.spritecollide returns a list.

总而言之,精灵 class 对于处理大量精灵很有用,否则需要更多代码来管理。 Sprite class 提供了一组可用于定义精灵的通用变量。