cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

Looking for quick-add? Try the external resource search, it's quicker and gives you access to the most recent version of thousands of libraries. ☝️

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Looking for quick-add? Try the external resource search, it's quicker and gives you access to the most recent version of thousands of libraries. ☝️

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <div class="container-fluid">
  
  
    <div class="row text-center">
    <div class="col-md-4 col-md-offset-4">
      <h1>tic tac toe</h1>
      </div>
      </div>

    <div class="row text-center">
      
    <div class="col-md-6 col-md-offset-3">
              <div class="text-center center-block" id ="who"></div>
      </div>
  </div>
  <div class="row text-center">
    
    <div class="col-md-6 col-md-offset-3">

      <div class="board center-block" id="grad">
        <div id="grid">
          <table>
            <tr id="row1">
              <td class="square" id="0"></td>
              <td class="square v" id="1"></td>
              <td class="square" id="2"></td>
            </tr>
            <tr id="row2">
              <td class="square h" id="3"></td>
              <td class="square v h" id="4"></td>
              <td class="square h" id="5"></td>
            </tr>
            <tr id="row3">
              <td class="square" id="6"></td>
              <td class="square v" id="7"></td>
              <td class="square" id="8"></td>
            </tr>
          </table>
        </div>

      </div>
      
    </div>
    
      
  </div>

</div>
            
          
!
            
              body {
  background: #1d2731;
  font-family: 'Montserrat', sans-serif;
  font-size: 30px;
}

h1 {
  font-size: 76px;
  margin: 0px;
  color: #fff;
  text-shadow: 1px 1px 1px grey, 0 0 1px grey, 0 0 1px grey;
}
button {
  display: inline;
  font-size: 24px;
  outline: none;
  border: none;
    background: #f9f9f9;

}
.board {
  height: 400px;
  width: 400px;
  border-radius: 10%;
  font-size: 80px;
  border: white 1px solid;
  padding: 22px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

.square {
  width: 120px;
  height: 120px;
  font-size: 80px;
  color: #fff;
  float: center;
  cursor: pointer;
}

.v {
  border-left: 4px solid #fff;
  border-right: 4px solid #fff;
}

.h {
  border-top: 4px solid #fff;
  border-bottom: 4px solid #fff;
}

.row {
  margin: 50px 0 50px 0;
}

.highlight:hover {
  cursor: pointer;
  text-decoration:underline;
}


#who {
  font-size: 40px;
  color: white;
  background: #394f66;
  width: 340px;
  height: 65px;
  text-align: center;
  float: center;
  border: white 1px solid;
  border-radius: 10px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  margin-bottom: -57px;
  z-index: -1;
}

#reset {
  padding-top: 50px;
  text-alight: left;
  float: right;
  background: #85dbdf;
}

#grad {
  text-align: center;
  color: black;
  background: linear-gradient(180deg, #DF744A, #FF383F);
}


