import java.util.Scanner;
public class TicTacToe { static char[][] board = { {' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '} }; static char currentPlayer = 'X'; // Player X always starts
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean gameActive = true;
// Main game loop
while (gameActive) {
printBoard();
playerMove(scanner);
gameActive = !checkWinner(); // If there's a winner, break the loop
if (isBoardFull() && gameActive) {
System.out.println("It's a tie!");
gameActive = false;
}
if (gameActive) {
switchPlayer();
}
}
printBoard();
System.out.println("Game over.");
}
// Function to print the current board
public static void printBoard() {
System.out.println("-------------");
for (int i = 0; i < 3; i++) {
System.out.print("| ");
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j] + " | ");
}
System.out.println();
System.out.println("-------------");
}
}
// Function to handle player move
public static void playerMove(Scanner scanner) {
int row, col;
while (true) {
System.out.println("Player " + currentPlayer + ", enter your move (row and column): ");
row = scanner.nextInt() - 1;
col = scanner.nextInt() - 1;
if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == ' ') {
board[row][col] = currentPlayer;
break;
} else {
System.out.println("This move is not valid, please try again.");
}
}
}
// Function to check for a winner
public static boolean checkWinner() {
// Check rows and columns
for (int i = 0; i < 3; i++) {
if (board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer) {
System.out.println("Player " + currentPlayer + " wins!");
return true;
}
if (board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer) {
System.out.println("Player " + currentPlayer + " wins!");
return true;
}
}
// Check diagonals
if (board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer) {
System.out.println("Player " + currentPlayer + " wins!");
return true;
}
if (board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer) {
System.out.println("Player " + currentPlayer + " wins!");
return true;
}
return false;
}
// Function to check if the board is full (for a tie)
public static boolean isBoardFull() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == ' ') {
return false;
}
}
}
return true;
}
// Function to switch between players
public static void switchPlayer() {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
}