Learn to Create a HTML Tic-Tac-Toe Game by using JavaScript

HTML Tic Tac Toe Game

Tic-Tac-Toe is a favorite game that works on using wit and strategy to help beat your opponent. While building the interface of this game is simple, writing the logic behind it is a bit more complex. However, this is one of the best ways to start building your skills on writing JavaScript if you are a newbie. Let’s get started with our coding.

In this blog, we are creating a Tic-Tac-Toe game board using HTML and JavaScript with three rows and three columns. The styling for the board will be in our style CSS file. It also includes jQuery script because the game also requires some jQuery functions.

A Tic-Tac-Toe game can at the most have 9 moves. The logic for player moves is as follows: Each player goes by pressing on an empty space on the board to mark it with an x or an o. The first person to get 3 x’s or o’s in a row, vertically, horizontally or diagonally, wins. We’ll use the jQuery click function to mark each square with an X or an O, depending on who is going first and who is going second.

Both players are continuing to increment the move variable by 1 and we do this until the 9th move, after which the board is filled completely. Player 1 goes when the move is equal to 1,3,5,7, and 9. Player 2 goes when the move is equal to 2,4,6 and 8. So, Player 1 goes when a move is an odd number – we can write this the following way: if ((move%2)==1), then it is player 1’s turn, otherwise, it is player 2’s turn. When either player presses on an empty space, that respective player places either an X or O on the board.

To check if a winner is selected, we will use the checkForWinners function () in the HTML file. There are total 9 allocated space text() rows and columns and diagonals.

Create an HTML Tic Tac Toe Game by using JavaScript

Sample : –

Now, we the game to stop if one person reaches 3 X’s or O’s in a row. We will also need to add the script to notify the player who has won.

The final script that includes the game logic will look something like this:

To add the styling for your game, all you need is to open the Style.CSS page and add the following script to the file. Save and Close.

Style.css –

OUTPUT – In the output photo below, Player 1 wins.

OUTPUT - In the output photo below, Player 1 wins.

Conclusion – Hope this guide has been helpful for you guys to learn how to create a complete Tic-Tac-Toe game using JavaScript, HTML and CSS.



Please enter your comment!
Please enter your name here