这是我基于文本的游戏中的一段代码:
location_now = ""
class what_do:
def whaat(self):
interactions = what_do()
print "*What will you do? Type help_ to see all the actions*"
what = raw_input("")
if what == "help_":
print ' '.join(help_)
interactions.whaat()
if what == "travel":
print "These are all the cities you can travel to:"
mapje.map()
travel = raw_input("To which city do you want to travel?(Takes 10 seconds)")
if travel == locations[0] or travel == locations[1] or travel == locations[2] or travel == locations[3] or travel == locations[4] or travel == locations[5] or travel == locations[6] or travel == locations[7] or travel == locations[8]:
print "You are now travelling to %s" % travel
time.sleep(10)
print "You are now in %s!" % travel
location_now = travel
else:
print "That is no location in Skyrim!"
interactions.whaat()
我希望来自travel = raw_input
等的输入被存储并保存在变量location_now
(我在类之前和之外创建的)。我必须在以后的代码中使用这个输入。在
这节课将重复,因为它是一种“你想下一步做什么?”,因此,如果第二次输入what = raw_input("")
,它必须替换存储在location_now = ""
中的先前输入
我将把你的
location_now
变量作为一个静态变量移动到“what\u do”类中。(Static class variables in Python)作为一个有用的提示,这一行
可以简化为
^{pr2}$这将检查
travel
是否在位置列表中。只是一个小提示来简化你的代码!Python不漂亮吗?在在what()函数中,当您尝试为location_赋值时,实际上是在创建一个名为location_now的新局部变量。您现在没有为全局位置分配新值。在
现在需要在赋值之前将location_声明为global,这样就可以为全局变量赋值了。在
我相信您担心如果再次使用
raw_input()
变量中存储的任何内容都会被覆盖。 幸运的是,这种情况不会发生,如果您将raw_input()
的结果存储在变量中,它将保持不变。在你有没有遇到任何让你得出结论的问题?在
相关问题 更多 >
编程相关推荐