Python text game: how to make a save feature?(Python文字游戏:如何制作保存功能?)
问题描述
我正在使用 Python 制作基于文本的游戏,我已经大致了解了这一点.但我要让游戏深入到这样的程度,完成它需要的时间比坐下来要长.所以我希望能够让游戏在退出时将变量列表(玩家健康、金币、房间位置等)保存到文件中.然后如果玩家想要加载文件,他们就去加载菜单,它会加载文件.
I am in the process of making a text based game with Python, and I have the general idea down. But I am going to make the game in depth to the point where, it will take longer than one sitting to finish it. So I want to be able to make the game to where, on exit, it will save a list of variables (player health, gold, room place, etc) to a file. Then if the player wants to load the file, they go to the load menu, and it will load the file.
我目前使用的是 2.7.5 版的 Python,并且在 Windows 上.
I am currently using version 2.7.5 of Python, and am on Windows.
推荐答案
如果我正确理解了这个问题,那么您是在询问一种序列化对象的方法.最简单的方法是使用标准模块 pickle:
If I understand the question correctly, you are asking about a way to serialize objects. The easiest way is to use the standard module pickle:
import pickle
player = Player(...)
level_state = Level(...)
# saving
with open('savefile.dat', 'wb') as f:
pickle.dump([player, level_state], f, protocol=2)
# loading
with open('savefile.dat', 'rb') as f:
player, level_state = pickle.load(f)
可以通过这种方式存储标准 Python 对象和具有任何嵌套级别的简单类.如果您的类有一些重要的构造函数,则可能需要使用相应的 pickle 实际需要保存的内容.html#the-pickle-protocol" rel="noreferrer">协议.
Standard Python objects and simple classes with any level of nesting can be stored this way. If your classes have some nontrivial constructors it may be necessary to hint pickle at what actually needs saving by using the corresponding protocol.
这篇关于Python文字游戏:如何制作保存功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python文字游戏:如何制作保存功能?
基础教程推荐
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
