2017-12-27 389 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)