I designed a TicTacToe console game, and I’m trying to figure out how to check if somebody has one. My current code for the game is below.
package tictactoe;
import java.util.Scanner;
public class TicTacToe {
private String[][] board = new String[3][3];
private String turn = "O";
private int turns = 0;
public void gameLoop() {
for (int y = 0; y < 3; y++) {
board[y][0] = " ";
board[y][1] = " ";
board[y][2] = " ";
for (int x = 0; x < 3; x++) {
board[0][x] = " ";
board[1][x] = " ";
board[2][x] = " ";
}
}
while (true) {
try {
Scanner scan = new Scanner(System.in);
System.out.println(" | | ");
System.out.println(" " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " ");
System.out.println("______|______|______");
System.out.println(" | | ");
System.out.println(" " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " ");
System.out.println("______|______|______");
System.out.println(" | | ");
System.out.println(" " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " ");
System.out.println(" | | ");
if (turns != 9) {
if (scan.hasNextInt()) {
int input = scan.nextInt();
if (!board[input/3][input%3].equals(" ")) {
System.out.println("Place already taken.");
} else {
board[input/3][input%3] = turn;
turn();
}
}
} else if (turns == 9) {
System.out.println(checkWin());
System.exit(0);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public String turn() {
if (turn == "O") {
setTurns(getTurns() + 1);
return turn = "X";
}
setTurns(getTurns() + 1);
return turn = "O";
}
public String checkWin() {
}
public int getTurns() {
return turns;
}
public void setTurns(int turns) {
this.turns = turns;
}
}
I’m not sure how to check for the win, all I know is that I will need to loop through the board array to check if there is 3 in a row horizontally, vertically or diagonally.
~Shazer2