Simple Tic-Tac-Toe JavaScript game for beginners - Main image

Intermediate

Simple Tic-Tac-Toe JavaScript game for beginners

Tic-Tac-Toe JavaScript game is a simple example of games you can program in JavaScript. Game making is the most popular branch of programming. It is also an amazing way to learn the basics of a programming language while creating a simple and interesting project. In this article we will guide you, step by step, to make a simple Tic-Tac-Toe game using JavaScript, HTML and CSS. Starting with the HTML code, which is the part for assigning id tags and classes to the elements of our game, such as the board and cells. The longest part of making the Tic-Tac-Toe game is the JavaScript code, which makes the game interactive. Lastly, we will show you how to personalize the game using CSS.

Nera Husarević - CodeBrainer
Nera Husarević
15 min read

Tic-Tac-Toe JavaScript game is a simple example of games you can program in JavaScript. Games can be developed with many programming languages, but the most popular for it are C++, JavaScript and C#. 

If you wish to learn while also having fun or just curing your boredom, creating a simple JavaScript and HTML/CSS game is your solution. In this article we will guide you through making a simple Tic-Tac-Toe JavaScript game, design and gameplay, which you later can expand to a more detailed and difficult game. We really like simple JavaScript games at CodeBrainer since they are educational and fun.

Tutorial is constructed in three parts. In the HTML part of our code, we will assign id tags and classes to the elements of our board. JavaScript will take care of all the interactions in our game. Lastly, the CSS stylesheet will let us personalize the visual appearance of our game. 

Tic-Tac-Toe is a two-player game in which the players fill up nine empty rectangles in a table with either an X or an O when it is their turn. Once someone succeeds to line up their sign vertically or horizontally without an interruption, that player wins. With our help you can make a multiplayer browser game, which you can play with a friend.

Tic-Tac-Toe JavaScript game



The beginning

To stay organized and optimized when making games, you should separate different parts of code into different files. For our Tic-Tac-Toe JavaScript game we will use only three different files since it is a simple game. In the index.html we will assign classes to all separate constructors of our game. We will style our game in the style.css. Last but not least we will write our script in the script.js. 

The gameplay will start with the x character, so that automatically makes x the first player. 



HTML for the Tic-Tac-Toe JavaScript game

Starting off with HTML. This is the most simple and short part of our code. Here we will assign classes and ids to our HTML elements. Since this game is made of a board with cells inside, we will construct the cells with the <div> element. This means we will just create generic containers which we will style later. Our board will be as simple as possible.

playing board - Tic-Tac-Toe JavaScript game

As you probably already know, a tic-tac-toe game requires 9 cells (3x3). Instead of a full blown menu, we will just add a message at the end with the restart button. This is what we will create in the body of our HTML. This is what our HTML will look like:

HTML
HTML frame for the Tic-Tac-Toe JavaScript game - HTML - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

The head is kept simple. Here we just titled our web page and connected the index.html to the stylesheet and script.

HTML
HTML body for the game - HTML - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!



In the body we created our board and named its class and id. We also assigned the “cell” class to the cells inside the board. We added a few more <div> elements for our winning message and the restart button. To learn a bit more about the basics of HTML read up on our "What is HTML?" article.

 

JavaScript for the Tic-Tac-Toe game

 

Now we create code for the Tic-Tac-Toe JavaScript game. This part is what makes the game playful. If you are a total beginner and need some introduction of JavaScript, you should check out our article about what JavaScript is.

JavaScript
Player CSS classes and winning combinations - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

In the first few lines of our script, we create a constant variable for our x and o characters. The table under presents combinations of movements for winning the game. These combinations will help us determine if the game is over or not, by checking if any of the combinations match the current gameplay.

JavaScript
Variables for elements for Tic-Tac-Toe game - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

Here we used the id tags we assigned in the index.html to save the values of all the board elements, winning message and the restart button. For this we used the JavaScript method getElementById(). For the winning message text element we used the querySelector() method which returns the first element within the document that matches the specified selector. We also used the squared brackets ([]) to target the data-cell attribute.

JavaScript
Initialization of the board - Tic-Tac-Toe - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

In this portion of the script we created a function for starting the game called gameStart(). We set the isPlayer_O_Turn variable to false, meaning the first to play will be an x character. The rest of the function removes all the characters left from previous gameplay. Here we also trigger the events which may happen on our board, which are the mouse clicks.

JavaScript
Handling clicks for the game of Tic-Tac-Toe - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

In the function handleClick we handle the mouse click events for the cells in the board. Most of the functions called here will be separately explained. In short, the currentClass variable saves the character (X or O), whose turn it is at the moment. Another function is used in the if statement to check if someone has already won by comparing the winning combinations to the gameplay. This way it determines whether there is a draw or not.

JavaScript
When does the game of Tic-Tac-Toe end? - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

The gameEnd() function was mentioned previously. It is the function that ends the game. The function can either display a winner message which specifies which character won or a message that states there is no winner – it is a draw, depending on the outcome of the if statement. 

JavaScript
Is a draw? - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

Another function that was mentioned before is the isDraw() function. This one just returns the value in case there is a draw, meaning that neither of the players has won. There is also a nice method hidden in the isDraw function named every that checks all elements of an array to confirm a condition by returning a boolean value. It is usually defined as an array which tests the elements of an array and returns true (1) if they pass the test.

JavaScript
Making a turn in Tic-Tac-Toe game - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

placeMark() and swapTurns() are two short and simple functions. The placeMark() places the character in the cell, currentClass being either an X or an O depending on whose turn it is. The second function is the one which swaps the turns after the character is placed in a cell.


