How to create tic-tac-toe game in Java

tic-tac-toe in console

·

3 min read

How to create tic-tac-toe game in Java

Hi, I'm Gokul a passionate learner and this is my first blog created to share and document my learning. This blog is about teaching how to create a tic-tac-toe game in Java and guiding you through the step-by-step process of building on your own.

Prerequisite:

1. Arrays

2. DataTypes

3. Variables

4. Methods

5. Loops

Let's dive into the process of creating a game:

The first step is Building the Board. In the main method, we are going to create a 2D Character array called a board it contains full of dashes{-}.

Next, create printBoard() method which takes the 2D array and prints the array content.

Create the askUser() function. It let the player to choose a spot on the board.

Inside the function:

1. Get the row and column from the user using the Scanner class.

2. Loop to check if the spot is already taken

3. If Spot is already taken again get the row and column from the user.

4. use while loop if the player tried to pick a spot that was already taken (0 0). The game prompted them to pick another spot.

In the main function setup for loop that runs 9 times and prints the counter.

X plays when the counter is even, whereas O plays when the counter is odd.

Call the function askUser() for each turn. During each turn the function call returns an array of integers that contains the user spot, so we need to store that array in a new variable int[]spot.

We are going to use spot variable to update the board i.e board[spot[0]][spot[1]] = 'X'; and board[spot[0]][spot[1]] = 'O';

Let's see about the game logic:

If the user wants to win the game by checking all the possibilities.

1. check every row has the same X or O.

2. check every column has the same X or O.

3. check right diagonal has the same X or O.

4. check left diagonal has the same X or O.

Write a function for the row to check the same X or O (chekcRow()).

If the count has 3 means X wins and -3 Means O wins. Create a method for each column, left diagonal, and right diagonal.

Write a function for the column to check the same X or O.

Write a function for the left diagonal to check the same X or O.

Write a function for the right diagonal to check the same X or O.

We are going to write the checkWin() Function to check the winning move.

Here, we use Math.abs method to return the absolute value of a given number, removing any negative sign.

We came to the last step in the program in the main function using the if statement to check if the count is 3 X wins, else if the count is -3 O wins, else if the game is tied.

Conclusion

Thank you, We are done creating a console tic-tac-toe game. Now you learn about how to create a tic-tac-toe game in Java. Through my blog posts, I aim to provide valuable information and practical tips. Feel free to leave comments, share your thoughts, and connect with me. For more future blogs follow me and also follow me on LinkedIn.