这是我基于文本的游戏的一些代码:
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 = ""
中的早期输入
我相信您担心如果再次使用raw_input()
,存储在location_now
变量中的任何内容都会被覆盖。幸运的是,这不会发生,如果您将raw_input()
的结果存储在变量中,它将保持不变。
您是否面临任何使您得出结论的问题?
我会将您的location_now
变量作为静态变量移动到类"what_do"中。(Python中的静态类变量)
同样作为有用的提示,这一行
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]:
可以减少到
if travel in locations:
这将检查travel
是否在位置列表中。只是一点提示来简化你的代码!蟒蛇不是很漂亮吗?
在 whaat() 函数中,当您尝试为location_now赋值时,您实际上是在创建一个名为 location_now 的新局部变量。您没有为全局location_now分配新值。
您需要在赋值之前将location_now声明为全局变量,以便实际为全局变量分配一个新值。
global location_now
location_now = travel