123

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

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

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div class="container text-center">
  <div class="row">
    <!-- app title -->
    <div class="text-center">
      <h1 class="heading">TIC TAC TOE - FCC</h1>
      <!-- tips -->
    <div class="text-center">
      <h4 id="tipText"></h4>
    </div> <!-- tips -->
    
    <!-- playing area -->
    
    <!-- sidebar -->
    <div class="text-center gameboard-text sidebar rounded-corners col-xs-12 col-md-4">
      
      <div class="options rounded-corners col-xs-12 col-md-12">
        <!-- difficulty -->
        <div class="col-xs-4 col-md-12">
          <h3 class="sidebar-title">Difficulty</h3>
          <hr>
          <div id="easy" class="no-padding"><h4 class="difficulty">Easy</h4></div>
          <div id="normal" class="no-padding"><h4 class="difficulty selected">Normal</h4></div>
          <div id="hard" class="no-padding"><h4 class="difficulty">Hard</h4></div>
        </div>
        <!-- choose piece -->
        <div class="text-center col-xs-4 col-md-12">
          <h3 class="sidebar-title">Choose</h3>  
          <hr>
          <button id="chooseX"><h4><strong> X <strong></h4></button>
          <button id="chooseO"><h4><strong> O </strong></h4></button>
        </div>
        
        <!-- score -->
        <div class="col-xs-4 col-md-12">
          <h3 class="sidebar-title">Score</h3>  
          <hr>
          <h4 class="score">Player <span id="human-score">0</span></h4>
          <h4 class="score">Computer <span id="ai-score">0</span></h4>
          <h4 class="score">Ties <span id="tie-score">0</span></h4>
        </div>
        
      </div>
    </div>
    
    <!-- spacer -->
    <div class="spacer col-xs-0 col-md-1"></div>
    
    <!-- gameboard -->
    <div class="text-center gameboard-text gameboard-outline rounded-corners col-xs-12 col-md-6" id="playing-area">

      <div class="rounded-corners col-xs-12 col-md-12" id="gameboard">
        
        <div class="row">
          <div id="box0" class="square col-xs-4 col-sm-4 col-md-4"></div>
          <div id="box1" class="square col-xs-4 col-sm-4 col-md-4"></div>
          <div id="box2" class="square col-xs-4 col-sm-4 col-md-4"></div>
        </div>

        <div class="row">
          <div id="box3" class="square col-xs-4 col-sm-4 col-md-4"></div>
          <div id="box4" class="square col-xs-4 col-sm-4 col-md-4"></div>
          <div id="box5" class="square col-xs-4 col-sm-4 col-md-4"></div>
        </div>

        <div class="row">
          <div id="box6" class="square col-xs-4 col-sm-4 col-md-4"></div>
          <div id="box7" class="square col-xs-4 col-sm-4 col-md-4"></div>
          <div id="box8" class="square col-xs-4 col-sm-4 col-md-4"></div>
        </div>         
      
      </div>
      <!-- feedback -->
      <div class="feedback-area gameboard-text text-center col-xs-12 col-md-12"><h3 id="feedback-text">Choose X or O to begin!</h3></div> 
      
    </div> 
    <!-- gameboard -->
    
    <!-- /playing area -->
    
  </div> <!-- row -->
</div> <!-- container -->
      
 <!--Footer-->
<footer id="footer" class="footer text-center">
    <div class="contact">
    <div class="row">
        <a href="https://www.facebook.com/lindakovacsart" target="_blank"><span class="fa fa-facebook-f"></span> Facebook | </a>
        <a href="https://twitter.com/lindakovacsart" target="_blank"><span class="fa fa-twitter"></span> Twitter | </a>
        <a href="https://plus.google.com/u/1/112468176480762133222" target="_blank"><span class="fa fa-google-plus"></span> Google+ | </a>
        <a href="https://www.linkedin.com/in/lindakovacsart" target="_blank"><span class="fa fa-linkedin"></span> LinkedIn | </a>
        <a href="https://github.com/lindakovacs" target="_blank"><span class="fa fa-github"></span> GitHub | </a>
        <a href="https://www.freecodecamp.org/lindakovacs" target="_blank"><i class="fa fa-fire"></i> FreeCodeCamp | </a> <!-- class="fa fa-free-code-camp" -->
        <a href="https://codepen.io/lindakovacs" target="_blank"><i class="fa fa-codepen"></i>Codepen</a>
    </div>
        <p>&copy 2018 Made with &#10084; by Linda Kovacs</a></p>
</footer>
            
          
!
            
              body {
  width: 100%;
  margin: auto;
  background-color: #6CE2F9;
}

.heading{
    font-family: 'Raleway', sans-serif;
    font-weight: bold;
    background-color: #A063DD;
    color: white;
    border-radius: 10px;
    margin: auto;
    padding:10px;
    width: 90%;
    text-align: center;
    margin-top: 10px;
  }

