I'm making chess in Java using Swing, and I have already figured out how to check legal moves for every piece. There is nothing wrong with that part. But now, I am having problems with checking whether a path is free. For example, all the pieces in chess cannot jump over a piece unless it's a knight. If a pawn is blocking a bishop's path, it cannot go over than pawn. I called the method that checks whether a path is free isVectorFree()
. It's working fine for horizontal and vertical paths but it's not working properly for diagonal paths.
Here is the code for isVectorFree()
:
public boolean isVectorFree(int x1, int y1, int x2, int y2) {
if (x1 == x2 && y1 > y2) { // horizontal north
for (int i = y1 - 1; i > y2; i--) {
if (piecePositions[i][x1] != null) {
return false;
}
}
} else if (x1 < x2 && y1 == y2) { // horizontal east
for (int i = x1 + 1; i < x2; i++) {
if (piecePositions[y1][i] != null) {
return false;
}
}
} else if (x1 == x2 && y1 < y2) { // horizontal south
for (int i = y1 + 1; i < y2; i++) {
if (piecePositions[i][x1] != null) {
return false;
}
}
} else if (x1 > x2 && y1 == y2) { // horizontal west
for (int i = x1 - 1; i > x2; i--) {
if (piecePositions[y1][i] != null) {
return false;
}
}
}
else if (x1 < x2 && y1 > y2) { // diagonal northeast
// these diagonals aren't working properly
for (int row = x1 + 1; row < x2; row++) {
for (int col = y1 - 1; col >= y2; col--) {
if (piecePositions[row][col] != null) {
return false;
}
}
}
} else if (x1 < x2 && y1 < y2) { // diagonal southeast
for (int row = x1 + 1; row < x2; row++) {
for (int col = y1 + 1; col < y2; col++) {
if (piecePositions[row][col] != null) {
return false;
}
}
}
} else if (x1 > x2 && y1 < y2) { // diagonal southwest
for (int row = x1 - 1; row >= x2; row--) {
for (int col = y1 + 1; col < y2; col++) {
if (piecePositions[row][col] != null) {
return false;
}
}
}
} else if (x1 > x2 && y1 > y2) { // diagonal northwest
for (int row = x1 - 1; row >= x2; row--) {
for (int col = y1 - 1; col >= y2; col--) {
if (piecePositions[row][col] != null) {
return false;
}
}
}
}
return true;
}
This method takes the piece's x coordinate x1
and y coordinate y1
in the matrix piecePositions
and the desired x coordinate x2
and desired y coordinate y2
in order to see if the path between the current coordinates and desired coordinates is free, but as I said earlier, this isn't working properly for the diagonals. Specifically, isVectorFree()
is being affected by surrounding pieces. In the starting position of the chess board, if I move the pawns away to make way for the bishop, even if the path is now free for the bishop, it still cannot move anywhere throughout the path, for some reason.
How can I fix this?