Pygame,livewires:属性错误:消息对象没有属性'handle collide'

时间:2015-05-25 16:06:27

标签: python pygame livewires

我正在使用来自 Python Programming For The Absolute Beginner 的特殊'pygame'和'livewires'进行游戏,并且它在大多数情况下运行良好。在你可以玩游戏的那一刻,一个计时器会勾选,然后当一个尖峰击中你的文字'失去!时间:'然后,无论何时,你都会出现。但是,尽管消息生命周期为300,但是当屏幕关闭时,消息会持续不到一秒钟,您会看到此错误:

Traceback (most recent call last):
    File "run.py", line 105, in main
        games.screen.mainloop()
    File "C:\Python31\lib\site-packages\livewires\games.py, line 308, in mainloop


       object._tick()
    File "C:\Python31\lib\site-packages\livewires\games.py", live 506, in _tick
        self.update()
    File "run.py", line 27, in update
        self.check_collide()
    File "run.py", line 34, in check_collide
        spike.handle_collide()
AttributeError: 'Message' object has no attribute 'handle_collide'

哇。以下是相关代码(根据我的判断):

class Player(games.Sprite):
    """The player that must dodge the spikes."""

    def __init__(self, image, x, y):
        super().__init__(image=image, x=x, y=y)
        """
        Timer
        """
        self.timer = games.Text(value = 0,
                            size = 40,
                            color = color.black,
                            x = 600,
                            y = 440)
        games.screen.add(self.timer)

    def update(self):
        """Move to the mouse."""
        self.x = games.mouse.x
        self.y = games.mouse.y
        self.check_collide()
        self.timer.value = int(time.clock())


    def check_collide(self):
        """Check for a collision with the spikes."""
        for spike in self.overlapping_sprites:
            spike.handle_collide()



class Spike(games.Sprite):
    """A spike!"""

    def update(self):
        """Move to the left!"""
        self.x -= random.randrange(3,12)
        if self.x == 0 or self.x == 1 or self.x == 2 or self.x == 3 or self.x == 4 or self.x == 5 or self.x == 6 or self.x < 10:
            self.x = 640
            self.y = random.randrange(games.screen.height)

    def handle_collide(self):
        """Destroy!"""

        timebomb = int(time.clock())
        man = ("Lose! Time:",timebomb)
        lost_message = games.Message(value = man,
                            size = 100,
                            color = color.red,
                            x = games.screen.width/2,
                            y = games.screen.height/2,
                            lifetime = 300,
                            after_death = games.screen.quit)
        games.screen.add(lost_message)

我很困惑。应该调用方法handle_collide以便游戏可以完成,但似乎事情handle_collide是对象消息的属性?如果这看起来很愚蠢那么抱歉因为我老老实实地试着用这个,正如书名所暗示的那样,我是一个菜鸟。请提前帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

找到了解决办法。

def check_collide(self):
    """Check for a collision with the spikes."""
    for spike in self.overlapping_sprites:
        spike.handle_collide()

for循环中的' spike '只是与玩家碰撞的名称。实际发生的是玩家与“消息”对象发生碰撞,然后询问消息对象处理精灵碰撞的方式。消息对象未准备好,并且没有“ handle_collide ”方法来处理此问题。所以它抛出一个错误。要修复它,您只需将文本从播放器移开,或者使用“消息”对象进行游戏,并创建for循环所期望的方法。