I am attempting to make a chess game from scratch and made significant progress over the past couple of months. However, I recently got stuck on a problem that I just cannot figure out how to solve.
CODE (UPDATED)
Since the source code is too large to post here, I think it is best to leave a link to my GitHub account where it can be found: https://github.com/lbragile/chessCAMO
DESCRIPTION
Chess
Contains relevant game flags and turn tracking, as well as keeps a stack of the board positions to allow a player to undo moves.
Piece
Contains the piece's:
- square ([0,63])
- move information (for castling and initial pawn moves)
- type
- color
Piece Type classes
Includes:
- Pawn
- Knight
- Bishop
- Rook
- Queen
- King
- Empty (for blank squares)
These inherit from the base class (Piece)
QUESTION
With this set up, Chess and Piece are separate classes (one is not derived from the other). However, to keep track of the board positions in a stack, the Chess class uses the member variable:
stack<vector<Piece*>> board_positions;
This does in fact allow me to undo the position and even make moves afterwards. However, after running my algorithm through my test cases, I noticed that it fails the cases involving flags for check, double check, checkmate, and stalemate. When I checked with my GUI, this was confirmed. For example, making a move which causes a check, then "undoing" that move, and repeating the move again. This fails since the check flag of the previous position is not stored.
This leads to the obvious conclusion that I must store the entire Chess object at each move so that I get both the board representation and the corresponding necessary flags. I just cannot figure out how to have a member variable in the class Chess that can store Chess objects in a stack. The main reason is that Chess itself contains Piece objects in it which are polymorphic (virtual functions) and the two classes are separate.
Any suggestions or helpful tips as to how to proceed would be much appreciated.
EDIT #1
I updated the code using the suggestions provided. However, my current problem is that the board flags do not seem to update on the stack. This seems to stem from the ~Chess()
. I think it is not actually destroying the object pointers but rather simply popping them. I attempted using std::move()
to move the resources in makeMove(int src, int dest, istream &in)
from temp_chess
in the pushInfo()
function of the if statement and deleting the game_info
pointer in the destructor, however this doesn't seem to fix the issue.
EDIT #2
See my answer below, I solved the problem using serialization/de-serialization of the Chess
object.