Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chess piece hierarchy design: inheritance vs type fields

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.

like image 309
joey_89 Avatar asked Dec 31 '10 13:12

joey_89


People also ask

How many types of chess pieces or designs?

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.

How many types of movable objects are there in a chess piece or Chessman?

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.

What is chess board design called?

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.


2 Answers

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...

like image 50
Nim Avatar answered Sep 22 '22 00:09

Nim


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 :).

like image 42
bcsanches Avatar answered Sep 20 '22 00:09

bcsanches