I went in late in a project of gamedev of a simple text game in C++.I studied the project and I think I know how to do everything but i get stuck on a thing:how to save and load the game as proposed.I don't want to have the thing done for me,only you show me a way to do it.
6 回答
Well the simplest way I can think of is to have a structure/class which represents the whole games "state." And on save you simply write this entire structure from memory to disk. Loading would be the opposite.
What format it is on disk is entirely up to you, if your state consists entirely of simple data types, you may just want to write a binary blob. Or you might want to go with something more versatile such as serializing it to XML, it's really up to you.
我只是快速浏览了帖子,但这是我的建议:
您的游戏状态可能由几个结构和一些数据数组组成。这些结构将定义玩家(姓名、健康、金钱等)、武器(攻击、机会等)、盔甲等……
首先,您将通过保存玩家的结构来写入玩家的状态。接下来是玩家拥有的武器数量,然后是一系列武器结构,盔甲也是如此……
文件格式将是
STRUCT player
INT num_of_weapons
STRUCT weapon
STRUCT weapon
STRUCT weapon
INT num_of_armor
STRUCT armor
STRUCT armor
使用 fstream 可以轻松完成。
The process you are describing is known as "serialization"- that is, taking an in-memory object and converting it into some form that can be saved to disk. It could be as simple as a raw memory dump, or something complicated like XML.
I suggest taking a look at the wikipedia article on this subject: http://en.wikipedia.org/wiki/Serialization
我没有阅读您链接到的网站,但您可能想要编写读取/写入基本文本文件的代码以加载/保存您的游戏。
首先,弄清楚如何格式化文本文件。例如,如果我正在编写一个允许玩家保存游戏的 pacman 游戏,那么文本文件可能如下所示:
5
54700
3
我会编写我的代码来一次读取一行文件:
第 1 行:玩家所在的关卡。
第 2 行:玩家拥有的点数。
第 3 行:玩家拥有的生命数。
在 Google 上搜索 C++ 文件输入/输出,以了解如何编写实际代码。
这完全取决于您的保存文件的复杂程度。如果它只是几个整数,那么简单地编写几个函数可能很容易,这些函数会以指定的顺序将这些值写入文件,然后以与写入它们相同的顺序加载它们。如果它需要更复杂并处理保存多个对象的值而不是序列化是你最好的选择。如果您正在寻找人类可读的保存格式,我建议您使用 XML 序列化,否则您可能需要查找一些非人类可读的格式。