I'm trying to write a chess program for one of my classes. Data encapsulation has been a serious challenge of mine. The problem is that I want the moves to be a part of my pieces class. However, I'm not sure what would be a good way to do this. This is my piece structure.
Class Board
which has a
Class Checkers
which has a
Class Piece
The problem is that in order for the piece to move, while following chess logic, it has to be aware of its position on the board. Therefore, I can't put a piece.move() function on the board very easily or without creating co-dependency. This makes it hard for me to know what to do.
So What if I did this?
What if I made a "move" class. Each piece object would have an object of the class "move" within it. This "move" class would have functions that allow me to move the piece and it would destroy the co-dependency between the checkers and the pieces. It would look like this.
By the way, each class is stored in a different header file. I'm not sure if that's relevant.
// My main class
class Board {
private:
Checkers checkers[8][8];
}
// The checkers class looks like this
class Checkers {
private:
Piece * piece;
}
// Piece class looks like this
class Piece {
private:
char type;
Move move;
}
class Move {
public:
void Move(Checkers); // Checkers would use a getPiece function so I
// access the pieces without relying on using
// directly using piece as a parameter.
void isValidMove(Checkers); //checks validity, needs to know board to do.
}
You are right in having a move class, but each piece shouldn't have it's own move object. The Move class should be the one that moves any piece that needs to be moved including any logic that goes with that. Then the move class will inform the board that a piece has been moved, then the board can either update a view (if this is a gui) and/or the board will simply check other things like if a winner is evident, etc.
Also if you think about it, there is no need to make Checkers and Piece two different things. Checkers could be an abstract class which Piece inherits from. Polymorphism ftw