【发布时间】: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__()的参数存在。Batsx坐标保留在矩形Bat.rect中。您可以随时制作副本,例如:Bat.update(),您可以使用:bat_x, bat_y = self.rect.topleft。如果您真的想要保留一个永久副本,请在__init__()中创建一个self.bat_x,但记得更新它和Bat.rect。 -
在 update() 中,
bat_x, bat_y = self.rect.topleftbat_x += 5不会将bat_x的值增加 5,但也不会使程序崩溃?但是,例如,if bat_x > 300:self.kill()确实有效。为什么程序可以读取bat_x,但无法对其进行操作? -
bat_x成为该函数的“局部变量”。因此,您可以随心所欲地更改它,但是一旦该功能返回,它就消失了。见:pythonbasics.org/scopeself.rect是类的“成员变量”,所以存放在对象里面。
标签: python class pygame sprite