繁体   English   中英

pygame.sprite.Group() 如何知道调用哪个精灵组? 还调用精灵组也调用class?

[英]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的代码。 这意味着您的项目符号实际上不会包含在您已命名项目bulletsGroup中。 可能您应该为每个项目符号执行此操作,因为它是创建的。 您可能想要这样的东西(为简洁起见,删除了文档字符串):

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.

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