首页 > 解决方案 > python pickle 的视频游戏保存/加载问题(不加载实例)

问题描述

我目前正在 python 中进行文本冒险(这种语言只是因为它是我所知道的语言),并且我发现创建和加载保存文件会删除我所做的一些机制。我将在此处包含有问题的代码,而不是所有可以正常工作的元素。它主要与类以及如何“腌制”实例有关。

以下是我创建的一些类:

class Player:
def __init__(self, name):
    self.sack = []
    self.kit = []
    self.equipped = []
    self.log = []
    self.done = []
class Weapon:
def __init__(self, name, price, minattack, maxattack):
    self.name = name
    self.price = price
    self.minattack = minattack
    self.maxattack = maxattack
class Food:
def __init__(self, name, price, healthadd):
    self.name = name
    self.price = price
    self.healthadd = healthadd
class Quest:
def __init__(self, name, requirement, num, gold, npc, place, give_text, prog_text, comp_text, done_text):
    self.name = name
    self.requirement = requirement
    self.num = num
    self.score = 0
    self.gold = gold
    self.npc = npc
    self.place = place
    self.give_text = give_text
    self.prog_text = prog_text
    self.comp_text = comp_text
    self.done_text = done_text

我在这里包含的 Player 类中的实例只是由其他机制与武器、食物和任务附加的实例。该代码包括填充武器、食物和任务的区域(尽管处理单独的资产文件可能会稍微整理一下)。

以下是当前保存/加载功能的工作方式:

def save(lastplace):
clear()
with open('savefile', 'wb') as f:
    PlayerID.currentplace = lastplace.name
    pickle.dump(PlayerID, f)     
    print("Game saved:\n")
    print(PlayerID.name)
    print("(Level %i)" % (PlayerID.level))
    print(lastplace.name)
    print('')
option = input(">>> ")
goto(lastplace)
def load():
clear()
if os.path.exists("savefile") == True:
    with open('savefile', 'rb') as f:
        global PlayerID
        PlayerID = pickle.load(f)
        savedplace = PlayerID.currentplace
        savedplace = locations[savedplace]
        goto(savedplace)        
else:
    print("You have no save file for this game.")
    option = input('>>> ')
    main()

值得注意的是,进入游戏后,PlayerID(你)成为一个全局变量。您可能会开始看到这里的一些问题,或者更确切地说是总体问题。本质上,酸洗过程序列化存储在 Player 类中的列表中的所有可能的类类型,只需附加它们的名称,从而在加载回游戏时删除它们的类属性。

有没有一种pythonic方法来确保类实例被保存以备将来加载,以便它们仍然可以像类一样运行,特别是当堆叠在Player类中时?我很欣赏这更像是一篇社论,而不是一个问题,但任何帮助都将不胜感激。

标签: pythonpython-3.xpicklegame-development

解决方案


推荐阅读