简体   繁体   English

if 语句检查 sprite.Group = 0

[英]If statement to check if sprite.Group = 0

I trying to create game using pygame,then using myTarget=pygame.sprite.Group() My problem is how to create if statement that tell if myTarget=0, I already using我尝试使用 pygame 创建游戏,然后使用 myTarget=pygame.sprite.Group() 我的问题是如何创建 if 语句来判断 myTarget=0,我已经在使用

if myTarget=="0"

and

if myTarget == [0]

But none of that code triggered, I also already checked that inside that group no more sprites (using print(myTarget) that says <Group(0 sprites)> Sorry for my English但是没有触发任何代码,我也已经检查了该组内没有更多精灵(使用 print(myTarget) 说 <Group(0 sprites)> 对不起我的英语

Unfortunately the SpriteGroup object is not able to be directly indexed.不幸的是, SpriteGroup object无法直接索引。

You can use the SpriteGroup.sprites() member function, which returns a python list of all the elements and then just tested item 0 in that list:您可以使用SpriteGroup.sprites()成员 function,它返回所有元素的 python 列表,然后只测试该列表中的项目0

import pygame

class SimpleSprite( pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface( ( 64, 64 ), pygame.SRCALPHA )
        self.image.fill( ( 255, 255, 12 ) )
        self.rect = self.image.get_rect()


pygame.init()

sprite_group = pygame.sprite.Group()  # empty group

# Make and add 3 sprites to the group
sprite_a = SimpleSprite()
sprite_b = SimpleSprite()
sprite_c = SimpleSprite()
sprite_group.add( sprite_a )
sprite_group.add( sprite_b )
sprite_group.add( sprite_c )

print( "Group has %d sprites" % ( len( sprite_group ) ) )

if ( sprite_a == sprite_group.sprites()[0] ):                 # <<-- HERE
    print( "Sprite A is the 0th item in the group" )
else:
    print( "Sprite A is NOT the 0th item" )

Which gives me the output:这给了我 output:

... ...
Group has 3 sprites组有 3 个精灵
Sprite A is the 0th item in the group Sprite A 是组中的第 0 个项目

Also you can use the len() function on a Sprite Group to test if it is empty.您也可以在 Sprite Group 上使用len() function 来测试它是否为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM