Tic-tac-toe is a popular game that uses a 3×3 grid. The goal of the game is to be the first player to place three symbols in a straight horizontal, vertical, or diagonal row.

You can create a Tic-tac-toe game that runs in a web browser using HTML, CSS, and JavaScript. You can use HTML to add the content that contains the 3×3 grid, and CSS to add some styling to the game design.

You can then use JavaScript for the game’s functionality. This includes placing symbols, taking turns between players, and deciding who wins.

How to Create the UI for the Tic-Tac-Toe Game

You can read and download the full source code for this game from its GitHub repository.

Tic-tac-toe is one of the many games that you can make when learning how to program. It’s a good one to practice a new language or environment, like the PICO-8 game development engine.

To create a Tic-tac-toe game that runs in a web browser, you will need to add HTML for the page content. You can then style this using CSS.

  1. Create a new file called "index.html".
  2. Inside "index.html", add the basic structure of an HTML file:
            <!doctype html>
    <html lang="en-US">
      <head>
        <title>Tic Tac Toe Game</title>
      </head>
      <body>
        
      </body>
    </html>
  3. Inside the HTML body tag, add a table that contains three rows, with three cells in each row:
            <div class="container">
      <table>
        <tr>
          <td id="1"></td>
          <td id="2"></td>
          <td id="3"></td>
        </tr>
        <tr>
          <td id="4"></td>
          <td id="5"></td>
          <td id="6"></td>
        </tr>
        <tr>
          <td id="7"></td>
          <td id="8"></td>
          <td id="9"></td>
        </tr>
      </table>
    </div>
  4. In the same folder as your HTML file, create a new file called "styles.css".
  5. Inside the CSS file, add some styling to your 3 by 3 grid:
            table {
      border-collapse: collapse;
      margin: 0 auto;
    }

    td {
      width: 100px;
      height: 100px;
      text-align: center;
      vertical-align: middle;
      border: 1px solid black;
    }
  6. Link the CSS file to your HTML file by adding it to the head tag:
            <link rel="stylesheet" type="text/css" href="styles.css">
        

How to Take Turns Adding Symbols to the Game Board

In the game, there will be two players, each with either an "X" or "O" symbol. You can add either an "X" or "O" symbol by clicking on one of the grid cells. This will continue until one of you has created a straight horizontal, vertical, or diagonal row.

You can add this functionality using JavaScript.

  1. In the same folder as your HTML and CSS files, create a JavaScript file called "script.js".
  2. Link the JavaScript file to your HTML file by adding the script to the bottom of the body tag:
            <body>
      <!-- Your code here -->
      <script src="script.js"></script>
    </body>
  3. Inside the JavaScript file, add a string to represent the player's symbol. This can either be "X" or "O". By default, the first player will place an "X":
            let playerSymbol = "X";
        
  4. Add another variable to keep track of whether the game has ended:
            let gameEnded = false
        
  5. Each cell in the HTML table has an ID between 1 and 9. For each cell in the table, add an event listener that will run whenever a user clicks on the cell:
            for (let i = 1; i <= 9; i++) {
      document.getElementById(i.toString()).addEventListener(
        "click",
        function() {
                
        }
      );
    }
  6. Inside the event listener, change the inner HTML to display the current symbol. Make sure to use a JavaScript conditional statement to first make sure the cell is empty, and that the game has not yet ended:
            if (this.innerHTML === "" && !gameEnded) {
      this.innerHTML = playerSymbol;
    }
  7. Add a class to the HTML element to style the symbol that will show on the grid. The name of the CSS classes will either be "X" or "O", depending on the symbol:
            this.classList.add(playerSymbol.toLowerCase());
        
  8. Inside the "styles.css" file, add these two new classes for the "X" and "O" symbols. The "X" and "O" symbols will display as different colors:
            .x {
      color: blue;
      font-size: 80px;
    }

    .o {
      color: red;
      font-size: 80px;
    }
  9. In the JavaScript file, after changing the innerHTML to display the symbol, swap the symbol. For example, if the player just placed an "X", change the next symbol to "O":
            if (playerSymbol === "X")
      playerSymbol = "O"
    else
      playerSymbol = "X"
  10. To run the game, open the "index.html" file in a web browser to display the 3 by 3 grid:
    Tic-Tac-Toe empty grid in browser
  11. Start placing symbols on the grid by clicking on the cells. The game will alternate between "X" and "O" symbols:
    Tic-Tac-Toe game in browser showing the symbols

