When checking if someone has won, I need to use IF several times. I would like to know if you can simplify the code a bit and even replace the IF s.
//left, top, right, bottom are int positions relative to canvas
//state is a enum{Blank,Red,Blue} which is used to determine if the square was clicked and who clicked it
private boolean checkHorizontalWin() {
for (Square s1 : squareList) {
if (s1.getState() != State.BLANK) {
for (Square s2 : squareList) {
if (s1 != s2) {
if (s1.getTop() == s2.getTop()) {
if (s1.getState() == s2.getState()) {
for (Square s3 : squareList) {
if (s1 != s3 && s2 != s3) {
if (s1.getTop() == s3.getTop()) {
if (s1.getState() == s3.getState()) {
return true;
} else break;
}
}
}
} else break;
}
}
}
}
} return false;
}
private boolean checkVerticalWin() {
for (Square s1 : squareList) {
if (s1.getState() != State.BLANK) {
for (Square s2 : squareList) {
if (s1 != s2) {
if (s1.getLeft() == s2.getLeft()) {
if (s1.getState() == s2.getState()) {
for (Square s3 : squareList) {
if (s1 != s3 && s2 != s3) {
if (s1.getLeft() == s3.getLeft()) {
if (s1.getState() == s3.getState()) {
return true;
} else break;
}
}
}
} else break;
}
}
}
}
} return false;
}
private boolean checkDiagonalWin() {
for (Square s1 : squareList) {
if (s1.getState() != State.BLANK) {
for (Square s2 : squareList) {
if (s1 != s2) {
if (s1.getBottom() != s2.getBottom()) {
if (s1.getRight() == s2.getLeft()) {
for (Square s3 : squareList) {
if (s1 != s3 && s2 != s3) {
if (s1.getBottom() != s3.getBottom() && s2.getBottom() != s3.getBottom()) {
if (s2.getRight() == s3.getLeft()){
if (s1.getState() == s2.getState() && s1.getState() == s3.getState()) {
return true;
} else break;
}
}
}
}
}
}
}
}
}
} return false;
}
squareList is created in a similar way as this:
private List<Square> squareList = new ArrayList<>();
private final int GRID_SIZE = 3;
private final int GRID_AREA = GRID_SIZE * GRID_SIZE;
private void createSquares() {
int x = 0;
int y = 0;
for (int i = 0; i < gridArea; i++) {
int left = field.getWidth() / 3 * x;
int top = field.getHeight() / 3 * y + field.getBorder();
int right = field.getWidth() / 3 * (x + 1);
int bottom = field.Height() / 3 * (y + 1) + field.getBorder();
squareList.add(new Square(left, top, right, bottom, State.BLANK));
x++;
if (x == GRID_SIZE) {
x = 0;
y++;
}
}
}
I'd rather not be Java 8 due to lack of compatibility with old APIs