If 语句检查 sprite.Group = 0
If statement to check if sprite.Group = 0
我尝试使用 pygame 创建游戏,然后使用 myTarget=pygame.sprite.Group()
我的问题是如何创建判断 myTarget=0 的 if 语句,
我已经在使用
if myTarget=="0"
和
if myTarget == [0]
但是触发了 none 的代码,我也已经检查过该组内没有更多的精灵(使用 print(myTarget) 表示
对不起我的英语
不幸的是,SpriteGroup
对象不能 直接索引。
您可以使用 SpriteGroup.sprites()
成员函数,它 returns 一个包含所有元素的 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" )
这给了我输出:
...
Group has 3 sprites
Sprite A is the 0th item in the group
也可以在精灵组上使用len()
函数来测试它是否为空。
我尝试使用 pygame 创建游戏,然后使用 myTarget=pygame.sprite.Group() 我的问题是如何创建判断 myTarget=0 的 if 语句, 我已经在使用
if myTarget=="0"
和
if myTarget == [0]
但是触发了 none 的代码,我也已经检查过该组内没有更多的精灵(使用 print(myTarget) 表示
不幸的是,SpriteGroup
对象不能 直接索引。
您可以使用 SpriteGroup.sprites()
成员函数,它 returns 一个包含所有元素的 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" )
这给了我输出:
...
Group has 3 sprites
Sprite A is the 0th item in the group
也可以在精灵组上使用len()
函数来测试它是否为空。