Implementing a Board Game in Java
First of all, I'm not sure if it's allowed to ask such a question. So I'm trying to build a board game and I'm stuck with the implementation of generating valid moves for Piece. Here is an excerpt from the class diagram.
You might think that this board game is similar to chess, so we need to know the location of the other pieces while creating valid moves. The problem is I have no idea how to check this. Is the class diagram wrong? Or should I check on the board every time I check a square? And how do I do it in Java? Thanks for the help.
source to share
The piece does not have to decide what its actual actions are, it only has to know where it is and how it is able to move. He is not responsible for such logic.
The board must control whether or not this is allowed (i.e. it takes a piece that returns its possible moves to it and, in turn, returns the actual moves).
The class Piece
provides a method getPossibleMoves
that returns a list of positions that it can reach:
public List<Square> getPossibleMoves(){ // might want to differentiate types of moves
Then the board class has a method getValidMoves
that takes a piece and returns its valid moves.
public List<Square> getValidMoves(Piece piece) {
return piece.getPossibleMoves().
stream(). // and filter by
filter(move -> isOnValidBoardCoordinate(move)). // can shorten
filter(move -> doesNotIntersectOtherPiece(move)).
filter(move -> otherValidation(move)).
collect(Collectors.toList());
}
source to share