I am trying to design online chess game(figuring out required classes). Need some suggestion on choosing better option to validate the move. So, lets say, I have below class
Option 1 : My Initial thought process was to have a validator Factory defined, and set of validators specific to each piece.
Public class Game{
private String id;
private Player player1;
private Player player2;
private GameStatus status;
private Board board;
private Color currentTurn ; //who have to make move now?
private static Map<PieceType , List<IValidate>> validators;
static {
validators = initialize_the_appropriate_validators
}
public boolean makeMove(Move move){
PieceType type = move.getPiece().getType() ;
for(Ivalidate validator : validators.get(type)){
if(!validator.validate())
throw new InvalidMoveException("Move not allowed!");
}
.............
}
}
public class KnightMovesValidator implements Ivalidate{
public boolean validate(Move){
//TODO: vlidate if it is proper move based on the piece
}
}
public class Box{
private int x ;
private int y ;
private Piece piece;
}
public Board{
private Box [][] boxes;
}
public class Move{
private Box src;
private Box dest;
private Piece piece;
private Player player;
}
public enum PieceType{
KINGHT , ROOK , KING , QUEEN .......
}
public enum color{
BLACK,WHITE
}
public class Piece{
private PieceType type;
private Color color;
private boolean isKilled;
}
Option 2 : When I searched on the internet to validate my implementation. I found the below design in many places.
Public Knight extends Piece{
public boolean canMove(Box src , Box dest) {
//TODO : implement
}
}
The idea is, instead of having external validator. Each piece is saying whether the requested move is possible or not. It sounds better than my design to me. But still I have some question here... Box is aware of the class Piece because it is holding it.
Should Piece be aware of Box(its location) ?? Shouldn't piece be independent of Box?
Is this correct way of designing our POJO? What is the thought process behind it? Please throw me some light.
Thanks.
AddMove
would be perfectly fine in theGame
class, and validating that move isn't wrong either as a last line of defense against bad input. – Flater Apr 11 '20 at 14:07