0
我在顶部设置了3点伤害,但是当我在底部键入损伤+ = 3时它说没有引用损伤,为什么会发生这种情况?Python变量不能按预期工作
import random, time
inventory = ['dagger','torch']
hp = 50
maxhp = 50
damage = 3
ac = 4
gold = 10
in_combat = False
def choice():
choose = input(">> ")
if choose == "stats":
print("Health:",hp,", Damage:",damage,", Armour: ",ac,", Gold:",gold)
elif choose == "backpack":
print(inventory)
elif choose == "help":
print("Keywords:\nstats | view your stats\nbackpack | view your inventory\nhelp | view keywords to input\nattack | attack an enemy when in combat")
else:
print("Invalid Input")
class Enemy:
def __init__(self, name, attack, armour, health):
self.name = name
self.attack = attack
self.armour = armour
self.health = health
def attack_enemy(self):
time.sleep(1)
print("What action do you want to make?\nType 'help' for a list of actions\n")
answer = input(">> ")
if answer == "attack":
self.health = self.health - damage
print(self.name,"health is: ",self.health)
def main():
while hp > 0:
if 'dagger' in inventory:
damage += 3
print(damage)
choice()
main()
另外,如果我改变代码的底部,将打印6匕首= 6,但是当我键入统计,它会说伤害= 3
'damage'不是'global'变量和'main'都有自己的范围... – jonrsharpe
的修复@zondo建议不涉及结构问题你有。为什么不为用户/玩家状态创建类似于你的敌人类的另一个类,所以它不会混淆你的全局命名空间?如果你不明白我的建议,我可以把它放在答案中。 –