Python中的对象被误认为是另一个对象,因此它无法正常工作

时间:2013-10-09 15:45:53

标签: pygame

在我的程序中,我的'missilepack包'对象被误认为是小行星对象,并返回错误'Missilepack对象没有属性'handle_caught',我不明白为什么,修复此错误的任何帮助都会很棒。编辑:如果有人帮助我,导弹被误认为是小行星。

class MissilePack(games.Sprite):
speed = 1.7
image = games.load_image('MissilePack.bmp')
global inventory

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


def update(self):
    """ Check if bottom edge has reached screen bottom. """
    if self.bottom>games.screen.height:
        self.destroy()

def handle_caughtpack(self):
    inventory.append('missile')
    self.destroy.()

部分错误发生在'asteroid.handlecaught()位'

   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()

def check_pack(self):
    for missilepack in self.overlapping_sprites:
        missilepack.handle_caughtpack()

这是我的Asteroid类中的handle_caught()方法:

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 check_drop(self):
    """ Decrease countdown or drop asteroid and reset countdown. """
    if self.time_til_drop > 0:
        self.time_til_drop -= 0.7
    else:
        asteroid_size = random.choice(images)
        new_asteroid = Asteroid(x = self.x,image = asteroid_size)
        games.screen.add(new_asteroid)

        # makes it so the asteroid spawns slightly below the spawner   
        self.time_til_drop = int(new_asteroid.height * 1.3 / Asteroid.speed) + 1

def drop_missile(self):
    """Randomely drops a missile pack for the player to use"""
    dropmissile = random.randrange(0, 100)
    if dropmissile == 5:
        missilepack = MissilePack(x = self.x)
        games.screen.add(missilepack)

1 个答案:

答案 0 :(得分:0)

查看将精灵放在一个组中的代码真的很有用,但我发现了一个问题:当导弹以这种方式检查碰撞时,它也会返回它与自身碰撞的情况。它将尝试自己调用handle_caught方法。这很容易解决,你需要做的就是:

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

这只会让它忽略与自身的冲突。