#tipText {
  font-family: 'Raleway', sans-serif;
  font-size: 20px;
  color: #fff;
  background-color: #A063DD;
  border-radius: 10px;
  margin: auto;
  padding:10px;
  width: 90%;
  text-align: center;
  margin-top: 10px;
}

.gameboard-text { 
  font-family: 'Raleway', sans-serif;
  font-size: 10px;
  color: #fff;
  text-align: center;
}

hr {
  border-color: #000;
  margin-top: 0px;
  padding-top: 0px;
  padding-bottom: 0px;
  margin-bottom: 0px;
}

.rounded-corners {
  border-radius: 10px;
}

#gameboard {
  hight: 55%;
  wide: 55%;
  background-color: #A063DD;
  padding: 30px;
  border: 10px solid #fff;
  align-items: center;
  justify-content: center; 
  margin-top: 20px;
  margin-bottom: 15px;
}

.spacer {
  width: 2%;
}

.options {
  background-color: #A063DD;
  border: 10px solid #fff;
  margin-top: 15px;
}

.square {
  width: 33%;
  height: 120px;
  font-size: 5em;
  font-weight: bold;
  margin: 0;
  text-align: center;
}

#box3, #box5 {
  border-top-style: solid;
  border-top-width: thick;
  border-top-color: #fff;
  border-bottom-style: solid;
  border-bottom-width: thick;
  border-bottom-color: #fff;
}

#box1, #box7 {
  border-right-style: solid;
  border-right-width: thick;
  border-right-color: #fff;
  border-left-style: solid;
  border-left-width: thick;
  border-left-color: #fff;
}

#box4 {
  border-style: solid;
  border-width: thick;
  border-color: #fff;
}
/*
#playing-area {
  margin-bottom: 10px;
}
*/
h1.giant {
  font-size: 2em;
}

.no-padding {
  padding-left: 0px;
  padding-right: 0px;
}
h4 {
  margin-top: 10px;
  margin-bottom: 10px;
  padding: 5px 15px;
  font-size: 20px;
}
h4.difficulty {
  border-radius: 6px;
  margin-top: 4px !important;
  margin-bottom: 4px !important;
  padding: 5px 15px;
  cursor: pointer;
  border: 3px solid #fff;
}
/*
h4.selected {
  padding: 4% 2%;
  border-radius: 6px;
  color: #fff;
  background-color: #6BE2F9;
}
*/
.selected {
  border: 3px solid #fff;
  background-color: #6BE2F9;
}

.score {
  border: 3px solid #fff;
  border-radius: 6px;
}
button {
  background-color: transparent;
  background-repeat: no-repeat;
  border: 3px solid #fff;
  border-radius: 5px;
  cursor: pointer;
  overflow: hidden;
  outline: none;
  margin: 5px;
}
/*
button.selected {
  background-color: #6BE2F9;
}
*/
.sidebar-title {
  margin: 5px;
  color: #000;
  font-weight: bold;
}

.feedback-area {
  background-color: #A063DD;
  border: 10px solid #fff;
  padding: 20px;
  border-radius: 10px;
  margin-top: 30px;
  width: 100%;
}

h1 {
  margin-top: 10px;
}
#footer {
    background-color: #A063DD;
    color: #fff;
    border-radius: 20px;
    margin: 2em auto;
    padding: 20px;
    width: 90%;
  }
  footer {
    text-align: center;
    font-size: 15px;
    margin: 20px;
  }
  footer a {
    color: #fff;
    position: relative;
    text-decoration: none;
    font-weight: bold;
  }
  footer a:hover {
    color: #000;
  }
  footer p {
    margin: 0;
    font-size: 17px;
  }
            
          
!
            
              "use strict";
