2017-12-27 350 views
-1

嗨我正在进行一个python文本冒险,并且我有一个保存所有主要变量库存,位置和黄金的保存功能。然后我添加了2个变量,它不起作用。 在此先感谢。python pickle IndexError:元组索引超出范围

这是我的工作代码。

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

什么是跟踪的确切错误? 'loadValues'可能不包含尽可能多的元素。你是否验证了它包含的内容? – Carcigenicate

+1

第一眼看起来这2个片段看起来是正确的。你确定你没有混合来自第一个片段的'do_save'和第二个片段的'do_load'吗?尝试打印'loadValues'之后再做任何事情。另外,'arg'似乎没有被使用。 – CristiFati

回答

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) 
相关问题