-1

我正在尝试转换我为计算单个“损坏”输出而制作的函数,但我不明白我哪里出错了。作为一个函数,它正常处理我的方法,但是当我进入一个类时,我收到一个未找到的全局名称。另外,我认为我的init是正确的,但我可能是错的。

import random

class Damage(object):
    """Represents 1 single damage value"""

    def __init__(self):
        """Constructor initializes objects attributes. stats."""
        ### I need to initialize my stats from a different class since they
        ### are not a constant. self._statList is a dictionary that will be
        ### imported.
        self._statList = {"strength":100, "hitStat":90, "eBlockchance":10, \
                          "critStat":15, "defense":0}
        self._strength = self._statList["strength"]
        self._hitStat  = self._statList["hitStat"]
        self._eBlockchance = self._statList["eBlockchance"]
        self._defense = self._statList["defense"]
        self._critStat = self._statList["critStat"]

    def __str__(self):
        """Returns string representation of the damage"""
        self._base = self._strength - self._defense
        self._damage = random.randint(self._base/2, self._base)
        ### I have no idea why this isn't running my methods below.
        ### NameError: global name 'hitChance' is not defined.
        if hitChance() == True:
            return "Miss"
        else:
            if enemyBlock() == True:
                return "Block"
            else:
                if critChance() == True:
                    return str(self._damage*2) + "CRITICAL"
                else:
                    return str(self._damage)

    def critChance(self):
        self._chance = random.randint(1,100)
        if self._chance <= self._critStat:
            return True

    def enemyBlock(self):
        self._chance = random.randint(1,100)
        if self._chance <= self._eBlockchance:
            return True

    def hitChance(self):
        self._chance = random.randint(1,100)
        if self._chance > self._hitStat:
            return True
4

1 回答 1

5

你有类似的东西:

if hitChance() == True:

它必须是:

if self.hitChance() == True:

就像你需要一个显式self的成员变量一样self._strength,你也需要它的方法。

于 2013-04-26T21:36:33.667 回答