python - 如何在pygame中将子类添加到精灵组
问题描述
我有一个名为 的基类'Block'
,它的精灵组设置为game.all_sprites
and 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)
谢谢!
解决方案
您可以使用可以覆盖的方法来定义组:
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,因为它是明确的并且不涉及花哨的聪明部分。
推荐阅读
- excel - VBA Excel 在字符串的第二个字符后插入符号
- excel - Excel : 使用 2 个 vlookup 更快的 Vlookup
- r - 夏皮罗测试的功能
- r - 使用 ggplot2 绘制时间序列/累积数据图
- azure - CI-CD Azure devops 用于函数应用部署
- python - 如何阅读拉丁字符(Python)?
- javascript - Javascript 无法识别我设置的变量
- python - 熊猫用多个列表填充列
- spring-boot - Intellij:代码在调试模式下以紫色突出显示
- python - 升级到 1.16 后,Numpy 数组不再使输入变平