I am a beginner android "developer" developing a chess app.
There is one variable in the InGameActivity
class called currentBoardState
which is public static
. Every ChessPiece
has a boolean[][] possibleMoves
. This following method will take the possibleMoves
and determine if any of the moves will cause the player to put him/herself in check and set it to false because it is no longer a possible move.
@Override
public void eliminateMovesThatPutYouInCheck() {
ChessPiece[][] originalBoard = InGameActivity.currentBoardState;
final ChessPiece emptyPiece = new EmptyPiece(Color.EMPTY);
final ChessPiece tempKnight = new Knight(side);
//This block eliminates moves that will cause a player
//to put him/her self in check.
InGameActivity.currentBoardState[x][y] = emptyPiece;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (possibleMoves[i][j] == true) {
tempKnight.x = i;
tempKnight.y = j;
InGameActivity.currentBoardState[i][j] = tempKnight;
if (InGameActivity.isPlayerInCheck(side)) {
possibleMoves[i][j] = false;
}
InGameActivity.currentBoardState[i][j] = emptyPiece;
}
}
}
InGameActivity.currentBoardState = originalBoard;
}
The problem is, my currentBoardState
variable is being messed up and I dont know why, ive saved the value then reset it at the end of the method why is it losing its values?
EDIT: Here is the isPlayerInCheck
method if you need it, thank you.
public static boolean isPlayerInCheck(Color side) {
List<boolean[][]> opponentsMoves = new ArrayList<boolean[][]>();
int xKing = -1;
int yKing = -1;
if (side.equals(Color.WHITE)) {
xKing = whiteKing.x;
yKing = whiteKing.y;
} else {
xKing = blackKing.x;
yKing = blackKing.y;
}
if (side.equals(Color.WHITE)) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (currentBoardState[i][j].isBlack()) {
opponentsMoves.add(currentBoardState[i][j].possibleMoves);
}
}
}
for (boolean[][] b : opponentsMoves) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (b[xKing][yKing] == true) {
return true;
}
}
}
}
return false;
} else {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (currentBoardState[i][j].isWhite()) {
opponentsMoves.add(currentBoardState[i][j].possibleMoves);
}
if (currentBoardState[i][j].isBlack() && currentBoardState[i][j].getType().equals(Type.KING)) {
xKing = currentBoardState[i][j].x;
yKing = currentBoardState[i][j].y;
}
}
}
for (boolean[][] b : opponentsMoves) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (b[xKing][yKing] == true) {
return true;
}
}
}
}
return false;
}
}
Also, I understand and appreciate that my code is probably very inefficient and the design is horrible for chess but that isn't really what I am concerned about at the moment.