如何在pygam中使用sprite组

2024-04-29 04:40:12 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我已经在我的程序中找到了一个点,我需要为一些精灵创建一个组,玩家可以在不死亡的情况下与之碰撞(就像我在屏幕上看到的其他精灵一样)。

我搜索过Google,但看起来官方的pygame文档毫无用处,而且/或者很难理解。我只想从任何知道这件事的人那里得到一点帮助。

首先,我需要了解如何创建一个组。在最初的游戏设置中有吗?

然后在创建时将精灵添加到组中。pygame网站在这个问题上说:

Sprite.add(*groups)

所以。。。怎么用这个?假设我有一个叫gem的精灵。我需要在宝石组中添加宝石。是不是:

gem = Sprite.add(gems)

我对此表示怀疑,但在网站上没有任何可供参考的例子,我不知所措。

此外,我希望能够编辑特定组的属性。这是通过定义一个组来完成的吗?或者是我在现有精灵的定义中定义的,但带有“if sprite in group”的东西?


Tags: 文档程序add游戏官方gem定义屏幕
3条回答

我知道这个问题已经得到了回答,但最好的方法是像凯尔温克建议的那样。我会详细说明,这样更容易理解。

# First, create you group
gems = pygame.sprite.Group()

class Jewel (pygame.sprite.Sprite): # Inherit from the Sprite
    def __init__ (self, *args): # Call the constructor with whatever arguments...
        # This next part is key. You call the super constructor, and pass in the 
        # group you've created and it is automatically added to the group every 
        # time you create an instance of this class
        pygame.sprite.Sprite.__init__(self, gems) 

        # rest of class stuff after this.

>>> ruby = Jewel()  
>>> diamond = Jewel()  
>>> coal = Jewel()

# All three are now in the group gems. 
>>> gems.sprites()
[<Jewel sprite(in 1 groups)>, <Jewel sprite(in 1 groups)>, <Jewel sprite(in 1 groups)>]

您还可以使用gems.add(some_sprite) 添加更多内容,同样也可以使用gems.remove(some_sprite)删除它们。

只需使用组列表调用super__init__函数。例如:

def __init__(self):
    pygame.sprite.Sprite.__init__(self, self.groups)

然后,在层次结构的每个类中,应该定义一个属性self.groups,超级构造函数将把每个实例添加到其组中。这是我认为最干净的解决办法。否则,只需使用每个类中的组列表显式调用超级构造函数。

要回答您的第一个问题;要创建一个组,您需要执行以下操作:

gems = pygame.sprite.Group()

然后要添加精灵:

gems.add(gem)

关于要编辑的组的属性,这取决于它们是什么。例如,您可以定义如下内容来指示组的方向:

gems.direction = 'up'

相关问题 更多 >