我在顶部设置了3点伤害但是当我在底部输入伤害+ = 3时它表示没有引用伤害,为什么会发生这种情况?
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()
如果我将代码更改为底部的dagger = 6,它将打印6但是当我输入统计数据时,它会说损坏= 3
答案 0 :(得分:0)
你可以读取全局变量,但是如果你想为它们分配(重新绑定),你需要告诉Python你要使用global
关键字。< / p>
在这种情况下,根本不需要将这些变量设为全局变量。
您应该将这些属性移动到一个类中。在这个例子中,我称之为Player
import random, time
class Player:
def __init__(self):
self.inventory = ['dagger','torch']
self.hp = 50
self.maxhp = 50
self.damage = 3
self.ac = 4
self.gold = 10
self.in_combat = False
def choice(self):
choose = input(">> ")
if choose == "stats":
print("Health:", self.hp, ", Damage:", self.damage,
", Armour:", self.ac, ", Gold:", self.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():
pl = Player()
while pl.hp > 0:
if 'dagger' in pl.inventory:
pl.damage += 3
print(pl.damage)
pl.choice()
main()
除此之外:由于您可能要打印许多多行块,请在dedent
中查找textwrap
功能。你可以使用这样的东西:
from textwrap import dedent
def deprint(s):
print(dedent(s))
...
elif choose == "help":
deprint("""
Keywords:
stats | view your stats
backpack | view your inventory
help | view keywords to input
attack | attack an enemy when in combat""")