C++ 控制台保存并加载已保存 "games"

C++ console Save and load saved "games"

我有一个随机生成的数字网格,大小为 gameSizexgameSize(用户输入),包含在一个向量向量中。用户可以输入两个坐标 (x, y),以便将网格内的数字更改为预定义值。

因此,例如用户输入 X:0 Y:0 和:

{9, 7, 9}

{9, 6, 8}

{5, 1, 4}

变成:

{0, 7, 9} <-- Changes position 0,0 to 0 (the predefined value)

{9, 6, 8} 

{5, 1, 4}

我正在尝试弄清楚如何制作它,以便用户可以保存当前的面板状态并在以后访问它。我知道我需要以某种方式将游戏 (myGame) 保存到一个文件中,这样我就可以访问它并将其再次加载到控制台应用程序中,本质上是保存并重新启动保存的游戏,但我不知道从哪里开始。

您可以使用标准库中的 fstream 并向您的游戏添加特殊方法 class,这里是工作示例:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Game
{
public:
    Game(int gameSize) : size(gameSize), field(size, vector<int>(size))
    {
        //Randomize(); //generate random numbers
//just filling example for test
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                field[i][j] = i * size + j;
            }
        }
    }

    Game(string filename) {
        Load(filename);
    }

    void Load(string filename) {
        fstream in;
        in.open(filename, fstream::in);
        in >> size;
        field.resize(size, vector<int>(size));
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                in >> field[i][j];
            }
        }
        in.close();
    }

    void Save(string filename) {
        fstream out;
        out.open(filename, fstream::out);
        out << size << endl;
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                out << field[i][j] << " ";
            }
            out << endl; //for user friendly look of file
        }
        out.close();
    }

private:
    int size;
    vector<vector<int>> field;
};

int main() {
    Game game(3);
    game.Save("game.txt");
    game.Load("game.txt");
    game.Save("game2.txt");

    return 0;
}

不要忘记将游戏大小存储在文件中以方便阅读。如果您想加载已存储的游戏,最好将大小 属性 添加到您的 class 并使用另一个构造函数。如果您添加一些检查文件是否采用适当的格式,那会更好。 如果它们不存在,您可以将所有制作逻辑添加到 Game class 中作为方法。祝你好运!

首先,您应该阅读有关 CSV 格式的内容。要求用户为您的游戏设置一个名称,然后将数组保存到这样的文件中:
- 每行 1 次保存。
- 行以保存名称
开头 - 接下来的两个值代表尺寸 X 和尺寸 Y。
- 直到行尾的下一个值表示数组数据。
加载存档游戏执行如下:
- 向用户显示可用保存列表
- 打算加载保存的用户输入
- 应用程序像这样加载数据:在文件中搜索包含它打算加载的名称的行,读取大小 x 和大小 y 以初始化该大小的数组,将内容加载到数组中。

逐行保存,每行一行:

void Game::save(std::istream& s)
{
    for (const auto& row: myGame)
    {
        for (auto cell: row)
        {
            s << cell << ' ';
        }
        s << '\n';
    }
}

然后逐行回读并边读边创建行:

void Game::load(std::istream& s)
{
    myGame.clear();
    std::string line;
    while (std::getline(s, line))
    {
        std::istringstream cells(line);
        std::vector<int> row;
        int cell = 0;
        while (cells >> cell)
        {
            row.push_back(cell);
        }
        myGame.push_back(row);
    }
}

将行分隔成行意味着您不需要跟踪长度。
使用 istream&ostream& 参数意味着您不仅可以使用文件,还可以使用任何流,例如 stringstreamcincout
后者可以在调试时派上用场。