7
When checking if someone won, I need to use the IF several times. I wonder if there’s a way to simplify the code a little bit and maybe even replace the IFs.
//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 way similar to 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 prefer not to use Java 8 because of the lack of compatibility with old Apis
Like this
squareList
is built?– Victor Stafusa
What are the attributes Top, State, Left, Right and Bottom of Square?
– Marcel
squareList is a list of the 9 squares on the board and the attributes are their position relative to the canvas
– Eliton Machado da Silva
And how do you create the
squareList
? In which order the squares are inserted in that list?– Victor Stafusa
first line from left to right, then bottom line in the same order and then the last
– Eliton Machado da Silva