簡體   English   中英

python sprite list如何工作? 我可以將精靈坐標添加到列表中嗎?

[英]How does the python sprite list work? Can i add sprite coords to the list?

親愛的朋友們,您好,對於我的python項目,我創建了一個按鈕類-它們的圖像,坐標,動作等,並且一切正常。 但是我想我會在游戲中添加很多按鈕,所以我決定將它們的坐標添加到一個pygame sprite組中,並使用for循環自動使其變亮。


 for oge in buttonList:
    pygame.blit(oge, (x, y)


有什么辦法可以將帶有其坐標的子畫面添加到組或列表中,以將它們全部合並?

簡短答案:

如果每個精靈都有一個.rect.image屬性,則可以調用.draw()

buttonList.draw(surf)

長答案:

pygame.sprite.Sprite對象應該具有.rect類型的pygame.Rect屬性pygame.Rect此屬性定義了Sprite的位置(和大小)。

在下文中,我假設buttonListpygame.sprite.Group
組shuold中的每個Sprite都具有.rect屬性,該屬性用於在其位置繪制Sprite,例如:

class MySprite(pygame.sprite.Sprite):

    def __init__(self):
        super().__init__() 

        self.image = [...]
        self.rect  = self.image.get_rect()

該組中的所有子畫面都可以通過調用來繪制。 參數surf可以是任何表面,例如顯示表面:

buttonList.draw(surf)

注意, pygame.sprite.Groupdraw()方法將包含的pygame.sprite.Group繪制到Surface上。 每個精靈的.image.rect位置“ .rect

pygame.Rect具有很多虛擬屬性,可以設置其位置(和大小),例如.center.topleft 使用它們來設置精靈的位置:

mysprite = MySprite()
mysprite.rect.topleft = (x, y)

當然,位置(x, y)也可以是sprite類的構造函數的參數:

class MySprite(pygame.sprite.Sprite):

    def __init__(self, x, y):
        super().__init__() 

        self.image = [...]
        self.rect  = self.image.get_rect(topleft = (x, y))

mysprite = MySprite(x, y)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM