python - 有人可以向我解释为什么调用 updateGame() 函数时“健康”变量没有更新吗
问题描述
一直在网上寻找一些答案,但是我仍然不清楚为什么在调用 getDamage() 函数时“健康”变量没有更新
我在学习 python 的最初几英里
health = 200.0
maxHealth = 200
healthDashes = 20
dashConvert = int(maxHealth/healthDashes)
currentDashes = int(health/dashConvert)
remainingHealth = healthDashes - currentDashes
healthDisplay = '-' * currentDashes
remainingDisplay = ' ' * remainingHealth
percent = str(int((health/maxHealth)*100)) + "%"
gameOver = False
def updateGame():
print(chr(27) + "[2J")
print (30 * '-')
print("")
print(" |" + healthDisplay + remainingDisplay + "|")
print(" health " + percent)
print ("")
print (30 * '-')
print("")
def getDamage():
global health
health = 10
while gameOver == False:
answer = raw_input("> ").lower()
if answer == "help":
print("")
print(" you can use the following commands: h, i, q, d")
print("")
elif answer == "q":
print("\n")
print("Game Over")
print("")
break
elif answer == "h":
updateGame()
elif answer == "d":
getDamage()
else:
print(""" not a valid command, see "help" """)
下次我调用 getDamage() 函数时,我能做些什么来正确更新“健康”变量并显示降低的健康状况吗?
基本上我想要实现的是一个基于文本的游戏,它在一个while循环中运行,并具有不同的功能来更新一个主要功能(updateGame),该功能显示有关玩家状态的相关信息,如健康、库存物品。
我试图实现的逻辑是:让 getDamage() 减少健康变量,然后用 updateGame() 显示新更改的变量
非常感谢
解决方案
在 updateGame 函数中,您永远不会引用全局变量 health。如果你想在函数内部改变健康,你需要访问它。
这意味着你应该有类似的东西:
def updateGame():
global health
health = updatedHEALTH
...
然后每次调用该函数时它都应该改变
推荐阅读
- laravel - LARAVEL 部署后有什么命令可以执行吗?
- visual-studio-2015 - 尽管设置为关闭,但在 getter 上自动格式化分号上的语句
- google-sheets - 条件日期格式
- c# - 如何在 aspx 标记中附加一个字符串以访问资源文件?
- typescript - 在 vue 模板中使用 Typescript 静态方法
- asp.net-mvc - 向数据库 mvc 添加多个东西的不那么懒惰的方式
- php - PHP如何从一个数组创建另一个数组
- android - 在 Thread 上刷新 UI 并更改 Fragment 时出错
- react-native - 当应用程序滚动时,标题会保持在顶部
- python - Keras/TensorFlow 中的损失函数