I'm writing a basic Java chess game and have written the following classes: Game, Player, Board, Square, Piece (superclass of each of the specific pieces), and each specific piece class (e.g. Pawn, Knight, Bishop, etc.)
One of the trickier methods is figuring out whether a move is valid based on whether it results in the moving player being in check. My solution is as follows:
- clone current Board
- make move
- see if moving player is in check
- if so, disallow move; else, allow move
I'm taking my cues on how to clone from here: http://www.jusfortechies.com/java/core-java/cloning.php
Now, the board object consists of a 2d array of Square objects. Each square object has a piece field which is either null (no piece on it) or refers to a piece object (has a piece on it). The board object also has a whiteKingSquare and a blackKingSquare (both are Square objects) to make locating the white king or black king faster / easier.
I've written the following method within my Board class:
public Object clone() throws CloneNotSupportedException {
Board clonedBoard = (Board) super.clone();
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
clonedBoard.myBoard[i][j] = new Square(this, i, j);
clonedBoard.whiteKingSquare = myBoard[7][4];
clonedBoard.blackKingSquare = myBoard[0][4];
}
}
return clonedBoard;
}
However, because Board refers to an 8 x 8 array of Square objects, I have to clone each of these. I've written this method within the Square class:
public Object clone() throws CloneNotSupportedException {
return (Square) super.clone();
}
Finally, I've written this method in the Piece class:
public Object clone() throws CloneNotSupportedException {
return (Piece) super.clone();
}
Onto the questions:
- Does this look roughly right?
- My Square objects also have a Board field which basically lets me reference the board they belong to. Will this mess with my attempt to clone by having each of my 64 squares clone the board separately?