首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更新类中的多个项目,而不只是一个

更新类中的多个项目,而不只是一个
EN

Stack Overflow用户
提问于 2020-03-27 23:01:16
回答 1查看 41关注 0票数 2

在这段代码的update部分中,只有第一个bat会受到Bat()类中update()的影响...在主循环之外:

代码语言:javascript
复制
START_BAT_COUNT = 30
BAT_IMAGE_PATH = os.path.join( 'Sprites', 'Bat_enemy', 'Bat-1.png' )

bat_image = pygame.image.load(BAT_IMAGE_PATH).convert_alpha()
bat_image = pygame.transform.scale(bat_image, (80, 70))


class Bat(pygame.sprite.Sprite):
    def __init__(self, bat_x, bat_y, bat_image, bat_health):
        pygame.sprite.Sprite.__init__(self)
        self.bat_health = bat_health
        self.image = bat_image
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)
        self.rect.topleft = (bat_x, bat_y)

    def update(self):
        self.bat_health -= 1 
        if self.bat_health < 0:
            new_bat.kill()

all_bats = pygame.sprite.Group()

for i in range(START_BAT_COUNT):
    bat_x = (random.randint(0, 600))
    bat_y = (random.randint(0, 600))
    bat_health = 5

    new_bat = Bat(bat_x, bat_y, bat_image, bat_health)
    all_bats.add(new_bat)

在主循环内部...

代码语言:javascript
复制
all_bats.update()
all_bats.draw(display)

任何帮助都是最好的!谢谢。

EN

回答 1

Stack Overflow用户

发布于 2021-01-03 03:38:17

Method Objects中,必须使用实例参数(self),而不是全局名称空间中的对象实例。这意味着您必须调用self.kill()而不是new_bat.kill()

代码语言:javascript
复制
class Bat(pygame.sprite.Sprite):
    # [...]

    def update(self):
        self.bat_health -= 1 
        if self.bat_health < 0:
            self.kill()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60888593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档