簡體   English   中英

python pickle IndexError:元組索引超出范圍

[英]python pickle IndexError: tuple index out of range

嗨,我正在從事 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: tuple index out of range

我想出了一個解決方案,但這里的代碼可能不是最有效的方法

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM