Tic Tac Toe Game Code - in Java (Play in Console)


Tic Tac Toe is a two-player game played on a three-by-three grid. Players alternately insert their unique marks like 'x' and 'o' in one of the grid's nine spots.

The player who succesfully reserves his symbol into three consecutive boxes - horizontally, vertically or diagonally, wins.

This article is about this game code written in Java Programming Language. This Tic Tac Toe game can be played in Java Console.

The Output of the Tic Tac Toe Game will look as follows -

Watch the Tic Tac Toe Java Console Game Play on youtube

Tic Tac Toe Game Code - in Java

We will need to create a package named TicTacToe.

In the package we will be creating three class files -

  • Board.java,
  • Player.java, and
  • TicTacToe.java.

TicTacToe.java file will contain the main method.

We follow a sequence while we enter the position for placing our symbol inside the grid of the game.

To determine the position, we make use of x-axis and y-axis.

Please refer to the following illustration to get an idea of the position number for axis for Tic Tac Toe game. And follow this illustration to understand the coding structure better.

Tic Tac Toe Game x-axis y-axis Illustration for Java Code

Referring to the above image, we have written our code for Tic Tac Toe Game code in Java that can be played in Console in the following files below.

Board.java

The following code should be present in the Board.java file -

package TicTacToe;

public class Board {
	private char board[][];
	private int boardSize = 3;
	private char p1Symbol, p2Symbol;
	private int count;
	public final static int PLAYER_1_WINS = 1;
	public final static int PLAYER_2_WINS = 2;
	public final static int DRAW = 3;
	public final static int INCOMPLETE = 4;
	public final static int INVALID = 5;

	public Board(char p1Symbol, char p2Symbol){
		board = new char[boardSize][boardSize];
		for(int i =0; i < boardSize; i++){
			for(int j =0; j < boardSize; j++){
				board[i][j] = ' ';
			}
		}
		this.p1Symbol = p1Symbol;
		this.p2Symbol = p2Symbol;
	}
	public int move(char symbol, int x, int y) {

		if(x < 0 || x >= boardSize || y < 0 || y >= boardSize || board[x][y] != ' '){
			return INVALID;
		}

		board[x][y] = symbol;
		count++;
		// Check Row
		if(board[x][0] == board[x][1] && board[x][0] == board[x][2]){
			return symbol == p1Symbol ? PLAYER_1_WINS : PLAYER_2_WINS;
		}
		// Check Col
		if(board[0][y] == board[1][y] && board[0][y] == board[2][y]){
			return symbol == p1Symbol ? PLAYER_1_WINS : PLAYER_2_WINS;
		}
		// First Diagonal
		if(board[0][0] != ' ' && board[0][0] == board[1][1] && board[0][0] == board[2][2]){
			return symbol == p1Symbol ? PLAYER_1_WINS : PLAYER_2_WINS;
		}
		// Second Diagonal
		if(board[0][2] != ' ' && board[0][2] == board[1][1] && board[0][2] == board[2][0]){
			return symbol == p1Symbol ? PLAYER_1_WINS : PLAYER_2_WINS;
		}
		if(count == boardSize * boardSize){
			return DRAW;
		}
		return  INCOMPLETE;

	}
	public void print() {
		System.out.println("---------------");
		for(int i =0; i < boardSize; i++){
			for(int j =0; j < boardSize; j++){
				System.out.print("| " + board[i][j] + " |");
			}
			System.out.println();
		}
		System.out.println();
		System.out.println("---------------");
	}
}

Player.java

The following code should be present in the Player.java file -

package TicTacToe;

public class Player {

	private String name;
	private char symbol;
	
	public Player(String name, char symbol){
		setName(name);
		setSymbol(symbol);
	}
	
	public void setName(String name) {
		
		if(!name.isEmpty()) {
			this.name = name;
		}
	}
	
	public String getName() {
		return this.name;
	}
	
	public void setSymbol(char symbol) {
		if(symbol != '\0') {
			this.symbol = symbol;
		}
	}
	
	public char getSymbol() {
		return this.symbol;
	}
}

TicTacToe.java

The following code should be present in the TicTacToe.java file -

package TicTacToe;

import java.util.Scanner;

public class TicTacToe {

	private Player player1, player2;
	private Board board;

