Loading

C++: Chess

Chess

In this C++ video tutorial, we present an implementation of the game of chess with an explanation. The code gives an example of polymorphism, where we override two pure virtual members functions to implement the specific behavior for each chess piece. The base of our class hierarchy is the piece class.

The piece class as two pure virtual functions: GetPiece() and AreSquaresLegal(). The function GetPiece() is overridden by each piece class to return the char that signifies each piece type: 'P' = pawn, 'N' = knight, 'R' = rook, 'B' = bishop, 'Q' = queen, and 'K' = king. The function AreSquaresLegal() is overridden to test the source and destination locations versus the movement rules for the particular piece.

For this video, we have simplified the rules of chess a little. We do not allow castling, en passant, double pawn moves, and pawn promotion. These simplifications help to make the code's use of polymorphism easier to understand. Moreover, the additional rules are easy enough to add in once you understand the simplified code.

The board is numbered on the left and bottom from 1 to 8 (as shown above) so that locations ca be specified as a two-digit number and moves can specified as a pair of two-digit numbers. The green squares show the legal moves for a knight. So, that 54 to 42 is a legal move and will return true if passed into the knight's AreSquaresLegal() function.

The main game board is an 8 by 8 array of pointers to piece objects. This is where the polymorphism comes in. Any square can hold any piece or none at all. If we want to know whether a piece can make a certain move, we just pass in the move to the IsLegalMove() function in the piece class. Then correct function is called for any of the pieces: pawn, knight, bishop, rook, queen, and king. However, all we know when the function is called is that it is a piece.

Of course, it is not entirely true that we cannot tell which piece is which, since we can use the GetPiece() function to find out our piece type at any time. However, we only need to the know the piece type when we are printing the board and when we are searching for the king to see if a player is in check. It would be easy enough to have the pieces print their type on the board using an override, but it is much harder to see if the player is in check without being able to tell which is the king. We found it much easier not to hide the data in this case, as data hiding offered no obvious advantage.