I have just finished building a Chess game in Java as an exercise. Whilst I am quite happy with the rest of the code, my castling move check code is lengthy and ugly and I want to see if there is a way to improve it.
There is a board class, which has a list of all pieces which are all unique classes extended from a single chessman class. This code is contained within the king class.
getOwner
returns an enum which has a value of 0 or 1 depending on the playercheckPosition
returns a boolean if there is a unit at the position or notdoMove
is the normal form of moving piecesgetUnit
retrieves a unit at a specified positiongetPossibleMoves
is every legal move a unit can make in the form of a point list
@Override
public boolean move(Point target){
int owner = super.getOwner().getValue() * 2;
List<Point> castlingMove = new ArrayList<>(Arrays.asList(new Point(3,1),new Point(7,1), new Point(3,8), new Point(7,8)));
List<Point> rooks = new ArrayList<>(Arrays.asList(new Point(1,1), new Point(8,1), new Point(1,8), new Point(8,8)));
Board b = super.getBoard();
if (castlingMove.contains(target) && !this.moved) {
boolean success = false;
if (target.equals(castlingMove.get(owner + 1)) && b.checkPosition(rooks.get(owner + 1))){ // Castling Short
success = checkRook(b, rooks, castlingMove, owner, 1);
} else if(target.equals(castlingMove.get(owner)) && b.checkPosition(rooks.get(owner))){ // Castling Long
success = checkRook(b, rooks, castlingMove, owner, 0);
}
if (success) this.moved = true;
return success;
} else {
boolean success = this.doMove(target);
if (success) this.moved = true;
return success;
}
}
private boolean checkRook(Board b, List<Point> rooks, List<Point> castlingMove, int owner, int moveType) {
Chessman u = b.getUnit(rooks.get(owner + moveType));
if (u instanceof Rook){
Rook r = (Rook) u;
if (!r.getMovedStatus()) {
boolean noCheck = true;
boolean freeSpace = true;
for (Chessman unit : b.getAllUnits()){
if (unit.getOwner() == super.getOwner()) continue;
Point[] t = {(Point) super.getPosition().clone(), (Point) r.getPosition().clone()};
int[] s = {5, 9};
Point m = t[moveType];
while (t[moveType].getX() < s[moveType]) {
if (unit.getPossibleMoves().contains(m)) noCheck = false;
m.translate(1, 0);
if (b.checkPosition(m) && m.x < s[moveType]) freeSpace = false;
}
}
if (noCheck && freeSpace) {
int[] p = {4,6};
super.setPosition(castlingMove.get(owner + moveType));
r.setPosition(new Point(p[moveType],super.getPosition().y));
return true;
}
}
}
return false;
}
If anyone needs more code, just say so. I didn't include the whole project because it is a large amount of code.