0

嗨,下面是我的问题的相关代码:

    class Player:
        def __init__(self, name, x, y, isEvil):
            self.health = 50
            self.attack = randint(1, 5)
            self.name = name
            self.x = x
            self.y = y
            self.isEvil = isEvil

        def checkIsAlive(self):
            if self.health <= 0:
            return False
        else:
            return True

    # implicit in heritance. if the child doesn't have a function that the parent has
    # the functions of the parent can be called as if it were being called on the
    # parent itself

    class Enemy(Player):


        #def __init__(self, name, x, y, isEvil):
        # self.health = 50
        # self.name = name
        # self.x = x
        # self.y = y
        pass

还有更多代码:

    e = Enemy('Goblin', 10, 11, True)

    p = Player('Timmeh', 0, 1, False)
    isLight()

    while True:
        if p.checkIsAlive() == True and e.checkIsALive() == True:
            fight()

        else:
            if p.checkIsAlive() == True:
                print('%s is victorious!!! %s survived with %s health points.' % (p.name, p.name, p.health))
            else:
                print('%s shrieks in its bloodlust!!! %s has %s health points' % (e.name, e.name, e.health))

但是,当我尝试运行此程序时,出现以下错误:

    Traceback (most recent call last):
    File "<string>", line 420, in run_nodebug
    File "C:\Python33\practice programs\textstrat\classees.py", line 94, in <module>
    if p.checkIsAlive() == True and e.checkIsALive() == True:
    AttributeError: 'Player' object has no attribute 'checkIsAlive'

但是,当使用交互式控制台时,我可以这样做:

    if p.checkIsAlive() == True and e.checkIsAlive() == True:
    ...     print('they are')
    ...     
    they are

我要做的就是调用 checkIsAlive 的布尔值来确定两个对象是否发生冲突。它适用于所有其他方面,我可以只使用: if p.health <= 0 or e.health <= 0: 但是,当我还希望能够回收尽可能多的东西时,这会使我的 checkIsAlive() 方法变得毫无用处尽可能的代码。我真的无法弄清楚它为什么会这样,并且肯定很想理解它。提前感谢您的意见。

4

1 回答 1

0

正如在上面的评论中迅速指出的那样。我错过了属性名称 checkIsAlive 中的一个错字。

于 2014-09-05T04:11:53.107 回答