对象行为不正确

时间:2013-10-09 17:18:43

标签: python pygame livewires

我正在使用Livewires和pygame,我在游戏中的一个物体给你额外的生命被误认为是一个小行星物体,当额外的生命物体与玩家碰撞时它返回'额外的生命物体没有属性handle_caught'错误信息,我可以请一些帮助。

class Extralives(games.Sprite):
global lives

image = games.load_image('lives.png', transparent = True)
speed = 2

def __init__(self,x,y = 10):
    """ Initialize a asteroid object. """
    super(Extralives, self).__init__(image = Extralives.image,
                                x = x, y = y,
                                dy = Extralives.speed)
def update(self):
    """ Check if bottom edge has reached screen bottom. """
    if self.bottom>games.screen.height:
        self.destroy()

    self.add_extralives

def add_extralives(self):
    lives+=1

小行星类:

class Asteroid(games.Sprite):
global lives
global score
"""
A asteroid which falls through space.
"""

image = games.load_image("asteroid_med.bmp")
speed = 1.7

def __init__(self, x,image, y = 10):
    """ Initialize a asteroid object. """
    super(Asteroid, self).__init__(image = image,
                                x = x, y = y,
                                dy = Asteroid.speed)


def update(self):
    """ Check if bottom edge has reached screen bottom. """
    if self.bottom>games.screen.height:
        self.destroy()
        score.value+=10

def handle_caught(self):
    if lives.value>0:
        lives.value-=1
        self.destroy_asteroid()

    if lives.value <= 0:
        self.destroy_asteroid()
        self.end_game()


def destroy_asteroid(self):
    self.destroy()

处理碰撞的玩家类的一部分:

def update(self):
    """ uses A and D keys to move the ship """
    if games.keyboard.is_pressed(games.K_a):
        self.x-=4
    if games.keyboard.is_pressed(games.K_d):
        self.x+=4

    if self.left < 0:
        self.left = 0

    if self.right > games.screen.width:
        self.right = games.screen.width

    self.check_collison()

def ship_destroy(self):
    self.destroy()

def check_collison(self):
    """ Check if catch pizzas. """
    global lives
    for asteroid in self.overlapping_sprites:
        asteroid.handle_caught()
        if lives.value <=0:
            self.ship_destroy()

    for extralives in self.overlapping_sprites:
        extralives.add_extralives()

1 个答案:

答案 0 :(得分:0)

这是你的问题:

for asteroid in self.overlapping_sprites:
    asteroid.handle_caught()
    if lives.value <=0:
        self.ship_destroy()

调用你的循环变量asteroid的事实并不意味着它神奇地只会成为一个小行星。如果您有其他类型的物品可以碰撞,请不要! overlapping_sprites都是重叠的精灵,而不仅仅是小行星。在某些时候asteroid是一个ExtraLives对象。当您尝试在其上调用handle_caught()时,这显然会失败,因为ExtraLives没有handle_caught()方法。

此处最简单的解决方案是在add_extralives课程中将handle_caught重命名为ExtraLives。毕竟,你正在做同样的事情:处理碰撞(或“捕获”)对象的情况,它只是一种不同类型的对象,因此结果需要不同,您可以通过提供不同的代码来指定。能够通过调用相同的方法(称为“多态”)来实现完全不同类型的行为,这是面向对象编程的重点。

以下循环有类似的问题,因为您在可能不是add_extralives()类型的对象上调用ExtraLives。幸运的是,您可以删除此代码,因为您已经通过将add_extralives重命名为handle_caught来处理这种情况。

for extralives in self.overlapping_sprites:
    extralives.add_extralives()