I'm writing a chess game. My basic design is to have a 2d array (8 x 8) consisting of square objects. Squares have a number of fields: int height, int width, Piece piece (null if empty, some type of Piece object otherwise.
NB: Rook, Knight, Bishop, etc. all extend Piece.
Now, I'm getting a little tripped up on how to figure out what moves are legal for a given piece, given my OOP design. Here's what I'm thinking:
1) User clicks square 2) We determine what piece is on square (if empty, return error message) 3) Generate legal moves for that piece on that square
I'm worried about writing code like:
if (clickedSquare.piece.instanceOf(Rook)) {
return Rook.getLegalDestinationSquares(clickedSquare);
} else if (clickedSquare.piece.instanceOf(Bishop)) {
return Bishop.getLegalDestinationSquares(clickedSquare);
} else if...
Which seems really bad. There must be a way to do this that conforms better to OOP but I'm still learning.
Thanks for the help, Mariogs
You don't need to create that if statement. Just get the current piece on the field and call some method like (getLegalMoves()) or something. If field is empty - return empty list of allowed moves.
public abstract class Piece {
public abstract List<Field> getFieldsAllowed(Field field);
}
public class Rook extends Piece {
@Override
public List<Field> getFieldsAllowed(Field field) {
// TODO Auto-generated method stub
return null;
}
}
public class Field {
public Piece getPiece() {
// get current piece
}
}
Something like this. Try to find your own solution. This one is not perfect.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments