[英]Assigning variables from a list, or “how to make an elegant save function”
我目前正在开发一款基于文本的小型游戏,该游戏会记住基于全局变量的游戏状态,例如goblins_dead,以查看您是否杀死了这些妖精。
在我决定添加保存和加载功能之前,此方法运行良好。 保存功能有效,加载功能无效,虽然我知道为什么,但是我无法提出简单的解决方案。
保存功能当前的工作方式是这样,我有一个列表,列出了到目前为止我们在游戏中使用的所有全局变量。 然后,让列表遍历每个变量,如果为true,则为1,否则为0,最后,它会打印“种子”,其中包含用户可以输入的1和0的列表。 看起来像这样,在我的示例测试代码中
def game_save():
print "This will give you a seed. Write it down, or see seed.txt"
print "When you start a new game, you will be propted to give your seed. Do so to reload."
global goblins_defeated
global lucky
global princesshelp
end = "done"
load_seed =[goblins_defeated, lucky, princesshelp, end]
load_seed.reverse()
variable = load_seed.pop()
seed = []
print globals()
while end in load_seed:
if variable == True:
seed.append("1")
print "APPENEDED 1"
print load_seed
variable = load_seed.pop()
elif variable == False:
seed.append("0")
print "APPENED 0"
print load_seed
variable = load_seed.pop()
else:
print "ERROR"
break
seedstring = ' '.join(seed)
print "This is your seed %s" %seedstring
这段代码有效,它产生一个字符串,该字符串以我想要的方式与值匹配。
问题是何时加载。 我颠倒了这个过程,像这样:
def game_load():
print "Please type your seed in here:"
global goblins_defeated
global lucky
global princesshelp
end = "done"
seedlist = [goblins_defeated, lucky, princesshelp, end]
seed = raw_input("> ")
seed_list = seed.split(" ")
seed_value = seed_list.pop()
variable_list = [end, goblins_defeated, lucky, princesshelp]
variable = variable_list.pop()
testlist = []
while end in variable_list:
if seed_value == '1':
variable = True
print variable_list
print variable
print seed_value
elif seed_value == '0':
variable = False
print variable_list
print variable
print seed_value
else:
print "ERROR ERROR FALSE LOOP RESULT"
break
if bool(seed_list) == False:
print "List is empty"
else:
seed_value = seed_list.pop()
variable = variable_list.pop()
这个错误对于经验丰富的程序员来说是显而易见的,事实证明列表加载了变量所指向的内容,而不是变量名,因此我不能以这种方式分配东西。
这就是我很困惑的地方,我可以列出一长串if语句,但这不是很优雅。 进一步的阅读表明,字典方法可能是解决此问题的方法,但是我不确定如何实现字典,更具体地说,我不确定字典如何与变量交互,我的理解是如何将变量实际存储在python中,但是我不确定如何开始可靠地访问和存储这些变量,或者我是否可以使用全局字典将所有变量正确存储在游戏中。 基本上,我不确定如何“正确”使用字典以发挥其全部潜能,特别是它如何与变量交互。
这比必要的要大得多。 只需使用字符串格式来提供保存密码:
print 'Your seed is {}{}{}{}'.format(goblins_defeated+0, lucky+0, princesshelp+0, end+0)
加0会将每个布尔值转换为其数字表示形式。 每个值都将插入到字符串中,以替换{}
。
像这样加载:
seed = raw_input("> ")
goblins_defeated, lucky, princesshelp, end = map(bool, map(int, seed.split()))
这会在空白处分割seed
,将每个元素映射为一个整数,然后将这些整数中的每个映射为布尔值,然后将该map
对象解压缩为适当的变量。
您完全不必将这些条件存储为布尔值,因为1
和0
计算结果相似,其中0
表示False
, 1
表示True
。 无论如何,布尔实际上是int
的子类。 您甚至可以对它们进行数学运算,例如True+True
等于2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.