Background: I am making a chess game. It works almost completely, just missing the check for checkmate, but I am refining some code for readability, etc.
Right now, I am recoding a method I had to check the path from any piece, to another location on the board. It returns true if there is a piece blocking the path and false if there is not one.
Note: I do not need to check the spot of the last location because my game will check to make sure that you do not occupy the spot you are trying to move to.
Also note that I have researched this question and I have found that the consensus, mainly on here, is that breaking is the correct solution. This is preferred over having a boolean variable initialized outside the loop and set true or false and breaking the loop on that value. However, I have two conditions in my loop that may make my code return true or return false so I can't do that completely.
Current Code
public boolean isPathClear(Location l1, Location l2) {
int atx = l1.getX();
int aty = l1.getY();
int xdiff = 0, ydiff = 0;
int endx = l2.getX(), endy = l2.getY();
if(l1.getX() > l2.getX()) {
xdiff = 1;
}
if(l1.getX() < l2.getX()) {
xdiff = -1;
}
if(l1.getY() > l2.getY()) {
ydiff = 1;
}
if(l1.getY() < l2.getY()) {
ydiff = -1;
}
while(true) {
atx += xdiff;
aty += ydiff;
if(atx == endx && aty == endy) {
return true
}
if(board[atx][aty].getType() != ' ') {
return false;
}
}
Problem: Since breaking is the preferred method, that is what I planned to do. But, I came into a problem, if I use break in one of the if statements, it looks like I have to return in the other. Like:
while(true) {
atx += xdiff;
aty += ydiff;
if(atx == endx && aty == endy) {
break;
}
if(board[atx][aty].getType() != ' ') {
return false;
}
}
return true;
Question: This seems like a sort of mix that could be confusing. So with my situation, would this still be the preferred method over this code:
boolean clear;
while(true) {
atx += xdiff;
aty += ydiff;
if(atx == endx && aty == endy) {
clear = true;
break;
}
if(board[atx][aty].getType() != ' ') {
clear = false;
break;
}
}
return clear;