$(document).ready(function() {
// variable declaration  
  var difficulty = 2;
  var time = 1;
  var humanPiece = "";
  var aiPiece = "";
  var playing = false;
  var playerTurn = false;
  var gameboard = [];
  var humanScore = 0;
  var aiScore = 0;
  var tieScore = 0;
  var regexX = /^[X]{3}$/;
  var regexO = /^[O]{3}$/;
  var potWinO = /^(?!\s\s\s|\sO\s|\s\sO|O\s\s$)[^X]+$/;
  var potWinX = /^(?!\s\s\s|\sX\s|\s\sX|X\s\s$)[^O]+$/;
  var openO = /^(?=[^O]*[O][^O]*)[^X]+$/;
  var openX = /^(?=[^X]*[X][^X]*)[^O]+$/;
  var lastBox = /^[^\s]*[\s][^\s]*$/;
  var tips = [
  "Choose X or O to start a game.",
  "Good luck and have fun!",
  "X always goes first."  
];
var winArray = [
  [ 0 , 1 , 2 ],
  [ 3 , 4 , 5 ],
  [ 6 , 7 , 8 ],
  [ 0 , 3 , 6 ],
  [ 1 , 4 , 7 ],
  [ 2 , 5 , 8 ],
  [ 0 , 4 , 8 ],
  [ 2 , 4 , 6 ]
];

  // choose piece buttons
  $("#chooseX").click(function() {
    if (!playing) {
      setPiece("X");
    } else {
      var feedback = "Wait till the game is over.";
      updateFeedbackText(feedback);
    }
  });
  
  $("#chooseO").click(function() {
    if (!playing) {
      setPiece("O");
    } else {
      var feedback = "Wait till the game is over.";
      updateFeedbackText(feedback);
    }
  });
  
  // choose difficulty divs
  $("#easy").click(function() {setDifficulty(1, "easy")});
  $("#normal").click(function() {setDifficulty(2, "normal")});
  $("#hard").click(function() {setDifficulty(3, "hard")});
  
  // gameboard buttons
  $("#box0").click(function() {populateBox(0)});
  $("#box1").click(function() {populateBox(1)});
  $("#box2").click(function() {populateBox(2)});
  $("#box3").click(function() {populateBox(3)});
  $("#box4").click(function() {populateBox(4)});
  $("#box5").click(function() {populateBox(5)});
  $("#box6").click(function() {populateBox(6)});
  $("#box7").click(function() {populateBox(7)});
  $("#box8").click(function() {populateBox(8)});
  
  function setDifficulty(diff, id) {
    if (playing === false) {
      difficulty = diff;
      time = (diff == 3) ? 0.25 : (diff == 2) ? 0.5 : 1;
      $("#easy").children("h4").removeClass("selected");
      $("#normal").children("h4").removeClass("selected");
      $("#hard").children("h4").removeClass("selected");
      $("#" + id).children("h4").addClass("selected");
      console.log("difficulty:", difficulty, "time:", time);
    } else {
      updateFeedbackText("Wait till the game is over.");
    }
  }
  
  function generateBoard() {
    gameboard.length = 0;
    for (var i = 0; i < 9; i++) {
      gameboard.push(" ");
    }
  }
  
  function clearBoard() {
    var i = 0;
    var myInterval = setInterval(function() {
      $("#box" + i).html(gameboard[i]);
      i++;
      if (i == 9) {
        clearInterval(myInterval);
      }
    }, 200);
  }
  
  function populateBox(box) {
    var feedback = "";
    if (playing && playerTurn) {
      if (gameboard[box] === " ") {
        $("#box" + box).html("<h1 class='giant'>" + humanPiece + "</h1>");
        gameboard[box] = humanPiece;
        feedback = "";
        updateFeedbackText(feedback);
        playerTurn = false;
        computerTurn();
      } else {
        feedback = "An " + gameboard[box] + " was already played there.";
        updateFeedbackText(feedback);
      }
    }
  }
  
  function updateFeedbackText(feedback) {
    $("#feedback-text").text(feedback);
  }
  
  function setPiece(piece) {
    var otherPiece = "X";
    if (piece == "X") {
      otherPiece = "O";
    }
    humanPiece = piece;
    aiPiece = otherPiece;
    $("#choose" + piece).addClass("selected");
    $("#choose" + otherPiece).removeClass("selected");
    updateFeedbackText("Player chose " + piece + ". Game starting.");
    beginGame();
  }
  
  function updateScores() {
    $("#human-score").html(humanScore);
    $("#ai-score").html(aiScore);
    $("#tie-score").html(tieScore);
  }
  
  function resetBoard() {
    $("#chooseX").removeClass("selected");
    $("#chooseO").removeClass("selected");
    var humanPiece = "";
    var aiPiece = "";
  }
  
  function checkForTie() {
    if (gameboard.indexOf(" ") == -1) {
      playing = false;
      updateFeedbackText("It's a tie.");
      tieScore = tieScore + 1;
      updateScores();
      resetBoard();
    }
  }
  
  function computerTurn() {
    // check for win
    if (checkForWin(humanPiece)) {
      humanScore = humanScore + 1;
      updateScores();
      playing = false;
      console.log("You won!");
      updateFeedbackText("You won!");
      resetBoard();
    }
    
    if (playing) {
      checkForTie();
    }
    
    // calculate move and update board
    if (playing) {
      computerMove();
    }
    
  }
  
  function compBox() {
    var rowArray = [];
    
    // check last move
    var gameboardJoin = gameboard.join("");
    if (gameboardJoin.search(lastBox) == 0) {
      console.log("Last place to move.");
      return gameboardJoin.indexOf(" ");
    }
    
    // check for potential computer wins
    for (var i = 0; i < winArray.length; i++) {
      for (var j = 0; j < winArray[i].length; j++) {
        rowArray.push(gameboard[winArray[i][j]]);
      }
      var rowArrayJoin = rowArray.join("");
      var regex = (aiPiece == "O") ? potWinO : potWinX;
      if (rowArrayJoin.search(regex) == 0) {
        console.log("Potential computer win found!");
        return winArray[i][rowArrayJoin.indexOf(" ")];
      }
      rowArray.length = 0;
    }
    
    // check for potential player wins
    for (i = 0; i < winArray.length; i++) {
      for (j = 0; j < winArray[i].length; j++) {
        rowArray.push(gameboard[winArray[i][j]]);
      }
      rowArrayJoin = rowArray.join("");
      regex = (aiPiece == "O") ? potWinX : potWinO;
      if (rowArrayJoin.search(regex) == 0) {
        console.log("Potential player win found!");
        console.log("move location:", winArray[i][rowArrayJoin.indexOf(" ")]);
        return winArray[i][rowArrayJoin.indexOf(" ")];
      }
      rowArray.length = 0;
    }
    
    // check for open row
    for (i = 0; i < winArray.length; i++) {
      for (j = 0; j < winArray[i].length; j++) {
        rowArray.push(gameboard[winArray[i][j]]);
      }
      console.log("checking open rows");
      rowArrayJoin = rowArray.join("");
      regex = (aiPiece == "O") ? openO : openX;
      if (rowArrayJoin.search(regex) == 0) {
        console.log("Open row found!");
        var bestMove = (rowArrayJoin.lastIndexOf(" ") == 1) ? winArray[i][rowArrayJoin.indexOf(" ")] : winArray[i][rowArrayJoin.lastIndexOf(" ")];
        return bestMove;
      }
      rowArray.length = 0;
    }
    
    if (difficulty == 3) {
      var goodMoves = [0, 2, 4, 6];
      return goodMoves[Math.floor(Math.random() * 4)];
    } else {
      return Math.floor(Math.random() * 9)
    }
  }
  
  function computerMove() {
    var feedback = "Thinking";
    var myInterval = setInterval(function() {
      // potential move is chosen
      var chosenBox;
      switch (difficulty) {
        case 1:
          chosenBox = Math.floor(Math.random() * 9);
          break;
        case 2:
        case 3:
          chosenBox = compBox();
          break;
      }
      console.log("chosenBox", chosenBox);
      
      // check if potential box is empty
      if (gameboard[chosenBox] === " ") {
        $("#box" + chosenBox).html("<h1 class='giant'>" + aiPiece + "</h1>");
        updateFeedbackText("");
        gameboard[chosenBox] = aiPiece;
        clearInterval(myInterval);
        // check for win
        if (checkForWin(aiPiece)) {
          aiScore = aiScore + 1;
          updateScores();
          playing = false;
          updateFeedbackText("I won!");
          resetBoard();
        } 
        if (playing) {
          checkForTie();
        }
        if (playing) {
          playerTurn = true;
        }
      } else {
        feedback = feedback + ".";
        updateFeedbackText(feedback);
      }      
    }, 2000 * time);
  }
  
  function checkForWin(piece) {
    var rowArray = [];
    for (var i = 0; i < winArray.length; i++) {
      for (var j = 0; j < winArray[i].length; j++) {
        rowArray.push(gameboard[winArray[i][j]]);
      }
      var rowArrayJoin = rowArray.join("");
      var regex = regexX;
      if (piece == "O") {
        regex = regexO;
      }
      if (rowArrayJoin.search(regex) == 0) {
        console.log("Win found!");
        return true;
      }
      rowArray.length = 0;
    }
    return false;
  }
  
  function beginGame() {
    playing = true;
    generateBoard();
    clearBoard();
    var i = 0;
    var myInterval = setInterval(function() {
      if (i > 0) {
        clearInterval(myInterval);
        if (humanPiece == "X") {
          updateFeedbackText("Your turn!");
          playerTurn = true;
        } else {
          updateFeedbackText("My turn...");
          computerTurn();
        }
      }
      i++;
    }, 1000);    
  }
  
  // tips
  (function tipStart() {
    $("#tipText").html(tips[0]);

    function rotateTip() {
      // #tipText for tip div
      $("#tipText").html(getNextTip($("#tipText").html()));
    }

    (function rotateTips() {
      setInterval(function() {rotateTip();}, 10000);    
    })();

    function getNextTip(lastTip) {
    // return the next tip
    var lastTipIndex = tips.indexOf(lastTip);
    var nextTipIndex = (lastTipIndex == (tips.length - 1) || lastTipIndex == -1) ? 0 : lastTipIndex + 1;
    return tips[nextTipIndex];
  }
  })();
  
});


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

Console