Help storing moves made in chess

Hiya! I've run into a problem with my chess program for class and Google is not providing the answers I need.

The chess program doesn't need to enforce any rules beyond whether or not there's actually a piece to move in a specified slot, so that's good, but in order to save the game, I'm supposed to store a list of moves. Here's an example file I was given:

a2a4 d7d5
a3a6 a7g6

The odd number moves are white moves, and the even number moves are black moves.

I cannot for the life of me figure out how to store the moves dynamically so that I can then store them in a file in this format and read them from a file to be used to set a board from a saved game. I think I need to use string class, but I can't think of how to differentiate between white and black moves and how to determine the size for my loops reading the data in and out of various files.
Any help is appreciated.
You could read from the file until you hit an EOF, and just have two arrays for the moves to be stored in. Here's an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <vector>
#include <iostream>
#include <string>

using MoveList = std::vector<std::string>;

void readMoves(const std::string& file, MoveList& white, MoveList& black) {
    std::ifstream in(file);
    std::string line;
    white.clear(); black.clear();

    while (in) {
        if (in >> line) white.push_back(line);
        if (in >> line) black.push_back(line);
    }
}

bool writeMoves(const std::string& file, MoveList& white, MoveList& black) {
    std::ofstream out(file);
    std::size_t i = 0;

    if (!(white.size() == black.size() || white.size() == black.size() + 1))
        return false; // or use an exception

    while (i < white.size() && i < black.size())
        out << white[i] << ' ' << black[i] << '\n';
    if (i < white.size())
        out << white[i];

    return true;
}

Then, you'll just need some code for transforming moves to and from strings. There are better ways of doing the reading / writing, but generally not as easy to understand. Also, I haven't tested that code, so I could well have made a silly mistake, but I'm sure you can work out what I'm suggesting from that snippet.
Last edited on
Topic archived. No new replies allowed.