如何在pygame中使用精灵组

use*_*592 7 python pygame sprite

所以我已经完成了我的程序,我需要为一些精灵创建一个组,玩家可以在没有死亡的情况下碰撞(就像我可能在屏幕上看到的其他一些精灵).

我已经搜索过Google,但似乎官方的pygame文档是无用的和/或难以理解的.我正在寻找任何对此有所了解的人的帮助.

首先,我需要了解如何创建一个组.它是否适用于最初的游戏设置?

然后在创建时将精灵添加到组中.pygame网站就此主题有这样的说法:

Sprite.add(*groups)
Run Code Online (Sandbox Code Playgroud)

那么......怎么用呢?假设我有一个名为gem的精灵.我需要为gem组添加gem.是吗:

gem = Sprite.add(gems)
Run Code Online (Sandbox Code Playgroud)

我对此表示怀疑,但没有任何例子可以在网站上发布,我感到很茫然.

此外,我希望能够编辑某个组的属性.这是通过定义像我会上课的小组来完成的吗?或者它是我在现有精灵的定义中定义的东西,但是'if sprite in group'?

tim*_*imc 12

回答你的第一个问题; 要创建一个组,你会做这样的事情:

gems = pygame.sprite.Group()
Run Code Online (Sandbox Code Playgroud)

然后添加一个精灵:

gems.add(gem)
Run Code Online (Sandbox Code Playgroud)

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

gems.direction = 'up'
Run Code Online (Sandbox Code Playgroud)


jts*_*287 6

我知道这个问题已经得到解答,但最好的方法就像kelwinfc建议的那样.我会详细说明,这样更容易理解.

# 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)>]
Run Code Online (Sandbox Code Playgroud)

你也可以添加更多,gems.add(some_sprite) 同样删除它们gems.remove(some_sprite).