我需要帮助从一个数字中减去另一个数字

-6 投票
3 回答
713 浏览
提问于 2025-04-18 10:38

我正在尝试编写一个基于文本的冒险游戏,以熟悉Python。基本上,我在处理健康值和攻击力等方面。我的健康值和攻击力的数值是

health=50
squidAttack=5
squidHealth=20
attack=5

然后我定义了

def squidAttack():
 global health
 global squidHealth
 global squidAttack
 health=health-squidAttack

但是当我运行时,出现了错误:

Traceback (most recent call last):                                    
File "C:\Users\AaronC\Documents\Python\Krados.py", line 280, in
<module> squidAttack()                File
"C:\Users\AaronC\Documents\Python\Krados.py", line 253, in squidAttack
health=health-squidAttack                                             
TypeError: unsupported operand type(s) for -: 'int' and 'function'

我想强调的是;我对这些错误的意思完全不懂,我搜索了很多,但找不到任何相关的信息。请帮帮我。

3 个回答

0

你把名字叫做 squidAttack 的变量和一个用来从 health 中减去这个变量的函数都叫成了 squidAttack。因为函数是在后面定义的,所以它把 5 这个值的意思给覆盖了。当你尝试执行 health=health-squidAttack 时,Python 会用函数的定义来处理 squidAttack,结果就是想从一个数字中减去一个函数。这显然是行不通的。你需要把其中至少一个 squidAttack 改个名字,这样它们就能有不同的名字了。

0
squidAttack = 5
# squidAttack is an int

# ... Code goes here ...

def squidAttack():
    # stuff goes here

# squidAttack is a function
class Actor(object):
    def __init__(self, name, health, attack):
        self.name = name
        self.health = health
        self.attack = attack
    def attacks(other):
        other.health -= self.attack

me = Actor("Me", 50, 5)
squid = Actor("Squid", 20, 5)

squid.attacks(me)

当你定义 squidAttack 这个函数时,它重新定义了之前的一个整数(int)。

其实,有一个更好的方法,那就是使用类(classes)。

2

你把变量和函数都叫做 squidAttack,这就造成了混淆。只要把其中一个改个名字,就能正常工作了。

撰写回答