[英]How does pygame.sprite.Group() know which sprite group to call? Also calling the sprite group also calls the class?
您好,我正在開發 AlienInvasion 游戲,我對 pygame.sprite.Group 有點困惑。 它怎么知道要調用哪個 pygame.sprite.Group() ?
我習慣於引用這樣的類。
self.ship = 船(自我)
但是這個是這樣稱呼的。 它如何知道它正在調用哪個精靈組? 我目前只有 1 個精靈組 ATM,所以這是有道理的,但如果我有更多呢?
self.bullets = pygame.sprite.Group()
然后我可以像這樣引用它的方法
self.bullets.update()
class AlienInvasion:
"""Overall class to manage game assets and behavior."""
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Alien Invasion")
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
def _update_bullets(self):
"""update position of bullets and get rid of old bullets"""
# update bullet positions
self.bullets.update()
class Bullet(Sprite):
"""A class to manage bullets fired from the ship"""
def __init__(self, ai_game):
"""Create a bullet object at the ship's current position."""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
self.color=self.settings.bullet_color
當你這樣做時:
self.bullets = pygame.sprite.Group()
您正在創建一個新Group
object 並將其分配給當前 object 上的屬性項目bullets
。 該組不知道它是從哪里引用的。 當您開始向其中添加精靈時,它將跟蹤這些精靈。 這是 object Group
的工作,它就像一個list
或其他容器。 一個Group
有一些專門的方法,雖然可以讓你在一個 go 中與多個 sprite 交互(例如Group.update()
,它在它包含的每個 sprite 上調用update()
)。
您沒有在Bullet
class 中顯示任何將它們添加到Group
的代碼。 這意味着您的項目符號實際上不會包含在您已命名項目bullets
的Group
中。 可能您應該為每個項目符號執行此操作,因為它是創建的。 您可能想要這樣的東西(為簡潔起見,刪除了文檔字符串):
class Bullet(Sprite):
def __init__(self, ai_game):
super().__init__(ai_game.bullets) # pass the group here!
... # do the rest of your initialization
Sprite.__init__
方法接受任意數量的 arguments,它預計是Group
s。 它將新創建的精靈添加到每個組中,這聽起來正是您想要的。
Sprite
class 有另一種與Group
交互的有用方法,您可能希望稍后在代碼中使用它: Sprite.kill()
從其所有組中刪除 sprite,如果 sprite 不再與您的相關,這很方便游戲(例如,一顆未命中目標並飛離屏幕的子彈)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.