python pickle IndexError:元组索引超出范围

时间:2017-12-27 13:09:02

标签: python python-2.7 pickle

嗨,我正在进行python文本冒险,我得到了一个保存功能,可以保存所有主要变量库存,位置和黄金。然后我又添加了2个变量,它不起作用。 提前谢谢。

这是我的工作代码。

def do_save(self, arg):
    saveGame = open('savegame.txt', 'wb')
    saveValues = (inventory, gold, location)
    pickle.dump(saveValues, saveGame)
    saveGame.close()

def do_load(self, arg):
    global inventory
    global gold
    global location
    global equiped
    global health
    loadGame = open('savegame.txt', 'rb')
    loadValues = pickle.load(loadGame)
    inventory = loadValues[0]
    gold = loadValues[1]
    location = loadValues[2]
    loadGame.close()

这是无效的代码

def do_save(self, arg):
    saveGame = open('savegame.txt', 'wb')
    saveValues = (inventory, gold, location, equiped, health)
    pickle.dump(saveValues, saveGame)
    saveGame.close()

def do_load(self, arg):
    global inventory
    global gold
    global location
    global equiped
    global health
    loadGame = open('savegame.txt', 'rb')
    loadValues = pickle.load(loadGame)
    inventory = loadValues[0]
    gold = loadValues[1]
    location = loadValues[2]
    equiped = loadValues[3]
    health = loadValues[4]
    loadGame.close()

我得到的错误信息是IndexError:元组索引超出范围

1 个答案:

答案 0 :(得分:0)

我提出了一个解决方案,但这可能不是最有效的方法是代码

def do_save(self, arg):
    saveGame = open('savegame.txt', 'wb')
    saveValues = (inventory, gold, location, equiped, health)
    saveValues1 = (equiped, health)
    pickle.dump(saveValues, saveGame)
    pickle.dump(saveValues1, saveGame)
    saveGame.close()

def do_load(self, arg):
    global inventory
    global gold
    global location
    global equiped
    global health
    loadGame = open('savegame.txt', 'rb')
    loadValues = pickle.load(loadGame)
    inventory = loadValues[0]
    gold = loadValues[1]
    location = loadValues[2]
    equiped = loadValues[3]
    health = loadValues[4]
    loadGame.close()
    displayLocation(location)