python - 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类中时?我很欣赏这更像是一篇社论,而不是一个问题,但任何帮助都将不胜感激。
解决方案
推荐阅读
- php - 如何在 Wordpress 中更改 Woocommerce 订单跟踪状态文本?
- javascript - window.addEventListener("message" ... 不适用于 IE11
- sap-cloud-platform - 使用 S4 SDK 集成 SuccessFactors 和 S4HANA
- php - UPS 费率 API 未获取地面/第二天/隔夜的值
- office365 - 保持 web 前景添加始终显示
- sql-server - 如何将 csv 文件从一台 linux 服务器导入到另一台服务器(mssql 服务器)
- python - 为数据框中的每一行绘制图表并保存为 jpg 格式?
- python - 删除具有一定百分比 0 的 pandas 的列和行
- php - 由于两个表之间的外键约束而无法登录
- node.js - node_module 和 aws lambda 函数