	public static void main(String args[]){
		TicTacToe t = new TicTacToe();
		t.startGame();
	}

	public void startGame(){
		Scanner s = new Scanner(System.in);
		// Players input
		player1 = takePlayerInput(1);
		player2 = takePlayerInput(2);
		while(player1.getSymbol() == player2.getSymbol()){
			System.out.println("Symbol Already taken !! Pick another symbol !!");
			char symbol = s.next().charAt(0);
			player2.setSymbol(symbol);
		}
		// Create Board
		board = new Board(player1.getSymbol(), player2.getSymbol());
		// Conduct the Game
		boolean player1Turn = true;
		int status = Board.INCOMPLETE;
		while(status == Board.INCOMPLETE || status == Board.INVALID){  
			if(player1Turn){
				System.out.println("Player 1 - " + player1.getName() + "'s turn");
				System.out.println("Enter x: ");
				int x = s.nextInt();
				System.out.println("Enter y: ");
				int y = s.nextInt();
				 status =  board.move(player1.getSymbol(), x, y);
				if(status != Board.INVALID){
					player1Turn = false;
					board.print();
				}else{
					System.out.println("Invalid Move !! Try Again !!");
				}
			}else{
					System.out.println("Player 2 - " + player2.getName() + "'s turn");
					System.out.println("Enter x: ");
					int x = s.nextInt();
					System.out.println("Enter y: ");
					int y = s.nextInt();
					 status =  board.move(player2.getSymbol(), x, y);
					if(status != Board.INVALID){
						player1Turn = true;
						board.print();
					}else{
						System.out.println("Invalid Move !! Try Again !!");
					}				
			}
		}
		
		if(status == Board.PLAYER_1_WINS){
			System.out.println("Player 1 - " + player1.getName() +" wins !!");
		}else if(status == Board.PLAYER_2_WINS){
			System.out.println("Player 2 - " + player2.getName() +" wins !!");
		}else{
			System.out.println("Draw !!");
		}
	}

	private Player takePlayerInput(int num){
		Scanner s = new Scanner(System.in);
		System.out.println("Enter Player " + num + " name: ");
		String name = s.nextLine();
		System.out.println("Enter Player " + num + " symbol: ");
		char symbol = s.next().charAt(0);
		Player p = new Player(name, symbol);
		return p;	
	}

}

Running and Playing the Game - Tic Tac Toe

After writing these codes into their respective files, we can run TicTacToe.java as Java Application.

Following is the game flow implemented in this Tic Tc Toe game -

  • At first, the game asks for two player's names.
  • Then the game asks for two different symbols, each symbol reserved for each player.
  • If the second player enters the same symbol as the first player's symbol, the second player will get an error message in the console.
  • Then the game will ask for x-axis and y-axis positions. Each player is required to enter values within the range 0 to 2 for each axis.
  • X-axis and Y-axis will form a grid of 9 boxes. If any player has used a box(by entering x-axis and y-axis positions) in the game, that particular box gets reserved for the entire upcoming session of the game . So, choosing a previously used box will throw an error in the console.
  • If a player has succesfully reserved his symbol into three consecutive boxes - horizontally, vertically or diagonally, that player wins.
  • If no single player could arrange their symbol into three consecutive boxes - horizontally, vertically or diagonally, the match is declared draw by the Tic Tac Toe game.

Explanation of Game Code -

The Board class contains the logic for the game board and the methods for making moves and checking for wins. It has a 2D char array to represent the board, and a count variable to keep track of the number of moves made.

The move method takes in a symbol (X or O) and the position of the move, checks if the move is valid, updates the board, and checks for a win. The print method prints the current state of the board.

The Player class simply stores the name and symbol of the player.

The TicTacToe class is the main class that starts the game. It takes input from the users to set up the game (player names and symbols), creates a Board object with the symbols, and then loops through the game until there is a winner or a draw.

It alternates between the two players, asking them for input and checking if the move is valid. It prints the board after each move and checks for a win or draw. If there is a winner or a draw, it prints the result and ends the game.

I hope you enjoyed making, understanding and playing this Tic Tac Toe game with your pals.

Tic Tac Toe Game Code – in Java (Play in Console) - Featured Image

You may like to Explore -

Make a Simple Calculator using Java

Cheers!

Happy Coding.

About the Author

This article was authored by Rawnak.