首页 > 解决方案 > 如何在pygame中将子类添加到精灵组

问题描述

我有一个名为 的基类'Block',它的精灵组设置为game.all_spritesand game.blocks。我有一个'ground'从块类继承的子类,但我无法改变精灵组。有谁知道如何做到这一点?块类:

class Block(pygame.sprite.Sprite):
    def __init__(self, game, x, y, collidable=True):
        self.groups = game.all_sprites, game.blocks
        pygame.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = pygame.Surface((SCALE, SCALE))
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y
        self.collidable = collidable

    def update(self):
        self.rect.x = self.x * SCALE
        self.rect.y = self.y * SCALE

地面等级:

class Ground(Block):
    def __init__(self, game, x, y, collidable=False):
        self.groups = game.all_sprites, game.grounds
        Block.__init__(self, game, x, y, collidable)

谢谢!

标签: pythonpygame

解决方案


您可以使用可以覆盖的方法来定义组:

class Block(pygame.sprite.Sprite):
    def __init__(self, game, x, y, collidable=True):
        pygame.sprite.Sprite.__init__(self, self.get_groups(game))
        self.game = game
        ...

    def get_groups(self, game):
        return game.all_sprites, game.blocks


class Ground(Block):

    def __init__(self, game, x, y, collidable=False):
        Block.__init__(self, game, x, y, collidable)

    def get_groups(self, game):
        return game.all_sprites, game.grounds

或者将精灵组的属性名称存储为类属性并动态查找它们,如下所示:

class Block(pygame.sprite.Sprite):
    groups = ['all_sprites', 'blocks']

    def __init__(self, game, x, y, collidable=True):
        pygame.sprite.Sprite.__init__(self, (getattr(game, g) for g in self.groups))
        self.game = game
        ...


class Ground(Block):
    groups = ['all_sprites', 'grounds']

    def __init__(self, game, x, y, collidable=False):
        Block.__init__(self, game, x, y, collidable)

或将组作为参数从子类传递给父类:

class Block(pygame.sprite.Sprite):
    def __init__(self, game, x, y, collidable=True, groups=None):
        pygame.sprite.Sprite.__init__(self, groups or (game.all_sprites, game.blocks))
        self.game = game
        ...


class Ground(Block):

    def __init__(self, game, x, y, collidable=False, groups=None):
        Block.__init__(self, game, x, y, collidable, groups or (game.all_sprites, game.grounds))

事实上,可能性是无穷无尽的:

class Block(pygame.sprite.Sprite):
    def __init__(self, game, x, y, collidable=True):
        groups = game.all_sprites, getattr(game, self.__class__.__name__.lower() + 's')
        pygame.sprite.Sprite.__init__(self, groups)
        self.game = game
        ...

我可能会使用选项 3,因为它是明确的并且不涉及花哨的聪明部分。


推荐阅读