I'm building a chess game, and I encounterred a problem when I'm checking to see if the NEXT move is valid:
the problematic case is when a player "checked" his opponent,
therefore the opponents next move is obligated to be a move that protects the king,
the way I do it is by cloning the board, making the move of the "checked" opponent, checking if his king is still "checked", and if its so, I ask the opponent to enter a different move.
the problem surprisingly occurs when the move protects the king,
when that happens, for some reason the "future board" (the clone I was doing the check on) is not cloned properly and there are changes made to the original board, I have failed to find the bug yet, maybe I'm not well aware of the clone() method,
here are the code snippets needed:
// board is the original board, futureBoard is the one I'm testing
// the next move on.
// inside class Board I have:
// theBoard - 8 on 8 objects named Square
// thePieces - a list of objects named Piece - the are the pieces on the board
// whiteKing, blackKing - Piece type, a referance to the location of the kings
// this functions creates the clone of board - futureBoard
static void cloneToFutureBoard(Board board)
futureBoard = new Board();
futureBoard.initializeBoard(); //method inside Board that creates the board
futureBoard.theBoard = board.theBoard.clone();
futureBoard.thePieces = new Piece[board.thePieces.length];
futureBoard.thePieces = board.thePieces.clone();
Col tempBlackCol = board.blackKing.getCol();
int blackRow = board.blackKing.getRow();
int blackIntCol = colToInt(tempBlackCol);
futureBoard.blackKing = futureBoard.theBoard[blackRow][blackIntCol].getPiece();
Col tempWhiteCol = board.whiteKing.getCol();
int whiteRow = board.whiteKing.getRow();
int whiteIntCol = colToInt(tempWhiteCol);
futureBoard.whiteKing = futureBoard.theBoard[whiteRow][whiteIntCol].getPiece();
// the next code snippet is from the flow of the game:
// check is a boolean thats true when the king is "checked"
if (futureBoard.getTheBoard()[newRow][intNewCol].getPiece() != null)
futureBoard.thePieces = removePiece(futureBoard.thePieces, newCol, newRow);
System.out.println("You are Checked!");
System.out.println("Check is Over");
check = false;
if (board.getTheBoard()[newRow][intNewCol].getPiece() != null)
board.thePieces = removePiece(board.thePieces, newCol, newRow);
the final if is supposed to come out false because I move the king to an empty spot, instead (after trying to debug) I found out the king has already moved to the new spot, so what happens is that the original spot is empty, and the new spot is full! but because a piece is moving there, it removes this piece, so actually, the king is taking himself!
I dont understand why messing around with the clone changes the original board,
is there anything wrong with my cloning method?