How to Program a Tic Tac Toe Console Game in Java

I have been busy with other things, so it’s been a while since my last post. In this post I will be showing you how to program a simple Tic Tac Toe console game in Java. For this we will be using Eclipse as the IDE, but any other Java IDE should be OK. Tic Tac Toe game is one of the first project new programmers do when learning a language. It is not too complicated and not entry level either. To complete this project you will need medium level programming knowledge eg: variables, methods, classes, constructors, arrays. So let’s get started.

If you prefer video instead of written tutorial, here’s a video of this project on youtube

First thing is to open Eclipse IDE. Then we need to create a new project. And finally, create a new class called Tictactoe. To start, our class needs to have three variables, a multi-dimensional array called “board”, and two constants called “ROWS” and “COLS.” The array board will represent the 3 by 3 tic tac toe board and the two constants are the size of the array. The “regex” variable is a regular expression for “three spaces” which we will be using to check for available empty squares in “setPlay” method later.

private String[][] board;
private static final int ROWS = 3;
private static final int COLS = 3;
private String regex = "\\s{3}";

The Next step will be to create the constructor that will be use to instantiate our class.

public Tictactoe() {
    board = new String[ROWS][COLS];		
}

Our first method will for initializing the board. We will be setting the board to all empty squares “spaces.”

/**
 * initialized board
 */
public void initializeBoard() {
	for(int i = 0; i < ROWS; i++) {
		for(int j = 0; j < COLS; j++) {
		       board[i][j] = "   ";
		}
	}
}

We also need a method for printing the board to console screen

/**
 * printing tictactoe board
 * @return strBoard
 */
public String printBoard() {
	String strBoard = "";
	for(int i = 0; i < ROWS; i++) {
		for(int j = 0; j < COLS; j++) {
			if(j != COLS-1)
				strBoard += board[i][j] + "|";
			else
				strBoard += board[i][j];
		}
		if(i != COLS-1)
			strBoard += "\n---+---+---\n";
	}
	return strBoard;
}

Our next method will set the players move on the board, which is either an “X” or “O”

public void setPlay(int i, int j, String player) {
	if(this.board[i][j].matches(regex))
		board[i][j] = " "+player+" ";
}

Finally, we need to check for end of game scenario, in which one player wins or is a draw.

/**
 * checking for end of game
 * @return
 */
public boolean isGameOver() {
	//checking rows
   	for(int i = 0; i < ROWS; i++) {
    		if(!board[i][0].matches(regex) && board[i][0].equals(board[i][1]) && board[i][1].equals(board[i][2])) {    			
    			return true; 
    		}   			 			
    	}
    	//checking columnse.co    	
    	for(int j = 0; j < COLS; j++) {    		
    		if(!board[0][j].matches(regex) && board[0][j].equals(board[1][j]) && board[1][j].equals(board[2][j])) 
   			return true;  			
   	}
   	//checking diagonals
   	if(!board[0][0].matches(regex) && board[0][0].equals(board[1][1]) && board[1][1].equals(board[2][2]))
   		return true;
   	if(!board[0][2].matches(regex) && board[0][2].equals(board[1][1]) && board[1][1].equals(board[2][0]))
   		return true;
   	//no body's won
	return false;
}

And we are done with the Tictactoe class. However, we need a main method to run our application. So let’s create a second class called Main, and create a Main method. Inside the main method we need a loop that runs the program until the end of the game. Here’s the code for Main method.

import java.util.Scanner;
public class Main {
 
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		Tictactoe game = new Tictactoe();
		game.initializeBoard();
		String player = "X";
		do {
			System.out.println(game.printBoard());
			System.out.println("Enter coordinates for rows: ");
			int row = input.nextInt();
			System.out.println("Enter coordinates for column: ");
			int col = input.nextInt();
			game.setPlay(row, col, player);
			if(game.isGameOver()) {
				System.out.println(game.printBoard() + "\n" + player + " wins!");
				break;
			}
			if(player == "X")
				player = "O";
			else
				player = "X";
 
		}while(true);	
 
	}
 
}

First, we instantiate our Tictactoe class. Second, we initialize the board. Third, we execute the loop. Inside the loop, we need to print the board with previous moves. Then, we ask every player for coordinates. We set the play, and we check for winners. Finally, if no one wins, we change players. And that’s it. That’s everything there’s to program a simple Tic Tac Toe console game.

Share This!

Leave a Reply

Your email address will not be published.