gpt4 book ai didi

python - 如何将子类添加到 pygame 中的 Sprite 组

转载 作者:行者123 更新时间:2023-12-04 10:07:52 25 4
gpt4 key购买 nike

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

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

或者将 Sprite 组的属性名称存储为类属性并动态查找它们,如下所示:
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,因为它是明确的,并且没有涉及任何花哨的聪明部分。

关于python - 如何将子类添加到 pygame 中的 Sprite 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61480883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com