Site icon

Develop Tic-Tac-Toe Game in Java (example)

What is Tic-Tac-Toe Game?

Tic-Tac-Toe is a classic paper-and-pencil game played between two players, typically called “X” and “O,” who take turns marking spaces in a 3×3 grid. The objective is to be the first to form a horizontal, vertical, or diagonal line of three of your marks.

Players take turns placing their symbol (“X” or “O”) in an empty cell of the grid, aiming to strategically create a row, column, or diagonal of their symbols while blocking their opponent from doing the same.

The game ends when one player successfully forms a line of three of their symbols or when all cells are filled without either player achieving a winning line, resulting in a draw. It’s a simple yet engaging game that often requires strategic thinking and anticipation of your opponent’s moves.

What is approach of Tic-Tac-Toe game?

  1. Board Representation:
    • Use a 3×3 grid represented by a 2D array or another suitable data structure.
    • Each cell in the grid can be empty (‘ ‘),
      • contain ‘X’ for player 1, or
      • ‘O’ for player 2.
  2. Displaying the Board:
    • Create a method to print the current state of the board to the console after every move.
    • Display the grid layout, updating it as players make their moves.
  3. Player Turns:
    • Design the game to allow two players to take turns, often represented by ‘X’ and ‘O’.
    • Accept player input for row and column positions to place their respective symbols on the board.
  4. Validating Moves:
    • Check if the chosen position is within the board boundaries and not already occupied before placing the symbol.
    • If the move is invalid, prompt the player to enter a new position.
  5. Checking for a Win:
    • After every move, check if the player who just made a move has won.
    • Check rows, columns, and diagonals for three consecutive symbols belonging to the same player.
  6. Checking for a Draw:
    • If there is no win and the board is full, declare a draw.
  7. Game Loop:
    • Enclose the game logic within a loop that continues until a player wins or the game ends in a draw.
  8. End of Game:
    • Display a congratulatory message to the winning player or announce a draw at the end of the game.
    • Allow players to restart the game if desired.

Implement tic-tac-toe game in Java

package org.example.games;

import java.util.Scanner;

public class TicTacToe {
    public static void main(String[] args) {
        char[][] board = {
                {' ', ' ', ' '},
                {' ', ' ', ' '},
                {' ', ' ', ' '}
        };
        char currentPlayer = 'X';
        boolean gameWon = false;

        Scanner scanner = new Scanner(System.in);

        System.out.println("Welcome to Tic-Tac-Toe!");

        while (!gameWon) {
            printBoard(board);
            System.out.println("Player " + currentPlayer + ", enter your move (row[1-3] column[1-3]): ");

            int row = scanner.nextInt() - 1;
            int col = scanner.nextInt() - 1;

            if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == ' ') {
                board[row][col] = currentPlayer;

                if (checkWin(board, currentPlayer)) {
                    gameWon = true;
                    printBoard(board);
                    System.out.println("Player " + currentPlayer + " wins!");
                } else if (isBoardFull(board)) {
                    gameWon = true;
                    printBoard(board);
                    System.out.println("It's a draw!");
                }

                currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
            } else {
                System.out.println("Invalid move. Try again.");
            }
        }

        scanner.close();
    }

    public static void printBoard(char[][] board) {
        for (int i = 0; i < 3; i++) {
            System.out.println(" " + board[i][0] + " | " + board[i][1] + " | " + board[i][2]);
            if (i < 2) {
                System.out.println("-----------");
            }
        }
    }

    public static boolean checkWin(char[][] board, char player) {
        for (int i = 0; i < 3; i++) {
            if ((board[i][0] == player && board[i][1] == player && board[i][2] == player) ||
                    (board[0][i] == player && board[1][i] == player && board[2][i] == player)) {
                return true;
            }
        }

        if ((board[0][0] == player && board[1][1] == player && board[2][2] == player) ||
                (board[0][2] == player && board[1][1] == player && board[2][0] == player)) {
            return true;
        }

        return false;
    }

    public static boolean isBoardFull(char[][] board) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == ' ') {
                    return false;
                }
            }
        }
        return true;
    }
}

Output: Tic-tac-toe game in java

Welcome to Tic-Tac-Toe!
   |   |  
-----------
   |   |  
-----------
   |   |  
Player X, enter your move (row[1-3] column[1-3]): 
1
3
   |   | X
-----------
   |   |  
-----------
   |   |  
Player O, enter your move (row[1-3] column[1-3]): 
3
1
   |   | X
-----------
   |   |  
-----------
 O |   |  
Player X, enter your move (row[1-3] column[1-3]): 
2
2
   |   | X
-----------
   | X |  
-----------
 O |   |  
Player O, enter your move (row[1-3] column[1-3]): 
3
2
   |   | X
-----------
   | X |  
-----------
 O | O |  
Player X, enter your move (row[1-3] column[1-3]): 
3
3
   |   | X
-----------
   | X |  
-----------
 O | O | X
Player O, enter your move (row[1-3] column[1-3]): 
1
1
 O |   | X
-----------
   | X |  
-----------
 O | O | X
Player X, enter your move (row[1-3] column[1-3]): 
2
3
 O |   | X
-----------
   | X | X
-----------
 O | O | X
Player X wins!
Exit mobile version