Pygame - number of sprites in a group

时光毁灭记忆、已成空白 提交于 2021-01-06 04:12:49

问题


How do I determine how many sprites are in a group? len() should work, but just... doesn't. Code:

print(len(sprites))
print('sprites',sprites)

Output:

0
('sprites', <Group(1 sprites)>)

(Yes, I did make a group called 'sprites')

EDIT: I renamed "sprites" to "aliveSprites", just in case that was the issue. No luck. Here's the code:

print(len(aliveSprites.sprites()))
if len(aliveSprites.sprites()) == 0:
    thing = test()
    aliveSprites.add(thing)

    thing.rect.x = 100
    thing.rect.y = 300

print('sprites',aliveSprites)

回答1:


Try (as ugly as it looks)

len(sprites.sprites)

Pygame Sprites Group does support the len operation.

pygame.sprite.Group

A simple container for Sprite objects. This class can be inherited to create containers with more specific behaviors. The constructor takes any number of Sprite arguments to add to the Group. The group supports the following standard Python operations:

in      test if a Sprite is contained
len     the number of Sprites contained
bool    test if any Sprites are contained
iter    iterate through all the Sprites



回答2:


You need to call sprites() to get the list of sprites

print(len(sprites.sprites()))


来源:https://stackoverflow.com/questions/21084366/pygame-number-of-sprites-in-a-group

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!