How to Create a Tic Tac Toe Game Using HTML, CSS, and JS

Tic tac toe is a popular and simple game that involves two players who take turns marking the spaces in a 3×3 grid with X or O. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner. Tic tac toe is also known as noughts and crosses or Xs and Os, and it has a long history that dates back to ancient Egypt and Rome.

In this article, you will learn how to create your own tic tac toe game using HTML, CSS, and JS. You will use HTML to create the basic structure of the game board, CSS to style the board and the symbols, and JS to add interactivity and logic to the game. You will also learn how to implement the winning strategy and the reset button for the game. By following these steps, you will be able to create a fun and responsive tic tac toe game that you can play on your browser or share with your friends.

HTML section

The first step is to create the HTML file for your tic tac toe game. You can name it index.html or anything you like. In this file, you will create the basic structure of the game board using HTML tags and attributes. You will also link the external CSS and JS files that you will create later.

The HTML file should look something like this:

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Tic Tac Toe Game</title>     <link rel="stylesheet" href="style.css">     <link rel="preconnect" href="[18](https://fonts.gstatic.com)">     <link href="[17](https://fonts.googleapis.com/css2?family=Itim&display=swap)" rel="stylesheet"> </head> <body>     <main >         <section >             <h1>Tic Tac Toe</h1>         </section>         <section >             Player <span >X</span>'s turn         </section>         <section >             <div ></div>             <div ></div>             <div ></div>             <div ></div>             <div ></div>             <div ></div>             <div ></div>             <div ></div>             <div ></div>         </section>         <section >             <button >Reset Game</button>         </section>     </main>     <script src="script.js"></script> </body> </html>

Let’s break down the HTML code and see what each part does:

  • The <!DOCTYPE html> declaration specifies the HTML version that the document is using.
  • The <html> element is the root element of the document, and it has a lang attribute that specifies the language of the document.
  • The <head> element contains the metadata of the document, such as the title, the character encoding, the viewport, and the links to the external files.
  • The <title> element defines the title of the document that appears on the browser tab.
  • The <link> elements link the external CSS and JS files to the HTML file. The first link element also links a Google font that we will use for styling the game.
  • The <body> element contains the visible content of the document, such as the main, section, and div elements.
  • The <main> element is a semantic element that defines the main content of the document. It has a class attribute that we will use for styling the background of the game.
  • The <section> elements are semantic elements that define different sections of the document. Each section has a class attribute that we will use for styling and selecting the elements. The first section contains the title of the game, the second section contains the display of the current player’s turn, the third section contains the game board, and the fourth section contains the reset button.
  • The <div> elements are generic containers that we will use for creating and styling the tiles of the game board. Each div element has a class attribute that we will use for styling and selecting the tiles.
  • The <h1> element defines the main heading of the document, which is also the title of the game.
  • The <span> element defines a part of text within another element. We will use it to display and style the current player’s symbol (X or O).
  • The <button> element defines a clickable button that we will use to reset the game.
  • The <script> element links the external JS file to the HTML file. It should be placed at the end of the body element so that it runs after the HTML elements are loaded.

CSS section

