Tic Tac Toe Game in Java

How to create a Tic Tac Toe Game in Java

By Nurinnajiah Tsani

Almost all of us are familiar with the tic tac toe game. This strategy game is quite easy to play but kind of challenging to beat the opponent. 

Back then we can play this game simply with a piece of paper and pen. Draw a 3×3 grid and start to write down O or X consecutively between two players.

By developing this tic tac toe game project utilizing several computer languages, we can eventually convert this game to a digital one. We will discuss how to make a tic tac toe game in Java, one of the computer languages that we can use to develop this game.

So, keep on reading, Champs!

What is a Tic tac toe game?

Tic-tac-toe is a simple strategy game played on a 3×3 grid by two players, who alternately place the marks X and O in one of the nine spaces in the grid. This game is also well-known as noughts and crosses in Commonwealth English, or Xs and Os in Canadian or Irish English.

Determining the winner is quite simple actually. The first player who succeeds in placing three of their marks (be it O or X) in a horizontal, vertical, or diagonal row is the winner.

Tic Tac Toe Game in Java

Creating console Tic tac Toe game in Java is deceptively easy and quite simple. It can even be created by beginners. Because actually in this game we are going to practice the basic core concept like:

  • Variables
  • Booleans
  • Input and Output
  • Conditionals checking
  • Loops
  • Functions
  • 2D arrays

In this tutorial, we are going to create a simple console Tic Tac Toe game in Java, in which there will be 2 players taking turn in choosing grid row and column to place their characters.

We are going to use the most basic solution which is accessible and easily understandable by all skill levels in programming.

How To Create Tic Tac Toe Game in Java

  1. Build The Board
Tic Tac Toe Game in Java
Illustration of the game board using 2D arrays

The first step is to create the board by making a 3×3 grid. To create this board we will need 2D array of characters. We are going to use dashes [ – ] to create our board.

Hint: To create a 3×3 char array, use the following line of code:

char[][] gameBoard = new char[3][3]

To fill our game board with dashes [ – ], we can use nested loop and set gameBoard[i][j] = ‘-‘.

  1. Ask Both Players’ Name

To ensure that our game will be able to get input from user, we need to import java.util.Scanner at the top of our project.

After we initialize our game board with dashes, we will create the Scanner variable. Next, we will print out the message asking for both players to enter their names. Those names will be stored in a String variable called player_1 and player_2.

  1. Print Out The Board Like a 3×3 Gridlines
Tic Tac Toe Game in Java
How the game board will look like in the console

To display the board to the players, we need a function to prints it out with the 2D array as the parameter. We will only print the board with this function, hence there will be no return value from this function.

We can use System.out.print(); and System.out.println(); alternately. To display each column, use System.out.print(); since it will print it out on one line, and use System.out.println(); to print new row.

Hint: Use System.out.print(); in the inner for loop, and use System.out.println(); after the iteration of the inner for loop is finished. Therefore it will start a new row after all of the columns in each row have been printed out.

  1. Keep Track of Correct Player’s Turn and Char (X or O)

We can use conditional checking to keep track of whose turn it is, whether it’s player 1 or player 2.

  1. Players Choose Row and Column and We Check The Validity 

Use System.out.print(); to print out a message telling the user to choose the row and column to put their X or O, and use the Scanner variable to get their input. Their chosen row and column will be stored in the int variables called row and col.

Player’s chosen row and column are not always valid. There are 3 probabilities of their input:

  1. User entering invalid number that is not on the board (less than 0 or greater than 2).
  2. User choosing row and column that already being blocked by other player (it already has an X or O on it).
  3. User choosing the empty spot on the board (entering valid number between 0 – 2 and there’s no X nor O on it).

From all of the above probabilities, our aim is of course the c situation. Therefore we need to use a conditional to check their input. 

  1. Use a Loop to Ensure Player Enter a Valid Row and Column

We need to keep asking player to re-enter valid row and column number, whenever there’s a situation a or b above. We can use while(true) and break the loop once the player entered a valid row and column.

  1. Set the Player’s Character on The Right Spot on The Board

Once we have a valid row and column, now we can put the player’s character on the right spot by writing gameBoard[row][col] = c; in which c is a variable that stores the player’s character (X or O).

  1. Create a Function to Checks The Winner
Tic Tac Toe Game in Java
Illustration of all possible winning combination

A player wins if their three characters appear in a row, column, or diagonal.

In our Java Tic Tac Toe game, we can utilize if conditional testing inside for loop to determine the winner.

Let’s say we check the row first, we can iterate through each row i. If gameBoard[i][0] equals gameBoard[i][1] and if gameBoard[i][1] equals gameBoard[i][2] and gameBoard[i][0]  doesn’t equal to a dash or in another word, there’s no empty spot, then we have the winner and we can return the value of gameBoard[i][0].

Similar steps can be used as well to check the column result.

If none of the conditions were true and we reach the end of our function, it means that there’s no winner and we can just return a whitespace.

  1. If There’s a Winner, Print Out The Player who Win

In the previous function that checks the whether there’s a winner, there’s a return value. So in our main method, we can use if conditionals to check the return value.

If the return value is X, then print out that the winner is player 1, whereas if the return value is O, then the winner is player 2.

  1. Check Whether It’s Ended in a Tie

The game ends in a tie if the game board is already filled but there is no winner (no character lines up in a row, column, or diagonal).

The existence of any vacant spaces on the game board can be checked using a function that we can create. Vacant spaces are denoted by a dash (-). If the game board is full, this function will return true; otherwise, it will return false.

Hint: use nested for loops to iterate through each row and column. Use if conditional to check whether gameBoard[i][j] is equal to ‘-‘. If it is so, then return false.

Conclusion

Tic Tac Toe game is a classic programming problem that is actually quite simple to build. By creating this project you are implementing as well as learning about arrays, data structure, Booleans, variables, conditionals checking, and many more.

Don’t ever be satisfied with only one project, keep improving your coding skills by creating another game and solving other programming problems. 

To get your hands on more educational and free resources on coding for kids, financial education for kids, and robotics for kids do check out the BrightCHAMPS Page now!

Last but not least if you want to learn coding and creating your own game, you can Sign up for BrightCHAMPS trial class and you will see something interesting more than you bargain for.

Nurinnajiah Tsani

⭐⭐⭐⭐⭐

I am a nature enthusiast and IT expert who enjoys teaching and learning with children and volunteering with humanitarian organizations. At BrightChamps, my goal is to make the kids future-ready by strengthening their IT skills. Learn from Me

Reach Us

Categories

General Sidebar Widget Coding

Get a Talent Discovery Certificate after trial class

100% Risk-Free. No Credit Card Required

Related Articles

Trending Articles