Code Pumpkin

Tic Tac Toe | Java Program Implementation

March 31, 2017
Posted by Abhi Andhariya

Tic Tac Toe

Tic Tac Toe (also known as Noughts and crosses or Xs and Os) is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row wins the game.

If you are interested in java programs for other board games like Sudoku SolverSudoku CheckerSnake N Lader and N Queen Problem, you can check out my posts in Board Games section.

How to implement Tic Tac Toe using JAVA ?

The basic idea is to use a two-dimensional array, board, to maintain the game board. Cells in this array store values that indicate if that cell is empty or stores an X or O.

TicTacToe Java Implementation

Board is a three-by-three matrix, whose middle row consists of the cells board[1][0], board[1][1], and board[1][2].

Figure shows an illustration of a Tic Tac Toe board and the two-dimensional integer array, board, representing it.

In our case, we choose to make the cells in the board array be integers, with a 0 indicating an empty cell, a 1 indicating an X, and -1 indicating an O.

This encoding allows us to have a simple way of testing if a given board configuration is a win for X or O, namely, if the values of a row, column, or diagonal add up to 3 or -3, respectively.

Below Java class is for maintaining a Tic Tac Toe board for two players

Note that this code is just for maintaining the Tic Tac Toe board and registering moves. It doesn't perform any strategy or allow someone to play Tic Tac Toe against the computer.


import java.util.Scanner;
 
public class TicTacToeTest{
 
    public static void main(String[ ] args) {
         
        TicTacToe t = new TicTacToe();
        Scanner s = new Scanner(System.in);
        int x=0,y=0;
        do
        {
            System.out.println(t.player==t.X?"Player X turn":"Player O turn");
            System.out.println("Enter x and y places");
            x=s.nextInt();
            y=s.nextInt();
             
            t.putSign(x, y);
            System.out.println(t.toString());
            System.out.println("_____________________________");
            t.displayWinner();
             
        }while(t.isEmpty);
    }
}
 
class TicTacToe
{
    public static final int X = 1, O = -1;
    public static final int EMPTY = 0;
     
    public int player = X;
    private int[][] board = new int[3][3];
    public boolean isEmpty = false;
     
    /** Puts an X or O mark at position i,j. */
    public void putSign(int x, int y)
    {
        if(x<0 || x>2 || y<0 || y>2)
        {
            System.out.println("Invalid board position");
            return;
        }
        if(board[x][y] != EMPTY)
        {
            System.out.println("Board position occupied");
            return;
        }
        board[x][y] = player;   // place the mark for the current player
        player = -player;       // switch players (uses fact that O = - X)
    }
     
    /** Checks whether the board configuration is a win for the given player. */
    public boolean isWin(int player)
    {
        return ((board[0][0] + board[0][1] + board[0][2] == player*3) ||
                (board[1][0] + board[1][1] + board[1][2] == player*3) ||
                (board[2][0] + board[2][1] + board[2][2] == player*3) ||
                (board[0][0] + board[1][0] + board[2][0] == player*3) ||
                (board[0][1] + board[1][1] + board[2][1] == player*3) ||
                (board[0][2] + board[1][2] + board[2][2] == player*3) ||
                (board[0][0] + board[1][1] + board[2][2] == player*3) ||
                (board[2][0] + board[1][1] + board[0][2] == player*3));
    }
     
    /**display the winning player or indicate a tie (or unfinished game).*/
    public void displayWinner()
    {
        if(isWin(X))
        {
            System.out.println("\n X wins...!!");
            isEmpty=false;
        }
        else if(isWin(O))
        {
            System.out.println("\n O wins...!!");
            isEmpty=false;
        }
        else
        {
            if(!isEmpty)
            {
                System.out.println("its a tie");
            }
             
        }
    }
     
    public String toString()
    {
        StringBuilder s = new StringBuilder();
        isEmpty = false;
        for(int i=0;i<3;i++)
        {
            for(int j=0;j<3;j++)
            {
                switch(board[i][j])
                {
                case X:
                    s.append(" X ");
                    break;
                case O:
                    s.append(" O ");
                    break;
                case EMPTY:
                    s.append("   ");
                    isEmpty=true;
                    break;
                }
                if(j<2)
                {
                    s.append("|");
                }
                 
            }
            if(i<2)
            {
                s.append("\n-----------\n");
            }
        }
        return s.toString();
    }
}

Download Complete Java Program »

That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.

Happy Learning 🙂

If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.

We may not get time to plant a tree, but we can definitely donate ₹42 per Tree.



About the Author


Surviving Java Developer, Passionate Blogger, Table Tennis Lover, Bookworm, Occasional illustrator and a big fan of Joey Tribbiani, The Walking Dead and Game of Thrones...!!



Tags: , , , ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.
Total Posts : 124
follow us in feedly

Like Us On Facebook