in

Create a two-player tic-tac-toe game using JavaScript, HTML, and CSS

knots and crosses symbols on bags

[ad_1]

Get this simple game up and running in your web browser in no time!


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 3 symbols in horizontal, vertical or diagonal rows.


You can use HTML, CSS, and JavaScript to create a tic-tac-toe game that runs in your web browser. You can use HTML to add content, including a 3×3 grid, and CSS to add styling to your game design.

You can then use JavaScript for game functionality. This includes placing symbols, taking turns between players, and determining winners.


How to create a UI for a Tic-Tac-Toe game

The full source code for this game can be read and downloaded from our GitHub repository.

Tic-tac-toe is one of many games you can create when learning how to program. Great for practicing new languages ​​and environments such as the PICO-8 game development engine.

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

  1. Create a new file named “index.html”.
  2. Inside “index.html” add the basic structure of the 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 with 3 rows with 3 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. Create a new file named “styles.css” in the same folder as your HTML file.
  5. In your CSS file, add styles to the 3×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. Add your CSS file to the head tag and link it to your HTML file.
     <link rel="stylesheet" type="text/css" href="styles.css"> 

How to add symbols to the game board in order

The game has two players, each with an ‘X’ or ‘O’ symbol. You can add an “X” or “O” symbol by clicking on his one of the grid cells. This continues until one creates a straight horizontal, vertical, or diagonal row.

This functionality can be added using JavaScript.

  1. Create a JavaScript file called “script.js” in the same folder as your HTML and CSS files.
  2. Add a script to the end of the body tag to link your JavaScript file to your HTML file.
     <body>
      
      <script src="script.js"></script>
    </body>
  3. Inside the JavaScript file, add a string representing the player symbol. This is either an ‘X’ or an ‘O’. By default, the first player places an “X”.
     let playerSymbol = "X"; 
  4. Add another variable to track if the game is over.
     let gameEnded = false 
  5. Each cell in the HTML table has an ID from 1 to 9. For each cell in the table, add an event listener that runs whenever the 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. Use a JavaScript conditional statement to first check that the cell is empty and that the game hasn’t finished yet.
     if (this.innerHTML === "" && !gameEnded) {
      this.innerHTML = playerSymbol;
    }
  7. Add classes to HTML elements to style the symbols displayed in the grid. The name of the CSS class will be either ‘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 are displayed in different colors.
     .x {
      color: blue;
      font-size: 80px;
    }

    .o {
      color: red;
      font-size: 80px;
    }

  9. In your JavaScript file, change the innerHTML to show the symbols, then swap the symbols. For example, if the player places an ‘X’, change the next symbol to an ‘O’.
     if (playerSymbol === "X")
      playerSymbol = "O"
    else
      playerSymbol = "X"
  10. To run the game, open the “index.html” file in your web browser to view the 3×3 grid.
    browser tic-tac-toe empty grid

  11. Click a cell to begin placing symbols in the grid. The game alternates between ‘X’ and ‘O’ symbols.
    A browser tic-tac-toe game that displays symbols

How the winner is determined

At this time, the game continues even if the player places 3 consecutive symbols. To check this, you need to add an end condition every turn.

  1. Inside the JavaScript file, add a new variable to store all possible “winning” positions of the 3 x 3 grid. for example, “[1,2,3]” is the top line, 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 every cell contains a player 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, all symbols are on a straight line. Inside the if statement, display a message to the user. You can also add her CSS class called “win” to change the style of HTML elements.
     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 your “styles.css” file. When a player wins, the background color of the winning cell changes to yellow.
     .win {
      background-color: yellow;
    }
  7. Inside the event handler you added in the previous step, call the checkWin() function each time the player takes a turn.
     for (let i = 1; i <= 9; i++) {
      
      document.getElementById(i.toString()).addEventListener(
        "click",
        function() {
          if (this.innerHTML === "" && !gameEnded) {
            
            this.innerHTML = playerSymbol;
            this.classList.add(playerSymbol.toLowerCase());
                    
            
            checkWin();
                    
            
            if (playerSymbol === "X")
              playerSymbol = "O"
            else
              playerSymbol = "X"
          }
        }
      );
    }

How to reset the game board

Once a player wins the game, you can reset the game board. In case of a tie, you can also reset the game board.

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

    #reset {
      margin: 48px 40%;
      padding: 20px;
    }

  3. In your JavaScript file, add an event handler that runs whenever the user clicks 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 innerHTML to remove “O” and “X” symbols and remove all other CSS styles.
     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. Open the “index.html” file in your web browser and run the game.
  6. Start placing the “X” and “O” symbols on the grid. Try to win one of the symbols.
    Tic-tac-toe winner

  7. Press the reset button to reset the game board.
    Tic-tac-toe with reset button

Learn JavaScript by making games

You can continue to improve your programming skills by creating more projects in JavaScript. Easily create simple games and tools in a web environment using cross-platform open technologies such as JavaScript and HTML.

There is no better way to improve your programming than by practicing writing programs!

[ad_2]

Source link

What do you think?

Leave a Reply

GIPHY App Key not set. Please check settings

    9a8a5d70 9e43 11ed 8f65 71bfa0525ce3

    Zoom: Monmouthshire councillor rebuked over knitting in meeting

    1674837606 31081.photo .2

    Friday Readings: Paolo De Marchi Leaves ‘Happy Ghosts’ on Isole e Olena