首页 > 解决方案 > 有人可以向我解释为什么调用 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() 显示新更改的变量

非常感谢

标签: python

解决方案


在 updateGame 函数中,您永远不会引用全局变量 health。如果你想在函数内部改变健康,你需要访问它。

这意味着你应该有类似的东西:

def updateGame():
  global health
  health = updatedHEALTH
  ...

然后每次调用该函数时它都应该改变


推荐阅读