Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="container text-center">
  <h1>Tic Tac Toe</h1>
  
  
  <div id="board" class="rounded">
    <div id="humanTurn" class="turnMsg">Your Turn</div>
    <div id="computerTurn" class="turnMsg">Computer's Turn</div>
    <div id="startMessage">
      <p>Would you like to be X or O?</p>
      <button id="chooseX">X</button>
      <button id="chooseO">O</button>
  </div>
    <div id="message">You Win!</div>
    <div id="grid">
      <div id="box1"></div>
      <div id="box2"></div>
      <div id="box3"></div>
      <div id="box4"></div>
      <div id="box5"></div>
      <div id="box6"></div>
      <div id="box7"></div>
      <div id="box8"></div>
      <div id="box9"></div>
  </div>
</div>
  <footer class="text-center">
    Made with <span class="glyphicon glyphicon-heart"></span><br/>
    by <a href='/kode29' target='_blank'>Kyle M. Perkins</a>
  </footer>
              
            
!

CSS

              
                body{
  background-color: #1e1f21;
  color: #cac9cd;
}
#board{
  font-family: 'Indie Flower', Arial, cursive;
  box-shadow: 0 0 10px rgba(255,255,255,.8);
  height: 545px;
  width: 545px;
  margin: auto;
  border: 10px #fff solid;
  border-radius: 5px;
  background-color: #999;
    box-sizing: border-box;
  color: #000;

}
#grid>div{
  border: 1px #000 solid;
  height: 175px;
  width: 175px;
  float: left;
  cursor: default;
}
#grid>div>div{
  font-size: 14em;
  line-height: 175px;
}
#grid{
  position: relative;
  z-index: 0;
}
#message{
  width: 100%;
    height: 100%;
    background: rgba(255,240,0,.8);
    margin-bottom: -100%;
    padding-top: 30%;
    font-size: 10em;
    z-index: 100;
    position: relative;
  display: none;
}
#startMessage{
    width: 100%;
    height: 100%;
    background: rgba(120,120,120,.8);
    margin-bottom: -100%;
    padding-top: 10%;
    font-size: 6em;
    z-index: 100;
    position: relative;
}
#startMessage button{
  background-color: rgba(255,255,255,.5);
  width: 130px;
  height: 130px;
  border-radius: 25%;
  border: 0;
  transition: all .5s ease-in-out;
}
#startMessage button:hover{
  background-color: rgba(255,255,255,.85);
}
.turnMsg{
  width: 30%;
    line-height: 2em;
    position: relative;
    z-index: -100;
    margin-bottom: -2em;
    height: 2em;
  border-radius: 5px;
}
#humanTurn{
  background-color: #fc0;
}
#computerTurn{
  background-color: #b00;
  float: right;
}
footer{
  margin: 2em auto;
  line-height: 1.5em;
  font-size: .8em;
}
              
            
!

