Are you beginning your web development career? Or are you just trying to have fun learning new skill? Whatever it is. Learning to create a simple Tic Tac Toe game that you have played with your friends hundreds of time is definitely a fun thing to do in your journey. So let us start without wasting our time.
What is Tic Tac Toe?
Tic Tac Toe is a classic two-player game where players take turns marking the spaces on a 3×3 grid with either an X or an O. The goal of the game is to get three of your symbols in a row, either horizontally, vertically, or diagonally.
In this article, we will go through the step-by-step process of creating a Tic Tac Toe game using HTML, CSS, and JavaScript. Before staring there are some prerequisite that you should have to understand it properly.
- Basic understanding of Html and Css
- Basic understanding of HTML DOM
- Basic understanding of Javascript
Step 1: Set up the HTML
Create an HTML file and add the basic structure for the game. This includes a table with 3×3 cells, a heading to indicate what the game is, and a paragraph to display the current player’s turn and the winner.
Step 2: Add styling with CSS
In the head of the HTML file, add the styles for the table and cells. This will make the table look neat and give it a border.
Step 3: Add the JavaScript logic
Add a JavaScript code to implement the game logic. First, we will add event listeners to the cells so that when a cell is clicked, it changes to either an X or an O, depending on whose turn it is. We will also update the status message to show the current player’s turn.
Step 4: Check for a win or draw
To determine if the game has ended in a win or a draw, we need to add code that checks the state of the game after each move. We will create a function that checks the state of the cells and updates the status message to show the winner or declare a draw.
Finally, we need to call the checkForWin
function after each move. To do this, we will add a call to checkForWin
at the end of the handleClick
function.
Now the final code looks something like this. I have added all code in the image format to encourage you to write the code by yourself because you will learn only when you code by yourself.
And that’s it! You now have a fully functional Tic Tac Toe game which can be customized by adding additional CSS styles or changing the logic to suit your needs.
Check the below code pen for the working game. If you see the code in CodePen you will find html, css and javascript in a separate page.
See the Pen
Untitled by Sagar Kunwar (@kunwarsagar)
on CodePen.