I prefer to avoid using pointers as you have to remember to clean them up.
This design uses the strategy pattern. The interface is PieceType
, which allows you to display valid positions on a board, or show the initial positions on the board. I'm sure there's more you would want each strategy to be able to do:
class Board;
class PieceType
{
public:
virtual showValidMoves(Board& board) const = 0;
virtual showInitialPosition(Board& board) const = 0;
// ...
};
class Pawn : public PieceType
{
public:
virtual showValidMoves(Board& board) const;
virtual showInitialPosition(Board& board) const;
// ...
};
class Rook : public PieceType
{
// ...
};
//...
We only need one of each PieceType
, and as that type is shared across chessmen, it can also be const:
const Pawn PAWN;
const Rook ROOK;
const Knight KNIGHT;
We use these strategies to initialise the Chessmen we keep in a vector:
class ChessMan
{
public:
enum Colour {Black, White};
ChessMan(const Colour& colour, PieceType& pieceType);
void showValidMoves(Board& board);
void showInitialPosition(Board& board);
private:
Colour m_colour;
PieceType& m_pieceType;
};
I'll wrap up the code for adding a ChessMan
to a vector in its own function:
void add(vector<ChessMan>& chessmen,
const ChessMan::Colour& colour,
const PieceType& pieceType,
const unsigned int amount)
{
chessmen.insert(chessmen.end(), ChessMan(colour, pieceType), amount);
}
void main()
{
using std::vector;
vector<ChessMan> chessmen;
add(chessmen, 16, ChessMan::Black, PAWN);
add(chessmen, 2, ChessMan::Black, ROOK);
add(chessmen, 2, ChessMan::Black, KNIGHT);
//...
}
Bonne chance!