JavaScript Tic Tac Toe Game

In this tutorial, I will tell you how to build a basic tic tac toe game using HTML, CSS and JavaScript.

Most of the people know that when we were kids we used to play this game on paper. We played it many times till we win.

Those who don’t know about this game let me give you little overview. In this game there are two players, the player who makes three of their marks in row and column or one of the two diagonals wins the game. When the board fills up and no combination making then the game is in draw state.

There are some rules that we are going to define here is that as we know the primary thing is move, here the player cannot undo that move. By clicking on the box he can make a move as soon as the move is done, the game proceeded to give a chance to another player.

At each move, it will show whose player moves it is either is A or it is B

When the game ends it displays three outcomes:

• winner player one
• winner player two
• draw

It also displays the replay button if a tie happens.

JavaScript Tic Tac Toe Game Example

Its programming is not that simple as it looks. In this js program, we track each move for the next players move. This is quite complex when we start coding. I am sharing my simple code so that you can understand the game easily. So basically we create 3 files here or we can do all code in one file which includes all html, css and javascript.

So firstly we make a design or UI part then start work on its functionality. You can create this by using plain javascript.

Before writing code, we also have to check what are the winning conditions.

Player 1 plays when the move is equal to 1, 3, 5, 7 and 9. Player 2 plays when the move is equal to 2, 4, 6 and 8. So, Player 1 plays when move is an odd number. Here we can write the logic this way, if ((count%2)==1), then it is player 1’s turn, otherwise it is player 2’s turn. When any player presses on a blank space, that respective player places either an X or O on the playing board.

In the code firstly we write the winning case scenarios at which numbers he/she can win the game. Then we make a function for each move player is playing, in the function we check that players wins or not by that move. We also make a function if no one wins the game then they can again play that game.

Here is code to make the game.

You can play the game given below to test how it works.

Comment down below if you have any queries related to above JavaScript Tic Tac Toe game.