How to Determine the Winner

At the moment, the game will still continue even if a player has placed three consecutive symbols. You will need to add an ending condition to check this after every turn.

  1. Inside your JavaScript file, add a new variable to store all possible "winning" positions for the 3 by 3 grid. For example, "[1,2,3]" is the top row, or "[1,4,7]" is a diagonal row.
            let winPos = [
      [1, 2, 3], [4, 5, 6],
      [7, 8, 9], [1, 4, 7],
      [2, 5, 8], [3, 6, 9],
      [1, 5, 9], [3, 5, 7]
    ];
  2. Add a new function called checkWin():
            function checkWin() {
      
    }
  3. Inside the function, loop through each of the possible winning positions:
            for (let i = 0; i < winPos.length; i++) {

    }
  4. Inside the for loop, check if all cells contain the player's symbol:
            if (
      document.getElementById(winPos[i][0]).innerHTML === playerSymbol &&
      document.getElementById(winPos[i][1]).innerHTML === playerSymbol &&
      document.getElementById(winPos[i][2]).innerHTML === playerSymbol
    ) {

    }
  5. If the condition evaluates to true, then all symbols are in a straight line. Inside the if statement, display a message to the user. You can also change the styling of the HTML element by adding a CSS class called "win":
            document.getElementById(winPos[i][0]).classList.add("win");
    document.getElementById(winPos[i][1]).classList.add("win");
    document.getElementById(winPos[i][2]).classList.add("win");
    gameEnded = true;

    setTimeout(function() {
      alert(playerSymbol + " wins!");
    }, 500);
  6. Add this "win" CSS class to the "styles.css" file. When the player wins, it will change the background color of the winning cells to yellow:
            .win {
      background-color: yellow;
    }
  7. Call the checkWin() function every time a player has a turn, inside the event handler added in the previous steps:
            for (let i = 1; i <= 9; i++) {
      // Whenever a player clicks on a cell
      document.getElementById(i.toString()).addEventListener(
        "click",
        function() {
          if (this.innerHTML === "" && !gameEnded) {
            // Display either "X" or "O" in the cell, and style it
            this.innerHTML = playerSymbol;
            this.classList.add(playerSymbol.toLowerCase());
                    
            // Check if a player has won
            checkWin();
                    
            // Swap the symbol to the other one for the next turn
            if (playerSymbol === "X")
              playerSymbol = "O"
            else
              playerSymbol = "X"
          }
        }
      );
    }

How to Reset the Game Board

Once a player has won the game, you can reset the game board. You can also reset the game board in the event of a tie.

  1. In the HTML file, after the table, add a reset button:
            <button id="reset">Reset</button>
        
  2. Add some styling to the reset button:
            .container {
      display: flex;
      flex-direction: column;
    }

    #reset {
      margin: 48px 40%;
      padding: 20px;
    }
  3. In the JavaScript file, add an event handler that will run whenever the user clicks on the reset button:
            document.getElementById("reset").addEventListener(
      "click",
      function() {

      }
    );
  4. For each cell in the grid, get the HTML element using the getElementById() function. Reset the innerHTML to remove the "O" and "X" symbols, and remove all other CSS styling:
            for (let i = 1; i <= 9; i++) {
      document.getElementById(i.toString()).innerHTML = "";
      document.getElementById(i.toString()).classList.remove("x");
      document.getElementById(i.toString()).classList.remove("o");
      document.getElementById(i.toString()).classList.remove("win");
      gameEnded = false;
    }
  5. Run the game by opening the "index.html" file in a web browser.
  6. Start placing "X" and "O" symbols on the grid. Try to make one of the symbols win.
    Tic Tac Toe winner
  7. Press the reset button to reset the game board.
    Tic-tac-toe with reset button

Learning JavaScript by Making Games

You can continue to improve your programming skills by creating more projects in JavaScript. It’s easy to build simple games and tools in a web environment, using cross-platform, open technologies like JavaScript and HTML.

There’s no better way to improve your programming than to practice writing programs!