简体   繁体   English

从列表中分配变量,或“如何制作优雅的保存功能”

[英]Assigning variables from a list, or “how to make an elegant save function”

I'm currently working on a small text based game, the game remembers the gamestate based on global variables, for example, goblins_dead to see if you've killed the goblins yet. 我目前正在开发一款基于文本的小型游戏,该游戏会记住基于全局变量的游戏状态,例如goblins_dead,以查看您是否杀死了这些妖精。

This worked pretty well, until I decided to add a save and load function. 在我决定添加保存和加载功能之前,此方法运行良好。 The save function works, the load function does not, and while I know why, I can't come up with an easy fix. 保存功能有效,加载功能无效,虽然我知道为什么,但是我无法提出简单的解决方案。

The way the save function currently works is this, I have a list with all the global variables we've used in the game so far. 保存功能当前的工作方式是这样,我有一个列表,列出了到目前为止我们在游戏中使用的所有全局变量。 Then I have the list run through each varaiable and give a 1 if its true or a 0 if its not, at the end it prints a "seed" that consists of a list of 1s and 0s the user can input. 然后,让列表遍历每个变量,如果为true,则为1,否则为0,最后,它会打印“种子”,其中包含用户可以输入的1和0的列表。 It looks like this, in my sample test code 看起来像这样,在我的示例测试代码中

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

This code works, it yields a string, that matches the values in the way I want. 这段代码有效,它产生一个字符串,该字符串以我想要的方式与值匹配。

The issue comes when its time to load. 问题是何时加载。 I inverted this process, like this: 我颠倒了这个过程,像这样:

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()

The mistake will be obvious to more seasoned programmers, it turns out lists load what a variable points at, not the variable name, so I can't assign things in this way. 这个错误对于经验丰富的程序员来说是显而易见的,事实证明列表加载了变量所指向的内容,而不是变量名,因此我不能以这种方式分配东西。

This is where I'm stumped, I could just make a long list of if statements, but that's not very elegant. 这就是我很困惑的地方,我可以列出一长串if语句,但这不是很优雅。 Further reading suggests that a dictionary approach might be the way to solve this, but I'm unsure on how I would go about implementing a dictionary, more specifically, I'm not sure how dictionaries interact with variables, my understanding is that this is how variables are actually stored in python, but I'm not sure how to get started on accessing and storing those variables reliably, or if I could use a global dictionary to store all my variables in the game properly. 进一步的阅读表明,字典方法可能是解决此问题的方法,但是我不确定如何实现字典,更具体地说,我不确定字典如何与变量交互,我的理解是如何将变量实际存储在python中,但是我不确定如何开始可靠地访问和存储这些变量,或者我是否可以使用全局字典将所有变量正确存储在游戏中。 Basically, I'm unsure of how to "correctly" use a dictionary to its full potential, specifically how it interacts with variables. 基本上,我不确定如何“正确”使用字典以发挥其全部潜能,特别是它如何与变量交互。

That's much larger than necessary. 这比必要的要大得多。 Just use string formatting to provide the save password: 只需使用字符串格式来提供保存密码:

print 'Your seed is {}{}{}{}'.format(goblins_defeated+0, lucky+0, princesshelp+0, end+0)

Adding 0 converts each boolean into its numeric representation. 加0会将每个布尔值转换为其数字表示形式。 Each value is inserted into the string, replacing the {} . 每个值都将插入到字符串中,以替换{}

Load like this: 像这样加载:

seed = raw_input("> ")
goblins_defeated, lucky, princesshelp, end = map(bool, map(int, seed.split()))

This splits seed on whitespace, maps each element to an integer, then maps each of those integers to a boolean, then unpacks that map object into the appropriate variables. 这会在空白处分割seed ,将每个元素映射为一个整数,然后将这些整数中的每个映射为布尔值,然后将该map对象解压缩为适当的变量。

You don't necessarily have to store these conditions as booleans at all, as 1 and 0 will evaluate similarly, with 0 for False and 1 for True . 您完全不必将这些条件存储为布尔值,因为10计算结果相似,其中0表示False1表示True Booleans are actually a subclass of int anyway. 无论如何,布尔实际上是int的子类。 You can even do math with them, eg True+True equals 2 . 您甚至可以对它们进行数学运算,例如True+True等于2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM