(对于那些上次我问这个问题的人,我表示诚挚的歉意,当我指的是“功能”时,我使用了“模块”一词,但是仍然感谢您的非常有帮助的建议!我将确保当我开始将其他文件添加到方程式时要牢记这一点。)
我正在尝试使用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)
答案 0 :(得分:0)
这是我认为您要实现的目标的简单示例。如果您使用的是全局变量,则需要确保不要无意间在函数中创建具有相同名称的局部变量(当您要修改全局变量时)。
您应该查看使用classes的情况,我认为这可以帮助您解决一些语义上的混乱。
value = 10
def reset():
global value
value = 10
def start():
print(f'initial value: {value}')
global value
value += 1
print(f'updated value: {value}')
reset()
print(f'reset value: {value}')
start()
# OUTPUT
# initial value: 10
# updated value: 11
# reset value: 10
答案 1 :(得分:0)
您可以将这些内容存储到用作存储容器的类中。如果将它们声明为classvariables,并将所有访问器声明为@classmethods,则不需要实例。
class GameState:
gold = 0
exp = 0
etnl = 100 #exp to next level
maxHP = 50
curHP = 50
maxmana = 10
curmana = 10
helm = "none"
armtop = "none"
armbot = "none"
boots = "none"
gloves = "none"
weapon = "fists"
weapons = {"fists":(5,5),"sword":(15,12),"mace":(30,3),"cushion":(2,20)}
@classmethod
def reset(cls):
cls.gold = 0
cls.exp = 0
cls.etnl = 100 #exp to next level
cls.maxHP = 50
cls.curHP = 50
cls.maxmana = 10
cls.curmana = 10
cls.helm = "none"
cls.armtop = "none"
cls.armbot = "none"
cls.boots = "none"
cls.gloves = "none"
cls.weapon = "fists"
@classmethod
def attack(cls):
return cls.weapons.get(cls.weapon,(0,0))[0]
@classmethod
def defense(cls):
return cls.weapons.get(cls.weapon,(0,0))[1]
for w in State.weapons:
State.weapon = w
print("{} has attack {} and defense {}.".format(w, State.attack(),State.defense()))
输出:
fists has attack 5 and defense 5.
sword has attack 15 and defense 12.
mace has attack 30 and defense 3.
cushion has attack 2 and defense 20.
您可能想将某些东西分开-f.e.武器/伤害/防御相关物品的额外类别...
更多阅读:
答案 2 :(得分:0)
您是否考虑过将所有统计信息存储在类/结构中,而不是全局变量?在游戏开始时创建该类的实例,并在构造函数中指定其默认值。
G = StartClass()
def gamestart():
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("HP " + str(G.curHP) + "/" + str(G.maxHP))
或者,全局声明G并将其传递给gamestart(G)和/或在reset()函数中重新实例化也是可能的选择。