Create a Tic-Tac-Toe Game using jQuery


In this post, we are going to implement 2-player tic-tac-toe using jQuery. It is quite easy to develop with some simple validations and error checks. Player-1 starts playing the game and both the players make their moves in consecutive turns. The player who makes a straight 3-block chain wins the game. Here, we’ll be implementing this game on the front-end using simple logics and validation checks only.

Prequisites: Basic knowledge of some front-end technologies like HTML, CSS, jQuery and Bootstrap.

Developing the layout: First of all, we will develop 3 * 3 grid layout and apply some CSS effects on the same. It should also show a text showing the turn of the player. It should also contain a button to reset the game whenever needed.

  • HTML Code:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!DOCTYPE html>
    <html lang="en">
      
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
      
        <script src=
        </script>
        <link rel="stylesheet" href=
        <script src=
        </script>
        <link rel="stylesheet" href=
              integrity=
    "sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" 
              crossorigin="anonymous">
      
    </head>
      
    <body>
        
        <!-- Heading -->
        <div class="container-fluid text-center">
            <h1 style="color: white;">TIC-TAC-TOE</h1></div>
        <br>
        <br>
        <div class="container-fluid text-center">
            
            <!-- Inform area for player's turn -->
            <h4 id="screen" style="color: white;">
              PLAYER 1 TURN FOLLOWS
            </h4>
        </div>
        <br>
        <div class="container-fluid">
            <div class="row">
                <div class="col-lg-4">   </div>
                <div class="col-lg-4">
                    <!-- Playing Canvas -->
                    <center>
                        <table>
                            <tr>
                                <td colspan="3">
                            </tr>
                            <tr>
                                <td>
                                    <button class="sq1 r"></button>
                                </td>
                                <td>
                                    <button class="sq2 r"></button>
                                </td>
                                <td>
                                    <button class="sq3 r"></button>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <button class="sq4 r"></button>
                                </td>
                                <td>
                                    <button class="sq5 r"></button>
                                </td>
                                <td>
                                    <button class="sq6 r"></button>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <button class="sq7 r"></button>
                                </td>
                                <td>
                                    <button class="sq8 r"></button>
                                </td>
                                <td>
                                    <button class="sq9 r"></button>
                                </td>
                            </tr>
                        </table>
                        <br>
                        <br>
                        
                        <!-- Reset button for Game -->
                        <input type="button" 
                               class="reset btn btn-lg btn-danger btn-block"
                               value="RESET" onClick="reset()" />
                    </center>
                </div>
                <div class="col-lg-4">   </div>
            </div>
        </div>
    </body>
      
    </html>

    chevron_right

    
    

  • CSS Code:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!-- Applying CSS Properties --> 
    <style> 
        body {
            background-color: #000000;
        }
      
        button {
            height: 80px;
            width: 80px;
            background-color: white;
            border: 0px transparent;
            border-radius: 50%;
            margin: 4px;
            padding: 4px;
        }
      
        .fa {
            font-size: 48px;
            color: black;
        }
      
        .reset {
            padding: 8px;
        }
      
        .reset:hover {
            opacity: 0.8;
        }
      
    </style>

    chevron_right

    
    

  • Output:

