Tic-Tac-Toe game in Java
Below is a simple console-based Tic-Tac-Toe game in Java. Copy and paste this code into a Java file (e.g., TicTacToe.java) and run it.
import java.util.Scanner; public class TicTacToe { private static char[][] board = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}}; private static char currentPlayer = 'X'; public static void main(String[] args) { printBoard(); playGame(); } private static void playGame() { Scanner scanner = new Scanner(System.in); while (true) { System.out.println("Player " + currentPlayer + "'s turn."); System.out.print("Enter row (0-2): "); int row = scanner.nextInt(); System.out.print("Enter column (0-2): "); int col = scanner.nextInt(); if (isValidMove(row, col)) { board[row][col] = currentPlayer; printBoard(); if (checkWin()) { System.out.println("Player " + currentPlayer + " wins!"); break; } else if (isBoardFull()) { System.out.println("It's a draw!"); break; } switchPlayer(); } else { System.out.println("Invalid move. Try again."); } } scanner.close(); } private 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("\n-------------"); } } private static boolean isValidMove(int row, int col) { return row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == ' '; } private static void switchPlayer() { currentPlayer = (currentPlayer == 'X') ? 'O' : 'X'; } private static boolean checkWin() { // Check rows, columns, and diagonals return (checkRows() || checkColumns() || checkDiagonals()); } private static boolean checkRows() { for (int i = 0; i < 3; i++) { if (board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer) { return true; } } return false; } private static boolean checkColumns() { for (int i = 0; i < 3; i++) { if (board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer) { return true; } } return false; } private static boolean checkDiagonals() { return (board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer) || (board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer); } private 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; } }