【问题标题】:Updating multiple items in a class, not just one更新一个类中的多个项目,而不仅仅是一个
【发布时间】:2020-03-27 15:01:15
【问题描述】:

在此代码的更新部分,只有第一个制作的 bat 受 Bat() 类中的 update() 影响... 主循环外:

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)

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

【问题讨论】:

  • 这是new_bat.kill()。应该是self.kill()。对象内部的代码是关于它作用于自身的。如果成员函数代码引用了类外部定义的东西,而不是常量,那么通常是错误的。
  • def update(self) 为什么self.bat_health 没有给出错误但self.bat_x 给出错误builtins.AttributeError: 'Bat' object has no attribute 'bat_x' ?另外,感谢您的回答,效果很好!
  • 找到你定义的Bat.bat_x...你错了吗?!变量bat_x 仅作为__init__() 的参数存在。 Bats x 坐标保留在矩形Bat.rect 中。您可以随时制作副本,例如:Bat.update(),您可以使用:bat_x, bat_y = self.rect.topleft。如果您真的想要保留一个永久副本,请在__init__() 中创建一个self.bat_x,但记得更新它和Bat.rect
  • 在 update() 中,bat_x, bat_y = self.rect.topleft bat_x += 5 不会将bat_x 的值增加 5,但也不会使程序崩溃?但是,例如,if bat_x &gt; 300:self.kill() 确实有效。为什么程序可以读取bat_x,但无法对其进行操作?
  • bat_x 成为该函数的“局部变量”。因此,您可以随心所欲地更改它,但是一旦该功能返回,它就消失了。见:pythonbasics.org/scopeself.rect是类的“成员变量”,所以存放在对象里面。

标签: python class pygame sprite


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 2015-12-06
    • 1970-01-01
    相关资源
    最近更新 更多