Implementing Logic: Now, we need to implement the following steps in our main code for mimicking the logic for a tic-tac-toe game.

  • Consecutive player turns: The consecutive turns will follow after the first player plays his move. Also, the text notifying the player’s turn should also be updated accordingly.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!-- Consecutive player Turns -->
    <script>
      
    // Flag variable for checking Turn
    // We'll be modifying our base logic in the
    // next steps as per requirements    
    var turn = 1;
      
    $("button").click(function() {
        if(turn == 1) {
            $("#screen").text("PLAYER 2 TURN FOLLOWS");
       
        // Check sign font from font-awesome
        $(this).addClass("fa fa-check"); 
            turn = 2;            
        }
        else {    
            $("#screen").text("PLAYER 1 TURN FOLLOWS");
           
            // Cross sign font from font-awesome
            $(this).addClass("fa fa-times"); 
            turn = 1;
        }
    });
    </script>

    chevron_right

    
    

  • Mark/Notify invalid moves: Also, we need to ensure that the player on the turn should not play any invalid move. For this, we will check if the clicked button is not already used by other font class in the process. If it is already marked by a font, mark the move invalid for a short interval.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!-- Script for checking any invalid moves -->
    $("button").click(function() {
        if($(this).hasClass("fa fa-times") ||
                $(this).hasClass("fa fa-check"))
        {       
            $(this).css("background-color", "red");
            setTimeout(() => {
                $(this).css("background-color", "white");
            }, 800);        
        }
    });

    chevron_right

    
    

  • Check for winning moves: We will develop a function that will check whether the player has completed the grid or not. For this, we need to check for 8 winning configurations of the player. We will send the font class to the function for checking the same.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!-- Function to check the winning move -->
    function check(symbol) {
        if ($(".sq1").hasClass(symbol) && 
            $(".sq2").hasClass(symbol) &&
            $(".sq3").hasClass(symbol))
        {
            $(".sq1").css("color", "green");
            $(".sq2").css("color", "green");
            $(".sq3").css("color", "green");
            return true;
        } else if ($(".sq4").hasClass(symbol)
                && $(".sq5").hasClass(symbol)
                && $(".sq6").hasClass(symbol))
        {
            $(".sq4").css("color", "green");
            $(".sq5").css("color", "green");
            $(".sq6").css("color", "green");
            return true;
        } else if ($(".sq7").hasClass(symbol)
                && $(".sq8").hasClass(symbol)
                && $(".sq9").hasClass(symbol))
        {
            $(".sq7").css("color", "green");
            $(".sq8").css("color", "green");
            $(".sq9").css("color", "green");
            return true;
        } else if ($(".sq1").hasClass(symbol)
                && $(".sq4").hasClass(symbol)
                && $(".sq7").hasClass(symbol)) 
        {
            $(".sq1").css("color", "green");
            $(".sq4").css("color", "green");
            $(".sq7").css("color", "green");
            return true;
        } else if ($(".sq2").hasClass(symbol)
                && $(".sq5").hasClass(symbol)
                && $(".sq8").hasClass(symbol))
        {
            $(".sq2").css("color", "green");
            $(".sq5").css("color", "green");
            $(".sq8").css("color", "green");
            return true;
        } else if ($(".sq3").hasClass(symbol)
                && $(".sq6").hasClass(symbol)
                && $(".sq9").hasClass(symbol)) 
        {
            $(".sq3").css("color", "green");
            $(".sq6").css("color", "green");
            $(".sq9").css("color", "green");
            return true;
        } else if ($(".sq1").hasClass(symbol)
                && $(".sq5").hasClass(symbol)
                && $(".sq9").hasClass(symbol)) 
        {
            $(".sq1").css("color", "green");
            $(".sq5").css("color", "green");
            $(".sq9").css("color", "green");
            return true;
        } else if ($(".sq3").hasClass(symbol)
                && $(".sq5").hasClass(symbol)
                && $(".sq7").hasClass(symbol)) 
        {
            $(".sq3").css("color", "green");
            $(".sq5").css("color", "green");
            $(".sq7").css("color", "green");
            return true;
        } else {
            return false;
        }
    }

    chevron_right

    
    

  • Resetting the game: Clicking on this button will reset the game.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!-- Resetting the game -->
    function reset()
    {
       $("#screen").text("PLAYER 1 TURN FOLLOWS");
       $("#screen").css("background-color", "transparent");
       $(".r").removeClass("fa fa-check");
       $(".r").removeClass("fa fa-times");
       turn=1;
      
       // Reset Colors
       $(".sq1").css("color", "black");
       $(".sq2").css("color", "black");
       $(".sq3").css("color", "black");
       $(".sq4").css("color", "black");
       $(".sq5").css("color", "black");
       $(".sq6").css("color", "black");
       $(".sq7").css("color", "black");
       $(".sq8").css("color", "black");
       $(".sq9").css("color", "black");
      
    }

    chevron_right

    
    

Output: Combining all the codes written above then it will be a complete tic-tac-toe game.

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.