jzbakos - 2 months ago 10

Java Question

I am a beginner java programmer and I am making a simple TicTacToe game using 2D arrays and these are my if statements to check if player 1, or player 2 has won. I believe that this can be simplified by using for loop(s) however I do not understand how to use that method.

`if ((grid[0][0] == 1 && grid[0][1] == 1 && grid[0][2] == 1)`

|| (grid[1][0] == 1 && grid[1][1] == 1 && grid[1][2] == 1)

|| (grid[2][0] == 1 && grid[2][1] == 1 && grid[2][2] == 1)

|| (grid[0][0] == 1 && grid[1][1] == 1 && grid[2][2] == 1)

|| (grid[0][2] == 1 && grid[1][1] == 1 && grid[2][0] == 1)

|| (grid[0][0] == 1 && grid[1][0] == 1 && grid[2][0] == 1)

|| (grid[0][1] == 1 && grid[1][1] == 1 && grid[2][1] == 1)

|| (grid[0][2] == 1 && grid[1][2] == 1 && grid[2][2] == 1)

&& won == false) {

title.setText("X wins!");

won = true;

} else if ((grid[0][0] == 2 && grid[0][1] == 2 && grid[0][2] == 2)

|| (grid[1][0] == 2 && grid[1][1] == 2 && grid[1][2] == 2)

|| (grid[2][0] == 2 && grid[2][1] == 2 && grid[2][2] == 2)

|| (grid[0][0] == 2 && grid[1][1] == 2 && grid[2][2] == 2)

|| (grid[0][2] == 2 && grid[1][1] == 2 && grid[2][0] == 2)

|| (grid[0][0] == 2 && grid[1][0] == 2 && grid[2][0] == 2)

|| (grid[0][1] == 2 && grid[1][1] == 2 && grid[2][1] == 2)

|| (grid[0][2] == 2 && grid[1][2] == 2 && grid[2][2] == 2)

&& won == false) {

title.setText("O wins!");

won = true;

}

Below is the modified code that uses far less if statments and conditions.

`public static boolean hasWon(int[][] grid) {`

for (int a = 1; a <= 2; a++) {

for (int b = 0; b < grid.length; b++) {

// Checking for win in horizontal, then vertical, then diagonal

if (grid[b][0] == a && grid[b][1] == a && grid[b][2] == a) {

won = true;

} else if (grid[0][b] == a && grid[1][b] == a && grid[2][b] == a) {

won = true;

} else if ((grid[0][0] == a && grid[1][1] == a && grid[2][2] == a

|| (grid[0][2] == a && grid[1][1] == a && grid[2][0] == a))) {

won = true;

}

}

}

}

Answer

In order to help you reach a solution on your own I'll give you some hints for now.

Hint #1: Think about what it means to win. A player must get 3 of their tokens in a row - horizontal, vertical, or diagonal. Think about how that can be represented in your program.

Hint #2: Think about how you can break the problem into smaller more manageable pieces. Think about what each winning scenario has in common and separate that logic into a method that you can call multiple times.

Hint #3: Consider what makes each winning scenario unique and how you might use your `grid`

to produce a representation of the spaces you want to examine that is easier to check for a win.

If you're not sure about how for loops work or other aspects of the Java Language you can find tutorials on Oracle's site