Python文字游戏:如何制作保存功能? [英] Python text game: how to make a save feature?

查看:39
本文介绍了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 对象和具有任何嵌套级别的简单类.如果您的类有一些重要的构造函数,则可能需要使用相应的 协议.

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文字游戏:如何制作保存功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