Best Website-BuildersBest Website-Builders
    What's Hot

    5 Best Password Managers (2022): Features, Pricing, and Tips

    March 27, 2023

    Harry's power play: Why has the prince turned up at court?

    March 27, 2023

    Casualties reported in Tennessee school shooting

    March 27, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram
    Best Website-BuildersBest Website-Builders
    • Home
    • CSS

      The 2023 Nagaland State Budget presents state matching shares for the CSS for the first time.

      March 27, 2023

      Annual Development Outlay for 2023-24 fixed at Rs 82,000 lakh | MorungExpress

      March 27, 2023

      Web Scraping with Python and Selenium | Daniel Ellis Research | | March 2023

      March 27, 2023

      Gunboat Association, Partners Host Environmental Education Day on April 1 — News News

      March 27, 2023

      6 best e-books about technology and the people behind it

      March 25, 2023
    • Joomla

      An In-Depth Study of the Market Status, Trends and Top Players of the Open Source Content Management Systems Market

      March 27, 2023

      Save Thousands On Web Hosting With iBrave, Now Only $86

      March 23, 2023

      In Vitro Transcription Services Market Analysis, Research Study with Shanghai Zhishuo Biotechnology Co., Yunzhou Biotechnology Co.

      March 23, 2023

      Current state of UK content management systems

      March 23, 2023

      Reseller Hosting Business: Important Q&A

      March 21, 2023
    • PHP

      TikTok’s WAGs want to show what their lives are really like

      March 27, 2023

      Olivia Wilde slammed leaked documents about Jason Sudeikis’ custody battle

      March 27, 2023

      March 27, 2023 — Biggest news story of the day

      March 27, 2023

      Former U.S. Marshal Convicted of ‘Rape Fantasy’ Conspiracy Against Former American

      March 26, 2023

      Explosion at Palmer chocolate factory kills 4

      March 26, 2023
    • UX

      Experience Optimization Product Acronym Translation

      March 27, 2023

      Uptime.com offers synthetic transaction monitoring to track performance, user experience and prevent revenue loss

      March 27, 2023

      AAZZUR Partners with Financial Services Data Platform Sikoia

      March 27, 2023

      y00ts forms a link from Solana to Polygon for easy user experience

      March 27, 2023

      5 Most Wanted Jobs in the Tech Startup Ecosystem

      March 27, 2023
    • Web Builders
      1. Web Design
      2. View All

      What Comes First in Website Development — Design or Copy?

      February 2, 2023

      Modern Campus Honors Best Higher Education Websites of 2022

      February 2, 2023

      Premier SEO Consultant in Las Vegas, Nevada with Unparalleled Customer Service

      February 2, 2023

      Can Religious Freedom Be Saved? This group is racing the clock to teach America’s first freedom

      February 2, 2023

      How i Create New Google Account

      February 7, 2023

      CWT powers tools for meeting and event planners

      January 31, 2023

      Best Website Builder – Website Builders

      January 24, 2023

      Is There A Market For Rap-Themed Slot Games? – Rap Review

      January 19, 2023
    • WordPress

      Xbox Series X receives a visual update, but it’s not what we’ve been waiting for

      March 27, 2023

      Procter & Gamble is the latest large-scale GoAnywhere zero-day victim

      March 27, 2023

      China to pass 1 billion 5G connections within 2 years

      March 27, 2023

      Beware — These IRS Tax Returns Could Actually Be Just Malware

      March 27, 2023

      Part of Twitter’s source code appears to have been leaked by a disgruntled programmer

      March 27, 2023
    • Realtoz
      • Our Other Sites
    • More News
    Best Website-BuildersBest Website-Builders
    Home » Create a two-player tic-tac-toe game using JavaScript, HTML, and CSS
    JavaScript

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

    websitebuildersnowBy websitebuildersnowJanuary 27, 2023No Comments6 Mins Read
    Facebook Twitter LinkedIn Telegram Pinterest Tumblr Reddit WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


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

    Bag zero and cross symbols


    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 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!



    Source link

    Share this:

    • Tweet
    • Email
    • Pocket
    • Mastodon
    • WhatsApp
    • Telegram
    • Share on Tumblr
    • Print
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email
    Previous ArticleNovak Djokovic’s father to watch Australian Open semi-final from home
    Next Article Millie Farrow on her struggle with OCD and serious injuries
    websitebuildersnow
    • Website

    Related Posts

    No More JavaScript: How Microsoft Blazor Uses WebAssembly

    March 27, 2023

    What’s New in TypeScript 5.0

    March 27, 2023

    How to Add a Property to Each Object in an Array of Objects Using JavaScript | Jon O’Young | | Mar 2023

    March 25, 2023
    Add A Comment

    Leave a Reply Cancel reply

    Top Posts

    Subscribe to Updates

    Get the latest sports news from SportsSite about soccer, football and tennis.

    Advertisement
    Demo

    This website provides information about CSS and other things. Keep Supporting Us With the Latest News and we Will Provide the Best Of Our To Makes You Updated All Around The World News. Keep Sporting US.

    Facebook Twitter Instagram Pinterest YouTube
    Top Insights

    5 Best Password Managers (2022): Features, Pricing, and Tips

    March 27, 2023

    Harry's power play: Why has the prince turned up at court?

    March 27, 2023

    Casualties reported in Tennessee school shooting

    March 27, 2023
    Get Informed

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    © 2023 bestwebsite-builders. Designed by bestwebsite-builders.
    • Home
    • About us
    • Contact us
    • DMCA
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.