Tic Tac Toe Game in Java

In this short tutorial, we will write a Java program to develop the Tic-Tac-Toe game. The Tic-Tac-Toe is a very common game that is fairly easy to play. The rules of the game are simple and well-known.
Learn Java at https://www.javaguides.net/p/java-tutorial-learn-java-programming.html
In this tutorial, we are going to develop the console-based Tic Tac Toe game. In this game, the user is prompted to choose one of the nine squares in the grid. The grid chosen by the player is then shown by the corresponding sign of the player. The first player marks A and second player marks B.

Tic-Tac-Toe Game in Java

package net.javaguides.springboot;

import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * Tic-Tac-Toe game in Java
 * @author https://www.javaguides.net/
 *
 */
public class TicTacToe {

    private static String[] board = new String[9];
    private static String turn = "A";

    public static void main(String[] args) {

        String winner = null;
        populateEmptyBoard();

        System.out.println("Welcome to 2 Player Tic Tac Toe.");
        System.out.println("--------------------------------");
        printBoard();
        System.out.println("A's will play first. Enter a slot number to place A in:");

        try (Scanner in = new Scanner(System.in)) {
            while (winner == null) {
                int numInput;
                try {
                    numInput = in .nextInt();
                    if (!(numInput > 0 && numInput <= 9)) {
                        System.out.println("Invalid input; re-enter slot number:");
                        continue;
                    }
                } catch (InputMismatchException e) {
                    System.out.println("Invalid input; re-enter slot number:");
                    continue;
                }
                if (board[numInput - 1].equals(String.valueOf(numInput))) {
                    board[numInput - 1] = turn;
                    if (turn.equals("A")) {
                        turn = "B";
                    } else {
                        turn = "A";
                    }
                    printBoard();
                    winner = checkWinner();
                } else {
                    System.out.println("Slot already taken; re-enter slot number:");
                    continue;
                }
            }
            if (winner.equalsIgnoreCase("draw")) {
                System.out.println("It's a draw! Thanks for playing.");
            } else {
                System.out.println("Congratulations! " + winner + "'s have won! Thanks for playing.");
            }
        }
    }

    static String checkWinner() {
        for (int a = 0; a < 8; a++) {
            String line = null;
            switch (a) {
                case 0:
                    line = board[0] + board[1] + board[2];
                    break;
                case 1:
                    line = board[3] + board[4] + board[5];
                    break;
                case 2:
                    line = board[6] + board[7] + board[8];
                    break;
                case 3:
                    line = board[0] + board[3] + board[6];
                    break;
                case 4:
                    line = board[1] + board[4] + board[7];
                    break;
                case 5:
                    line = board[2] + board[5] + board[8];
                    break;
                case 6:
                    line = board[0] + board[4] + board[8];
                    break;
                case 7:
                    line = board[2] + board[4] + board[6];
                    break;
            }
            if (line.equals("AAA")) {
                return "A";
            } else if (line.equals("BBB")) {
                return "B";
            }
        }

        for (int a = 0; a < 9; a++) {
            if (Arrays.asList(board).contains(String.valueOf(a + 1))) {
                break;
            } else if (a == 8)
                return "draw";
        }

        System.out.println(turn + "'s turn; enter a slot number to place " + turn + " in:");
        return null;
    }

    private static void printBoard() {
        String createBoard = "/---|---|---\\ \n" + "| " + board[0] + " | " + board[1] + " | " + board[2] + " | \n" +
            "|-----------| \n" + "| " + board[3] + " | " + board[4] + " | " + board[5] + " | \n" +
            "|-----------| \n" + "| " + board[6] + " | " + board[7] + " | " + board[8] + " | \n" +
            "/---|---|---\\ \n";
        System.out.println(createBoard);
    }

    private static void populateEmptyBoard() {
        for (int a = 0; a < 9; a++) {
            board[a] = String.valueOf(a + 1);
        }
    }
}
Output:
Welcome to 2 Player Tic Tac Toe.
--------------------------------
/---|---|---\ 
| 1 | 2 | 3 | 
|-----------| 
| 4 | 5 | 6 | 
|-----------| 
| 7 | 8 | 9 | 
/---|---|---\ 

A's will play first. Enter a slot number to place A in:
1
/---|---|---\ 
| A | 2 | 3 | 
|-----------| 
| 4 | 5 | 6 | 
|-----------| 
| 7 | 8 | 9 | 
/---|---|---\ 

B's turn; enter a slot number to place B in:
2
/---|---|---\ 
| A | B | 3 | 
|-----------| 
| 4 | 5 | 6 | 
|-----------| 
| 7 | 8 | 9 | 
/---|---|---\ 

A's turn; enter a slot number to place A in:
4
/---|---|---\ 
| A | B | 3 | 
|-----------| 
| A | 5 | 6 | 
|-----------| 
| 7 | 8 | 9 | 
/---|---|---\ 

B's turn; enter a slot number to place B in:
5
/---|---|---\ 
| A | B | 3 | 
|-----------| 
| A | B | 6 | 
|-----------| 
| 7 | 8 | 9 | 
/---|---|---\ 

A's turn; enter a slot number to place A in:
7
/---|---|---\ 
| A | B | 3 | 
|-----------| 
| A | B | 6 | 
|-----------| 
| A | 8 | 9 | 
/---|---|---\ 

Congratulations! A's have won! Thanks for playing.

Java programs

  1. Java Program to Count Number of Duplicate Words in String
  2. Java Program to Count Number of Words in Given String
  3. Java Program to Count the Number of Occurrences of Substring in a String
  4. Java Program to Count the Occurrences of Each Character in String
  5. Java Program to Merge two String Arrays  
  6. Java Program to Remove Duplicate Words from String 
  7. Java Program to Reverse a String(5 ways)
  8. Java Program to Reverse Each Word of a String    
  9. Java Program to Swap Two Strings      
  10. How to Check if the String Contains only Digits         
  11. How to Check if the String Contains only Letters  
  12. How to Check If the String Contains Only Letters or Digits 
  13. Java Program to Check if Input String is Palindrome 
  14. Java Program to Find all Permutations of String
  15. How to Remove or Trim All White Spaces from a String in Java
  16. How to Remove Leading and Trailing White Space From a String in Java
  17. Java Program to Count Duplicate Characters in a String
  18. Remove Character from String in Java (Java 8)
  19. Java Program to Count Vowels and Consonants in a String (Java 8)
  20. 4 Ways to Find First Non-Repeated Character in String in Java
  21. Java Program to Remove Duplicate Elements in an Array
  22. Java Program to Find Largest Element in an Array
  23. Java Program to Reverse an Array Without Using Another Array
  24. Java Program to Check the Equality of Two Arrays
  25. Java Program to Check Armstrong Number
  26. Java program to check prime number
  27. Java Program to Swap Two Numbers
  28. Java Program to Find Factorial of a Number
  29. Java Program to Reverse a Number
  30. Java Program to Swap Two Strings Without Using Third Variable

Comments