(对于上次我问这个问题时看到这个问题的人,我真诚地道歉,我用了“模块”这个词来表示“功能”,但非常感谢您的宝贵建议!当我开始向公式中添加其他文件时,一定要记住这一点。)
我正在尝试使用python制作一个基于文本的冒险游戏,结果它需要很多变量,而回溯是必须的,我需要使用全局变量作为基本变量。我在试图让其他函数读取这些文件时遇到了减速带。这是用于定义通用变量及其起始值的代码行
def reset():
global gold, exp, etnl, maxHP, curHP, maxmana, curmana, attack, defence, helm, armtop, armbot, boots, gloves, weapons
gold = 0
exp = 0
etnl = 100 #exp to next level
maxHP = 50
curHP = 50
maxmana = 10
curmana = 10
attack = 5
defence = 5
helm = "none"
armtop = "none"
armbot = "none"
boots = "none"
gloves = "none"
weapon = "fists"
例如,当我试图显示一个全局变量时,它显示为未定义的变量,如下所示:
def gamestart():
clear() #this command is fine, simply to make it look neater when it is run again
print("you wake up in a clearing in the forest, you can't remember what happened.")
print("you feel numb, you realize you're lying flat on your back.")
print
print("HP " + str(curHP) + "/" + str(maxHP))
有人能帮我解决这个问题吗? 有没有更简单的方法? 感谢您的帮助! (是的,我确保在newgame函数之前运行reset函数)
一个更简单的版本,至少在我看来是:
def variable():
global foo
foo = 7
def trigger():
variable():
output():
def output():
print(foo)
您可以将这些东西存储到用作存储容器的类中。如果将它们声明为类变量和任何访问器@classmethods,则不需要实例。你知道吗
输出:
你可能想把一些东西分开-f.e.一个额外的类用于武器/伤害/防御相关的东西。。。你知道吗
更多阅读:
这是一个简单的例子,我认为你正在努力实现。如果您使用的是全局变量,那么您需要确保不会无意中在函数中创建具有相同名称的局部变量(当您打算修改全局变量时)。你知道吗
你应该看看如何使用classes,我认为这会帮助你解决一些语义上的混乱。你知道吗
您是否考虑过将所有统计信息存储在类/结构中而不是全局变量?在游戏开始时创建类的实例,其默认值在构造函数中指定。你知道吗
G=开始类()
或者,全局声明G并将其传递到gamestart(G)和/或在reset()函数中重新实例化可能是可选的。你知道吗
相关问题 更多 >
编程相关推荐