The next step is to create the CSS file for your tic tac toe game. You can name it style.css or anything you like. In this file, you will style , and applies some styles to them, such as color.

  • The .reset selector selects the section element with the class attribute of reset, and applies some styles to it, such as margin-top.
  • The .reset-button selector selects the button element with the class attribute of reset-button, and applies some styles to it, such as width, height, border, border-radius, font-family, font-size, color, background-color, and cursor.
  • The .reset-button:hover selector selects the reset-button element when it is hovered over by the mouse pointer, and applies some styles to it, such as transform.
  • The @media screen and (max-width: 600px) rule defines a media query that applies some styles to the elements when the screen width is less than or equal to 600px. This makes the game responsive and adaptable to different screen sizes.
  • The @keyframes bounce rule defines an animation that makes the elements bounce by changing their scale property.
  • The .winner selector selects the tile elements with the class attribute of winner, and applies an animation to them using the animation property.
  • JS section

    The final step is to create the JS file for your tic tac toe game. You can name it script.js or anything you like. In this file, you will add interactivity and logic to the game using JS variables, functions, events, and conditions. You will also implement the winning strategy and the reset button for the game.

    The JS file should look something like this:

    // Selecting the elements from the HTML file const tiles = document.querySelectorAll(".tile"); const display = document.querySelector(".display"); const displayPlayer = document.querySelector(".display-player"); const resetButton = document.querySelector(".reset-button"); // Declaring some variables for storing the game state let currentPlayer = "X"; // The current player's symbol (X or O) let gameStatus = "Game On"; // The status of the game (Game On or Game Over) let board = ["", "", "", "", "", "", "", "", ""]; // The array that represents the game board // Declaring some constants for storing the winning combinations const winningCombos = [     [0, 1, 2],     [3, 4, 5],     [6, 7, 8],     [0, 3, 6],     [1, 4, 7],     [2, 5, 8],     [0, 4, 8],     [2, 4, 6] ]; // Adding an event listener to each tile element tiles.forEach((tile) => {     tile.addEventListener("click", () => {         // Checking if the tile is empty and the game is on         if (tile.innerHTML === "" && gameStatus === "Game On") {             // Marking the tile with the current player's symbol             tile.innerHTML = currentPlayer;             // Updating the board array with the current player's symbol             board[parseInt(tile.id)] = currentPlayer;             // Checking if the current player has won             checkWin();             // Switching to the next player             switchPlayer();         }     }); }); // Adding an event listener to the reset button element resetButton.addEventListener("click", () => {     // Resetting the game state     currentPlayer = "X";     gameStatus = "Game On";     board = ["", "", "", "", "", "", "", "", ""];     // Clearing all the tiles     tiles.forEach((tile) => {         tile.innerHTML = "";         tile.classList.remove("winner");     });     // Updating the display     displayPlayer.innerHTML = currentPlayer;     displayPlayer.classList.remove("playerO");     displayPlayer.classList.add("playerX");     display.innerHTML = `Player ${currentPlayer}'s turn`; }); // Defining a function that checks if the current player has won function checkWin() {     // Looping through the winning combinations array     for (let i = 0; i < winningCombos.length; i++) {         // Storing a single winning combination in a variable         let combo = winningCombos[i];         // Checking if the board array has the same symbol in all three indices of the winning combination         if (             board[combo[0]] === currentPlayer &&             board[combo[1]] === currentPlayer &&             board[combo[2]] === currentPlayer         ) {             // Changing the game status to Game Over             gameStatus = "Game Over";             // Updating the display             display.innerHTML = `Player ${currentPlayer} has won!`;             // Adding a winner class to the tiles that form the winning combination             tiles[combo[0]].classList.add("winner");             tiles[combo[1]].classList.add("winner");             tiles[combo[2]].classList.add(" winner");             // Returning from the function to stop further execution             return;         }     }     // Checking if the board array has no empty spaces left     if (!board.includes("")) {         // Changing the game status to Game Over         gameStatus = "Game Over";         // Updating the display         display.innerHTML = "It's a tie!";         // Returning from the function to stop further execution         return;     } } // Defining a function that switches to the next player function switchPlayer() {     // Checking if the game is still on     if (gameStatus === "Game On") {         // Changing the current player to the opposite symbol         currentPlayer = currentPlayer === "X" ? "O" : "X";         // Updating the display         displayPlayer.innerHTML = currentPlayer;         displayPlayer.classList.toggle("playerX");         displayPlayer.classList.toggle("playerO");         display.innerHTML = `Player ${currentPlayer}'s turn`;     } }

    Let's break down the JS code and see what each part does:

    • The first four lines select the elements from the HTML file using the document.querySelectorAll and document.querySelector methods, and store them in variables for later use.
    • The next three lines declare some variables for storing the game state, such as the current player's symbol, the status of the game, and the board array.
    • The next line declares a constant for storing the winning combinations, which are arrays of three indices that correspond to the tiles of the game board.
    • The next block of code adds an event listener to each tile element using the forEach method and an arrow function. The event listener listens for a click event, and executes a callback function that checks if the tile is empty and the game is on, marks the tile with the current player's symbol, updates the board array with the current player's symbol, checks if the current player has won, and switches to the next player.
    • The next block of code adds an event listener to the reset button element using an arrow function. The event listener listens for a click event, and executes a callback function that resets the game state, clears all the tiles, and updates the display.
    • The next block of code defines a function that checks if the current player has won using a for loop and an if statement. The function loops through the winning combinations array, and checks if the board array has the same symbol in all three indices of each winning combination. If so, it changes the game status to Game Over, updates the display, and adds a winner class to the tiles that form the winning combination. If not, it checks if the board array has no empty spaces left. If so, it changes the game status to Game Over, and updates the display with a tie message.
    • The last block of code defines a function that switches to the next player using an if statement and a ternary operator. The function checks if the game is still on, and changes the current player to the opposite symbol using a ternary operator. It also updates the display with the current player's symbol and turn.

    Conclusion

    Congratulations! You have successfully created a tic tac toe game using HTML, CSS, and JS. You have learned how to use HTML tags and attributes to create the basic structure of the game board, how to use CSS properties and selectors to style the board and the symbols, how to use JS variables, functions, events, and conditions to add interactivity and logic to the game, and how to implement the winning strategy and the reset button for the game. You have also learned how to make the game responsive and attractive using media queries and animations.

    Now that you have created your own tic tac toe game, you can try to improve or customize it in different ways. Here are some tips and challenges for you:

    • Try to add some sound effects or music to the game using the HTML audio element and the JS Audio object.
    • Try to add some difficulty levels or modes to the game, such as easy, medium, hard, or multiplayer.
    • Try to add some features or options to the game, such as changing the symbols, colors, or fonts of the game.
    • Try to create a different version or variation of the game, such as 4x4 grid, 3D tic tac toe, or tic tac toe with gravity.

    I hope you enjoyed this article and learned something new. If you have any questions or feedback, feel free to leave a comment below. Happy coding!

    FAQs

    What is tic tac toe?

    Tic tac toe is a popular and simple game that involves two players who take turns marking the spaces in a 3x3 grid with X or O. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner.

    How do you create a tic tac toe game using HTML, CSS, and JS?

    You can create a tic tac toe game using HTML, CSS, and JS by following these steps:

    1. Create an HTML file that contains the basic structure of the game board using HTML tags and attributes, and link the external CSS and JS files.
    2. Create a CSS file that styles the game board and the symbols using CSS properties and selectors, and make the game responsive and attractive using media queries and animations.
    3. Create a JS file that adds interactivity and logic to the game using JS variables, functions, events, and conditions, and implement the winning strategy and the reset button for the game.

    How do you make a tic tac toe game responsive?

    You can make a tic tac toe game responsive by using media queries in your CSS file. Media queries allow you to apply different styles to different screen sizes or devices. For example, you can use @media screen and (max-width: 600px) to apply some styles when the screen width is less than or equal to 600px.

    How do you implement the winning strategy for tic tac toe?

    You can implement the winning strategy for tic tac toe by using an array that stores all the possible winning combinations of three indices that correspond to the tiles of the game board. You can then use a loop and a condition to check if the board array has the same symbol in all three indices of each winning combination. If so, you can declare the current player as the winner and update the display and the tiles accordingly.

    How do you add sound effects or music to tic tac toe?

    You can add sound effects or music to tic tac toe by using the HTML audio element and the JS Audio object. The HTML audio element allows you to embed an audio file in your HTML file, and the JS Audio object allows you to control the playback of the audio file using JS methods and properties. For example, you can use new Audio("sound.mp3") to create an audio object from a sound file, and use audio.play() and audio.pause() to play and pause the audio respectively.



    bc1a9a207d