更新一个类中的多个项目,而不仅仅是一个 [英] Updating multiple items in a class, not just one

查看:46
本文介绍了更新一个类中的多个项目,而不仅仅是一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码的update节中,只有第一个蝙蝠受到Bat()类中的update()的影响.在主循环之外:

In the update section of this code, only the first bat that gets made is affected by update() in class Bat()... Outside of main loop:

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)

内部主循环...

all_bats.update()
all_bats.draw(display)

任何帮助都会很棒!谢谢.

Any help would be great! Thanks.

推荐答案

In Method Objects you must use the instance parameter (self) instead of an object instance in the global namespace. This means you have to call self.kill() instead of new_bat.kill():

class Bat(pygame.sprite.Sprite):
    # [...]

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

这篇关于更新一个类中的多个项目,而不仅仅是一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