Making Tic-Tac-Toe JavaScript game more interactive

In the upcoming part of our JavaScript code, we will set the cursor hovering effect onto the board. This will make it easier for the player to aim at the cells. It also makes our game a bit more responsive.

JavaScript
Effects for the game of Tic-Tac-Toe - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

Since we want a character to appear in the cells while hovering over them with our mouse cursor before placing them, the setBoardHoverClass() function takes care of the interactive part of that. The interactive elements will make our Tic-Tac-Toe JavaScript game more interesting.

JavaScript
Its a win!!! - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

And lastly of our JavaScript is the function checkWin() which is called to check if our board matches any of the winning combinations.


CSS - styling our game

The upcoming part of our code is where you can let your imagination and creativity loose. In the stylesheet we will use our id tags and classes to personalize the visuals of our game. All the way from borders and line width to colours and text size. Since this part of the code can be completely personalized you can either write it from scratch, suitable for your own preferences or use our example. You can also just change the colors, size, fonts etc. if you will be using our example.

For the purpose of the game, we assume you know a bit about CSS, but if you want to learn more about CSS you can check our blog post about what CSS is.

CSS
CSS Variables for Tic-Tac-Toe game - CSS - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

We use :root element to set variables for later use. These variables set the color of X and O, and width of the X sign. See personalization below to see how you can make Tic-Tac-Toe more to your liking.

CSS
CSS for board for Tic-Tac-Toe - CSS - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

Starting with visualizing our HTML, the margin creates spaces between elements with defined borders, here it is used to make zero borders for the whole screen. After that we describe the element with our board class name, specifying its width, height, how and where it is displayed. grid-template-columns is a less known property (here is a nice article about grid-template-columns), so to keep it simple, it specifies the number and width/s of columns in a grid layout. This way we make our 9 cells for playing.

CSS
Cell of the board - Tic-Tac-Toe JavaScript game - CSS - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

Here we specify how we want our cells to look. Starting with width and height, followed by width and color of the borders, display, position and cursor.

Next is making our table look more like a game of Tic-Tac-Toe. IWe exclude the outer cells from having a full border, so our board can look like this:

Making table more like board for the game

For a given cell we specify that there should not be a border. We select a cell using the nth-child selector where you write the number of a cell to select that element/cell.

CSS
Remove borders for the table - CSS - CSS - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

Here we determine that there is no hover effect if the cell is already filled with one of our two characters.

CSS
Cursor for the cell - CSS - CSS - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

 

Drawing a cross sign for player

Drawing a cross takes a bit of CSS magic. Using linear-gradient we define colors in 3 steps white, blue (for the cross) and white once again. But be careful at the beginning we also define the angle using words to top right at which it all happens. Background settings are there to make some spacing and to center the cross.

CSS
Draw Cross for the player using CSS - Tic-Tac-Toe - CSS - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

For color we use our variable --color-set. You can see that we used var function for that (read more about var function). There is another function called calc(read about calc function). This is a special function since it takes all kinds of measurements (like px, pt, %) and sums them together.

In case the cell is empty the hover effect will use a variable for color named --color and if we stamp an x or an o into it, it will be --color-set. Here you can see the stamped x next to the hovering effect of the o.

Hover effect - Tic-Tac-Toe

Here is the code for X that is not hovering. Only change is the name of the color.

CSS
Cross when cell is taken - CSS - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

 

Drawing a circle sign for a player

Drawing a circle is much easier, it only takes one line. But the same principle is used, just with radial-gradient.

CSS
Drawing Circle using CSS - Tic-Tac-Toe - CSS - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

This time it is more transparent how we use colors when a sign is hovering and when it is "set in stone".

 

Styling a winning messages

Styling for a winning message is more straightforward. Here we set fonts, and color for the text. Make the button a bit rounded. And add a hover effect at the end.

 

 

Displaying game results

Getting close to the finish line, we now play with our winning or draw message. Here we centered it on the screen and set the colour to white, since after the game is over the background becomes black.

Display a winner message

Here is the code for the message:

CSS
Winning message - CSS - Tic-Tac-Toe - CSS - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

And here is the code for the button with a hovering effect added:

CSS
Reset button with hover effect - CSS - CSS - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

It all looks something like this:

Restart button

The last class is for the way elements are drawn within the winning message.

CSS
Display winning message - CSS - CSS - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

 

 

Personalizing the game by changing the CSS

After following instructions on how to make a Tic-Tac-Toe JavaScript game, you can now  personally choose colors of the game elements and make it yours. Here is what it looks like after the background and cells have been altered to orange/yellow:

Personalize the JavaScript Tic-Tac-Toe game

You can change color using variables --color and --color-set. If you want to change the color of the border, change the border color of the cell.

 

 

Shout out

We would also like to give a shout out to the one (sadly no name is mentioned) that wrote the code that our project is based on. We changed quite a bit and made it more suitable for beginners. But it is still a nice piece of code, and you can check other projects they have on their page.

 

 

Conclusion

In CodeBrainer, we truly enjoy making and playing games. That is why we were excited to write an article about creating a Tic-Tac-Toe JavaScript game, which is simple enough to be an interesting project for both our students or just someone that is self-learning.

We hope to inspire people while introducing them to both game and web development at the same time. With JavaScript, HTML and CSS you are free to explore and experiment while making a simple game and yet advancing.

Feel free to share with us any adjustments or advice about this article or if you have taken interest in enrolling in some of our courses. We welcome both beginners and experienced developers with open arms.