/*/  background: linear-gradient(180deg, #319399, #85dbdf, #cc96d5, #901e86);/*/
            
          
!
            
              $(document).ready(function() {
    //set these values to do calculations on success rows
    var x = 1;
    var o = 4;
    //keep track of turns
    var turn = 0;
    //default
    var computer = "O",
        human = "X";
    var id;
    //beginning state of board
    var board = [0, 0, 0, 0, 0, 0, 0, 0, 0];
    //all possible indices that can win
    var success = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 4, 8],
        [2, 4, 6],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8]
    ];

    $("#who").html('Play as <span class ="highlight" id = "chooseX">X</span> or <span class ="highlight" id = "chooseO">O</span>?');

    //choose to play as X or O, then initiate game
    $("#who").on('click', "#chooseX, #chooseO", function() {

        var selection = this.id;
        if (selection === "chooseO") {
            $("#who").show().text("O's turn");
            computer = "X", human = "O";
            start1Play();
            AImove(board);
        } else {
            $("#who").show().text("X's turn");
            start1Play();
        }

    });

    //check if anyone has won by adding up all the success rows, 
      //if sums to 3, human wins, else if it sums to 12, computer wins
    function checkWin(board, turn) {
        for (var i = 0; i < success.length; i++) {
            var sum = 0;
            for (var j = 0; j < success[i].length; j++) {
                var index = success[i][j];
                sum += board[index];
            }
            if (sum === 3) {
                return 1;
            } else if (sum === 12) {
                return 2;
            }
            sum = 0;
        }
        if (turn >= 9) {
            return 3;
        }
        return 0;
    }

    //interprets result from checkWin and displays winner, then resets board
    function getWinner(result) {

        if (result === 1) {
            $("#who").text(human + " wins!");
            $("td").empty();
            setTimeout(function() {
                reset();
            }, 1000);
        } else if (result === 2) {
            $("#who").text(computer + " wins!");
            $("td").empty();
            setTimeout(function() {
                reset();
            }, 1000);
        } else if (result === 3) {
            $("#who").text("Draw!");
            $("td").empty();
            setTimeout(function() {
                reset();
            }, 1000);

        }

    }

    function AImove(board) {
        var sum = 0;
        var almostWin = [];
        var block = [];
        var allEmptyIndices = [];
        for (var i = 0; i < success.length; i++) {
            var emptyIndex;
            for (var j = 0; j < success[i].length; j++) {
                //add index to sum of a success row
                var index = success[i][j];
                sum += board[index];
                if (board[index] === 0) {
                    emptyIndex = success[i][j];
                    //if an empty index isn't already in allEmptyIndices, add it
                    if (allEmptyIndices.indexOf(emptyIndex) === -1) {
                        allEmptyIndices.push(emptyIndex);
                    }
                }
            }
            //after the inner for loop, if a sum adds to 8, that means AI is about to win
            //store the index of the winning empty slot
            if (sum === 8) {
                almostWin.push(emptyIndex);
                // else if sum adds to 2, that means human is about to win
                //store the index of the empty slot to block
            } else if (sum === 2) {
                block.push(emptyIndex);
            }
            //reset sum to 0 at the end of the outer for loop
            sum = 0;
        }
        //if almostWin has a value in it, computer will move there and win the game
        if (almostWin.length > 0) {
            id = "#" + almostWin[0].toString();
            $(id).text(computer).text(computer);
            board[almostWin[0]] = 4;
            turn += 1;
            return;
            //if computer is not about to win, check if it needs to block the human and move there
        } else if (block.length > 0) {
            board[block[0]] = 4;
            id = "#" + block[0].toString();
            $(id).text(computer).text(computer);
            turn += 1;
            return;
            //else put it somewhere random
        } else {
            var random = Math.floor(Math.random() * allEmptyIndices.length);
            board[allEmptyIndices[random]] = 4;
            id = "#" + allEmptyIndices[random].toString();
            $(id).text(computer);
            turn += 1;
            return;
        }
    }

    //initialize the game
    function start1Play() {
        $("td").one('click', function() {
            var slot = $(this);
            //if a slot is empty
            if (slot.text() === "") {
                $("#who").text(computer + "'s turn");
                turn += 1;
                slot.text(human);
                board[eval(this.id)] = x;

                var result = checkWin(board, turn);
                if (result === 0) {
                    AImove(board);
                } else {
                    getWinner(result);
                    return;
                }
                result = checkWin(board, turn);
                if (result !== 0) {
                    getWinner(result);
                    return;
                } else {
                    setTimeout(function() {
                        $("#who").text(human + "'s turn");
                    }, 500);
                }

            }
        });

    }

    function reset() {
        $("#who").html('Play as <span class ="highlight" id = "chooseX">X</span> or <span class ="highlight" id = "chooseO">O</span>?');
        $("td").empty();
        $("td").removeClass("animated zoomIn");
      
        computer = "O";
        human = "X";
        board = [0, 0, 0, 0, 0, 0, 0, 0, 0];
        turn = 0;
    }


});
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console