【发布时间】:2016-09-21 11:12:50
【问题描述】:
我目前正在尝试使用 Python 并编写一些文本冒险游戏。在我的游戏中,玩家具有某些属性,例如 hp、攻击伤害和物品的库存槽位。 我希望能够在我的代码中的任何地方调用这些属性。为此,我创建了一个接收三个值的函数:
“edit”:指定是否应该编辑变量
“info_id”:指定应该访问哪个变量
“value”:变量的新值
这就是我的代码中的样子:
def player_info(edit, info_id, value):
if edit == 1:
##function wants to edit value
if info_id == 1:
player_hp = value
print ("Assigned hp to: ", player_hp)
##the "prints" are just to check if the asignments work -> they do
return player_hp
elif info_id == 2:
player_attack = value
print ("Assigned attack to: ", player_attack)
return player_attack
elif info_id == 3:
item_1 = value
return item_1
elif info_id == 4:
item_2 = value
return item_2
elif info_id == 5:
item_3 = value
elif edit == 0:
##function wants to retrieve value
if info_id == 1:
return player_hp
elif info_id == 2:
return player_attack
elif info_id == 3:
return item_1
elif info_id == 4:
return item_2
elif info_id == 5:
return item_3
实际上有 10 个物品栏位(直到 info_id==13),但它们都一样。
我在代码开头定义了所有变量:
player_info(1,1,20)
player_info(1,2,5)
n=3
while n<=13:
player_info(1,n,0)
n=n+1
##items are not fully implemented yet so I define the item slots as 0
定义有效,我可以说是因为我在代码中实现了控制“打印”。仍然当我调用变量时,例如像这样的健康:
player_info(0,1,0)
我收到一个错误:
local variable 'player_hp' referenced before assignment
函数没有正确保存变量吗?或者是什么问题?
有没有更好的方法来保存变量?在这种情况下,全局变量是要走的路吗?
感谢您的帮助!
【问题讨论】:
-
请格式化您的代码。缩进是一团糟
-
您的函数正在创建名为
player_hp等的局部变量,它不会修改同名的全局变量。您可以使用global关键字使函数修改全局变量,但创建一个 Player 类并使用该类的实例会更好存储玩家信息。
标签: python function variables save call