Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I wrote a Chess engine in Java and I am porting it over to C++. I am new to C++.

ID: 658913 • Letter: I

Question

I wrote a Chess engine in Java and I am porting it over to C++. I am new to C++.

The idea:
I have a Board object which holds a 2-dimensionnal array of Piece objects. Queen, Rook, Bishop, etc are subclasses of Piece. They all have a method getPossibleMoves(). Therefore they need to have a reference to the board to be able to generate the possible moves.

The implementation:
Board class:

class Board
{
public:
    using PiecePtr = std::shared_ptr<Piece>;
    std::array<std::array<PiecePtr, BOARD_SIZE>, BOARD_SIZE> myPieces;
};
Piece class:

class Piece
{
public:
    std::weak_ptr<Board> myBoard
};
I used shared_ptr and weak_ptr because the Board can/should exist whitout Pieces. Is this approach correct?

Note: I know this OOP approch to represent the chess board is not the best for performance. Other approaches (Bitboards for instance) will be more efficient.

Explanation / Answer

This is a case of premature over-design.

The pieces don't need a pointer to the board. Just pass the board to the 'generateMoves' method. You don't even need objects for the individual chessmen. All pawns are alike, so you only need one Pawn instance.

Also, by the laws of chess, there is a game state that is also needed to correctly generate moves. Pawns can capture e.p. but only after a previous two-square advance. A king can castle with a rook but not if either has previously moved.

My suggestion is to forget all the class design stuff. Start with a single ChessGame class with two methods: generateMoves and makeMove. Write it test-first. Start by only having two kings on the board. Then add the different kinds of chessmen one at a time. Extract classes as you find it convenient.