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 のブール値を呼び出して、2 つのオブジェクトが競合しているかどうかを判断することだけです。それは他のすべての点で機能し、次を使用できます: if p.health <= 0 or e.health <= 0: ただし、できるだけリサイクルできるようにしたい場合、 checkIsAlive() メソッドはかなり役に立たなくなりますコードのお尻が可能です。なぜこのように動作するのか、私には本当に理解できません。それを理解したいと思っています。ご意見をお寄せいただきありがとうございます。

4

1 に答える 1