Search code examples
c++consolesaverestart

C++ console Save and load saved "games"


I have a grid of randomly generated numbers of size gameSizexgameSize (user input) which is contained within a vector of vectors. The user can enter two co-ordinates (x, y) so that it changes a number within the grid to a predefined value.

So for example the user enters, X:0 Y:0 and:

{9, 7, 9}

{9, 6, 8}

{5, 1, 4}

becomes:

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

{9, 6, 8} 

{5, 1, 4}

I'm trying to figure out how to make it so the user can save the current board state and access it later on. I understand I need to somehow save the game (myGame) to a file, that way I can access it and load it into the console application again, essentially saving and restarting saved games, but I have no clue where to begin.


Solution

  • You can use fstream from standard library and add special methods to your game class, here is working example:

    #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;
    }
    

    Don't forget to store game size in file for convinience of reading. It is good to add size property to your class and have another constructor if you want to load already stored game. Also it would be better if you add some checks that file is in appropriate format. You can add all you logic of making turns into Game class as methods if they are not there already. Good luck!