pygame.sprite.Group


Group類,它只存儲sprite對象 

 

import pygame

pygame.init()
screen = pygame.display.set_mode((960, 800))
pygame.display.set_caption("pygame.sprite.Group")

class sprite(pygame.sprite.Sprite):

    def __init__(self, filepath):
        super().__init__()
        self.image = pygame.image.load(filepath).convert_alpha()
        self.rect = self.image.get_rect()
sprite_list = pygame.sprite.Group()  #定義精靈組
#pygame.sprite.RenderPlain與這個語句相同

sprite_list1 = pygame.sprite.Group()
sprite_list2 = pygame.sprite.Group()

for i in range(5):
    filepath='./圖片/aa'+str(i)+'.png'
    sp = sprite(filepath)  #創建一個精靈
    sp.rect.x = 10  #精靈的位置
    sp.rect.y = 10
    #務必在Sprite添加到Groups之前調用基本初始值設定項
    sprite_list.add(sp)  #將精靈加入組
    #print(sprite_list)
    #<Group(76 sprites)>     76表示組內的精靈數

    sprite_list1.add(sp)

    sprite_list.update()  # 組更新
    #在組中的所有Sprite上調用update()方法
    # 如果沒有在Group類中使用同名的方便方法,則無需使用此方法


#sprite_list.remove(sp)  #從組中刪除指定的精靈
#<Group(75 sprites)>

#pygame.sprite.Sprite.kill(sp) #從所有組中刪除指定的精靈
# 這不會改變關於Sprite狀態的任何信息。 調用此方法后,可以繼續使用Sprite,包括將其添加到Groups

#b=pygame.sprite.Sprite.alive(sp)  #指定精靈時候已經加入組(任何組都可以)
#當Sprite屬於一個或多個組時返回True

b=pygame.sprite.Sprite.groups(sp)  #返回包含指定精靈的組的列表
#[<Group(76 sprites)>, <Group(76 sprites)>]

for i in sprite_list.__iter__():  #sprite_list.__iter__()  組中精靈集合的迭代器
    #print('xxx',i)
    pass

b= len(sprite_list)  #返回組內的精靈數

b=sprite_list.sprites()  #返回組中精靈的列表
#[<sprite sprite(in 2 groups)>, <sprite sprite(in 2 groups)>, <sprite sprite(in 2 groups)>, <sprite sprite(in 2 groups)>, <sprite sprite(in 2 groups)>]
#in 2 groups   表示這個精靈在兩個組中

sprite_list2=sprite_list.copy()  #組復制

b=sprite_list.has(sp)  #組中是否包含指定精靈
#如果組包含所有給定的精靈,則返回True

#sprite_list2.empty()  #從該組中刪除所有Sprite

print(b)


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

    sprite_list2.draw(screen)  # 將組內所有精靈渲染到screen上
    #Group.draw()方法要求每個Sprite都有一個Surface.image屬性和一個Surface.rect
    #將包含的Sprite繪制到Surface參數



    pygame.display.update()

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM