这次我们来讲一个非常实用的模块:sprite模块,它可以用来处理含有多个对象的整体,比如一堆子弹和一堆俄罗斯方块,使用sprite模块不仅可以简化控制的复杂度,也可以利用它的函数来简化实现方法。
主要内容: Sprite类的继承、Group类、检测精灵的碰撞、应用
一、Sprite类的继承
sprite类:类的定义
class Sprite(object):
def __init__(self, *groups):
self.__g = {
} # The groups the sprite is in
if groups:
self.add(*groups)
def add(self, *groups):
def remove(self, *groups):
def update(self, *args):
pass
Sprite类在sprite模块中的定义像上面这样,由于update函数,没有定义,所以不适合直接用。但它适合用于继承重载。
sprite类:继承
在继承Sprite类时,要确保子类的构造函数调用了Sprite类的构造函数:
class Block(pygame.sprite.Sprite):
def __init__(self,color,topleft):
# 执行父类构造函数
pygame.sprite.Sprite.__init__(self)
...
我们继承Sprite的主要目的是是希望派生类覆盖Sprite.update()并分配Sprite.image