I have a base class for pieces
class piece;
and an array containing derived objects
piece* board[8][8];
Advantage, clean design through virtual functions. Disadvantage, if I have to find a piece in the board or compare a piece I have to revert to dynamic casting (or typeid). It’s ugly and could be a performance hog when making millions of requests.
In the other hand, if I make an array of a single piece class, that has a type field for identifying pieces, I don’t have this problem (and it should be faster) but I have to make super ugly switch statements. I guess that since the number of pieces is finite and I don’t see myself making that many of switches, this could be in the end a better choice, what do you think?
This is for fun (so no bitboard).
Reading some answers, I think using type fields only for operator overloading (==
, !=
, ...) could bring the best of both words.
The boost::variant
looks very interesting too.
The six different types of pieces are: king, rook, bishop, queen, knight, and pawn. More than 500 different patterns of chess pieces have been recorded.
The chess pieces are what you move on a chessboard when playing a game of chess. There are six different types of chess pieces. Each side starts with 16 pieces: eight pawns, two bishops, two knights, two rooks, one queen, and one king.
The Staunton style was soon the standard on which most tournament playing pieces have been made and used around the world ever since. The low cost of the Staunton set allowed the masses to purchase sets and helped to popularize the game of chess.
Alternatively, if your set of classes is limited - i.e. you know the number, use a variant and visitors. For example, boost::variant<king, queen, bishop, knight ...>
And the board is made up of a 2D array of this type. Now to interrogate, you can use visitors...
I would go with the class hierarchy.
For finding a piece you can keep a separeted list for each piece type. So you know where to look for each piece type.
For comparison you can rely on virtual methods too.
Another aproach is to use a component architecture (like described here: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/), but I think it is too much for a chess game where you clealy know the types and know that those types will not change soon :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With