JS

              
                $(function() {
    // First, determine who's turn it is
    var currentTurn = "human"; // manual override for now
    var humanSymbol, computerSymbol;
    var gameStatus = "play";
    var winningBoxes = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
        [1, 4, 7],
        [2, 5, 8],
        [3, 6, 9],
        [1, 5, 9],
        [3, 5, 7]
    ];
  
  function resetTurnBoxes(){
    $('#humanTurn').animate({"top": "0px"});
    $('#computerTurn').animate({"top": "0px"});
  }

    function playGame() {
        console.log("Current Turn: " + currentTurn);
      resetTurnBoxes();
        if (currentTurn == "computer") {
            $('#computerTurn').animate({"top": "-50px"});

            var emptyBoxes = [];

            $("#grid div").each(function(e) {
                if ($(this).html().length == 0) {
                    emptyBoxes.push($(this).attr("id"));
                }
            });
           //console.log(emptyBoxes);

          var randomBox =
              emptyBoxes[Math.floor(Math.random() * emptyBoxes.length)];
          console.log("Thinking...");
          //console.log(randomBox);
          setTimeout(function() {
            $("#" + randomBox).click();
          }, 1000);
        } else{
          $('#humanTurn').animate({"top": "-50px"});
          console.log("Your turn!");
        }
    }
  
      $('#startMessage button').on('click', function(){
        var selectedSymbol = $(this).attr("id").substr(-1);
        if (selectedSymbol == "X"){
          humanSymbol = "X";
          computerSymbol = "O";
        } else {
          humanSymbol = "O";
          computerSymbol = "X";
        }
      
      $('#startMessage').fadeOut(function(){
        $(this).remove();
      });
      playGame();
    });

    function resetGame() {
        console.log("Resetting Game...");
        resetTurnBoxes();
        $("#grid div div").each(function(e) {
            $(this).fadeOut(function() {
                $(this).remove();
            });
        });
        gameStatus = "play";
        playGame();
    }

    function searchForArray(haystack, needle) {
        var b, i, j, current, boxCounter;
        for (i = 0; i < haystack.length; ++i) {
            //console.log(haystack[i]);
            current = haystack[i];
            boxCounter = 0;

            for (j = 0; j < needle.length; j++) {
                //console.log(needle);
                for (b = 0; b < current.length; b++) {
                    //console.log("Checking " + current[b] + "==" + needle[j]);
                    if (current[b] == needle[j]) {
                        boxCounter++;
                    }
                    //console.log(boxCounter);
                    if (boxCounter == 3) {
                        console.warn("We've reached our limit of the game. The result is...");
                        return true;
                    }
                }
            }
        }
        return false;
    }

    function changeTurn() {
        currentTurn = currentTurn == "human" ? "computer" : "human";
    }

    function checkIfWin() {
        var filledBoxesX = [];
        var filledBoxesO = [];

        $("#grid div div").each(function(e) {
            if ($(this).text() != "") {
                var boxSymbol = $(this).text();
                var boxId = $(this)
                    .parent()
                    .attr("id");

                switch (boxSymbol) {
                    case "X":
                        filledBoxesX.push(boxId.substr(-1) * 1);
                        break;
                    case "O":
                        filledBoxesO.push(boxId.substr(-1) * 1);
                        break;
                }
            }
        });

        // Display end message, and restart

        if (filledBoxesX.length >= 3 && searchForArray(winningBoxes, filledBoxesX))
            win("X");
        else if (
            filledBoxesO.length >= 3 &&
            searchForArray(winningBoxes, filledBoxesO)
        )
            win("O");
        else if (filledBoxesX.length + filledBoxesO.length == 9) win("Draw");
        else changeTurn();
    }

    function win(symbol) {
        gameStatus = "stop";
        resetTurnBoxes();
        var msg, msgColor;
        switch (symbol) {
            case humanSymbol:
                msg = "You Win!";
                msgColor = "rgba(255,240,0,.8)";
            console.log("%c"+msg, "background-color: #fc0;");
                break;
            case computerSymbol:
                msg = "You lost";
            console.log("%c"+msg, "background-color: #c00; color: #fff;");
                msgColor = "rgba(240,0,0,.8)";
                break;
            case "Draw":
                msg = "Draw!";
            console.log("%cIt's a draw!", "background-color: rgb(34,139,34); color: #fff;");
                msgColor = "rgba(34,139,34, .8)";
                break;
        }
        $("#message").css("background-color", msgColor);
        $("#message")
            .html(msg)
            .fadeIn()
            .delay(2000)
            .fadeOut();
        setTimeout(resetGame, 2000);
    }

    // Next, insert the "symbol" of whose turn it is
    // inside the square that is clicked
    $("#grid div").on("click", function() {
        //console.log($(this).attr('id'));
        symbol = currentTurn == "human" ? humanSymbol : computerSymbol;
        console.log("Inserting " + symbol);

        if ($(this).html().length == 0 && gameStatus == "play") {
            // Don't insert a symbol on a box that is already occupied
            $(this).html("<div>" + symbol + "</div>");

            // On click, and after placement, check for a "winning strategy"
            checkIfWin();
            playGame();
        } else
          console.warn("I can't do that. The box already has a symbol in it! Choose another box");
    });

});
              
            
!
999px

Console