如何从函数中永久更改python中的全局变量?
我正在尝试用python创建一个基于文本的冒险游戏,其中将有与怪物和商店的战斗,你可以增加你的生命值和伤害。我意识到在函数中使用全局变量是不可取的,但我还没有找到另一种实现我想要做的事情的方法。战斗和商店在游戏中出现在多个点上,所以我认为定义它们是重复使用它们的最佳方式。以下是一个小部分,涉及商店中提供的商品:如何从函数中永久更改python中的全局变量?,python,Python,我正在尝试用python创建一个基于文本的冒险游戏,其中将有与怪物和商店的战斗,你可以增加你的生命值和伤害。我意识到在函数中使用全局变量是不可取的,但我还没有找到另一种实现我想要做的事情的方法。战斗和商店在游戏中出现在多个点上,所以我认为定义它们是重复使用它们的最佳方式。以下是一个小部分,涉及商店中提供的商品: import random own_health = 15 gold = 10 helmet = False def helmet(): global own_health
import random
own_health = 15
gold = 10
helmet = False
def helmet():
global own_health
global gold
global helmet
health_boost = random.randint(2,5)
cost = random.randint(7,10)
print("There is a helmet that costs", cost, "and will increase your health by", health_boost)
buy = input("Would you like to buy and equip the helmet? (y/n): ")
if buy == "y":
if gold - cost > -1 and helmet == False:
gold -= cost
own_health += health_boost
helmet = True
elif gold - cost < 0:
print("You don't have enough money to buy this helmet.")
elif helmet == True:
print("You are already wearing a helmet.")
elif buy == "n":
print("You didn't buy the helmet.")
else:
print("Invalid input.")
helmet()
print(own_health)
print(gold)
print(helmet)
随机导入
自身健康=15
黄金=10
头盔=假
def头盔():
全球自身健康
全球黄金
全球头盔
健康状况提升=随机。随机数(2,5)
成本=随机。随机数(7,10)
打印(“有一个头盔需要花费”,花费,“并且会增加你的健康”,健康促进)
购买=输入(“您想购买并装备头盔吗?(y/n):”)
如果购买=“y”:
如果黄金-成本>-1且头盔==假:
黄金-=成本
自身健康+=健康提升
头盔=真
elif黄金-成本<0:
打印(“你没有足够的钱买这个头盔。”)
elif头盔==真:
打印(“您已经戴上头盔了。”)
elif buy==“n”:
打印(“你没有买头盔。”)
其他:
打印(“无效输入”)
头盔()
打印(自身健康)
印刷品(金色)
印花(头盔)
此代码的结果是,own_health、gold和Healm被设置回执行函数helm()
之前的原始值。是否有办法解决此问题,以便在执行函数后永久设置全局变量?如果没有,我渴望听到任何不同的方式,我可以代码的程序
if gold - cost > -1 and helmet == False:
此条件永远不会成功,因为函数中的helmet
永远不会为False。当您使用相同的名称定义函数时,您创建的own_health
和gold
下方的头盔将被覆盖。尝试为函数指定不同的名称,例如get\u helmet
。然后,您的全局文件应根据需要进行更新:
c:\Users\Kevin\Desktop>test.py
There is a helmet that costs 7 and will increase your health by 2
Would you like to buy and equip the helmet? (y/n): y
17
3
True
确实应该避免使用全局变量。最好将它们作为参数传递
您有多个相同变量的实例。全局变量不应该在函数中声明,而应该在外部的某个地方声明。如果全局变量在声明它们的文件之外使用,请导入该文件并将文件名附加到全局变量的开头
导入文件名
fileName.gold
..我将创建一个类:
import random
class myClass:
def __init__(self, own_health, gold, helmet):
self.own_health = own_health
self.gold = gold
self.helmet = helmet
def buyHelmet(self):
health_boost = random.randint(2,5)
cost = random.randint(7,10)
print("There is a helmet that costs", cost, "and will increase your health by", health_boost)
buy = input("Would you like to buy and equip the helmet? (y/n): ")
if buy == "y":
if self.gold - cost > -1 and self.helmet == False:
self.gold -= cost
self.own_health += health_boost
self.helmet = True
elif self.gold - cost < 0:
print("You don't have enough money to buy this helmet.")
elif self.helmet == True:
print("You are already wearing a helmet.")
elif buy == "n":
print("You didn't buy the helmet.")
else:
print("Invalid input.")
kbball = myClass(15, 10, False)
print(kbball.own_health)
print(kbball.gold)
print(kbball.helmet)
kbball.buyHelmet()
print(kbball.own_health)
print(kbball.gold)
print(kbball.helmet)
#output
15
10
False
There is a helmet that costs 10 and will increase your health by 2
17
0
True
随机导入
类别myClass:
定义初始(自我、自身健康、黄金、头盔):
self.own\u health=自身健康
self.gold=黄金
self.helmet=头盔
def安全帽(自身):
健康状况提升=随机。随机数(2,5)
成本=随机。随机数(7,10)
打印(“有一个头盔需要花费”,花费,“并且会增加你的健康”,健康促进)
购买=输入(“您想购买并装备头盔吗?(y/n):”)
如果购买=“y”:
如果self.gold-成本>-1且self.helmet==False:
self.gold-=成本
self.own_health+=健康提升
self.helmet=True
elif self.gold-成本<0:
打印(“你没有足够的钱买这个头盔。”)
elif self.helmet==真:
打印(“您已经戴上头盔了。”)
elif buy==“n”:
打印(“你没有买头盔。”)
其他:
打印(“无效输入”)
kbball=myClass(15,10,False)
打印(kbball.own_health)
打印(kbball.gold)
打印(kbball.头盔)
kbball.buyHelmet()
打印(kbball.own_health)
打印(kbball.gold)
打印(kbball.头盔)
#输出
15
10
错误的
有一个头盔,价格为10美元,将增加你的健康2
17
0
符合事实的
解决此问题的一种方法是使用OOP
class Game():
def __init__(self):
self.own_health = 15
self.gold = 10
self.helmet = 5
def helmet(self):
health_boost = random.randint(2,5)
cost = random.randint(7,10)
print("There is a helmet that costs", cost, "and will increase your health by", health_boost)
buy = input("Would you like to buy and equip the helmet? (y/n): ")
if buy == "y":
if self.gold - cost > -1 and self.helmet == False:
self.gold -= cost
self.own_health += health_boost
self.helmet = True
elif self.gold - cost < 0:
print("You don't have enough money to buy this helmet.")
elif self.helmet == True:
print("You are already wearing a helmet.")
elif buy == "n":
print("You didn't buy the helmet.")
else:
print("Invalid input.")
现在,您可以按如下方式检查变量值:
game = Game()
game.helmet()
print(game.get_own_health())
在这种情况下,请澄清“永久”的含义。将变量作为参数传递给函数。不要将函数和变量命名为相同的名称。使用数据结构(例如,dict
s和object
s)而不是顶级变量。您误用了全局关键字,但它们已更改。我在这里看到了设计问题。为什么不编写一个Player
类呢?我建议您学习避免完全使用全局变量的方法。对于eample,您可以创建一个玩家
类,该类存储关于玩家的数据,以及一个设备
类,用于任何类型的设备,而不仅仅是头盔。
game = Game()
game.helmet()
print(game.get_own_health())