Tic Tac Toe

In this example below you will see how to do a Tic Tac Toe with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by LindseyMaddox, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright LindseyMaddox ©
  • HTML
  • CSS
  • JavaScript
    <div class="container">
  </br>
    <div class="row">
      <div id = "start-message" class="col-7 offset-3">
        <div class="row">
          Tic Tac Toe....X or O?
        </div>
           </br>      
        <div class="row selection">
          <button class="btn btn-info x">X</button>
          <button class="btn btn-info o">O</button>
        </div>
      </div>
      <div id="end-message" class="col-7 offset-3">
        <div class="row" id = "computer-win">Computer wins! Choose your letter for the next game.
        </div>
        <div class="row" id =  "draw">It's a tie! Choose your letter for the next game.
        </div>
        </br>      
      <div class="row">
        <div class="col-6 offset-1 new-game-selection">
          <button class="btn btn-info x" >X</button>
          <button class="btn btn-info o">O</button>
        </div>
      </div>
  </div>
  <div class="col-6 offset-3 game">
    <div class="row">
      <div class="col-2 offset-1 box rb top ltcol dg" id = "1"></div>
      <div class="col-2 box rb top mdcol" id = "2"></div>
      <div class="col-2 box top rtcol dg" id = "3"></div>
    </div>
    <div class="row">
      <div class="col-2 offset-1 box rb mid ltcol" id = "4"></div>
      <div class="col-2 box rb mid mdcol dg" id = "5"></div>
      <div class="col-2 box mid rtcol" id = "6"></div>
    </div>
    <div class="row">
      <div class="col-2 offset-1 box rb bot ltcol dg" id = "7"></div>
      <div class="col-2 box rb bot mdcol" id = "8"></div>
      <div class="col-2 box bot rtcol dg" id = "9"></div>
     </div>
    </div>
</div>

/*Downloaded from https://www.codeseek.co/LindseyMaddox/tic-tac-toe-ZQVMPZ */
    .game {
   display: none; 
  padding-top: 30px;
}
.box{
  text-align: center;
  font-size: 20px;
  height: 40px;
  width: 100px;
}

.rb {
  border-right: 1px solid black;
}
.top, .mid {
  border-bottom: 1px solid black;
}

#start-message {
  text-align: center;
  font-size: 20px;
}
#end-message {
  text-align: center;
  font-size: 16px;
  display: none;
}

.selection {
  margin-left: 15px;
}
.new-game-selection {
  margin-left: -15px;
}
.btn-info {
  margin-right: 20px;
}


/*Downloaded from https://www.codeseek.co/LindseyMaddox/tic-tac-toe-ZQVMPZ */
    $(document).ready(function(){
  var compVal;
  var userVal;

  var acceptedStarts = ["1", "3", "5", "7", "9"];
  var win;
  var block;
  var remainingSpaces = ["1","2", "3","4","5","6", "7", "8", "9"];
  var corners = ["1", "3", "7", "9"];
  var classes = ["top", "mid", "bot", "rtcol", "ltcol", "mdcol", "dg"];
  var start; 
  var cur;
  var curId;
  var curCompVal;
  var curUserVal;
 var lastUserVal = ""; 
  var lastCompVal = "";
  var secUserVal = "";
  var secCompVal = "";
  var initUserVal = "";
  var initCompVal = "";
 var movesPlayed = [];
  var userPlays = 0;
  var center;
  var corner;
   var idxToSpliceCompVal;
  var idxToSpliceUserVal;
  
  $('.box').on('click', function(){
     console.log("box was clicked");
     cur = $(this);
 
 if(cur.html() == ""){ 
      gameSequence();
 }
  });
  function gameSequence(){
    cur.html(userVal);
    //get tne id of the div for the user val
    curId = cur.attr('id');
    userPlays += 1;
    win = true;
    idxToSpliceUserVal = remainingSpaces.indexOf(curId);
    remainingSpaces.splice(idxToSpliceUserVal, 1);
    if (userPlays == 1) {
      secondCompPlay();
    } else {
      fifthAndBeyondPlays();
    }
}
    function secondCompPlay() {
      movesPlayed.push(curId);
 
      if(start == "1" && curId == "5"){
        $("#9").html(compVal);
        movesPlayed.push("9");
        idxToSpliceCompVal = remainingSpaces.indexOf("9");  
        remainingSpaces.splice(idxToSpliceCompVal,1);
      } else if(start == "3" && curId == "5"){
        $("#7").html(compVal);
        movesPlayed.push("7");
        idxToSpliceCompVal = remainingSpaces.indexOf("7");  
        remainingSpaces.splice(idxToSpliceCompVal,1);
      } else if(start == "7" && curId == "5"){
        $("#3").html(compVal);
        movesPlayed.push("3");
        idxToSpliceCompVal = remainingSpaces.indexOf("3");  
        remainingSpaces.splice(idxToSpliceCompVal,1);
      } else if(start == "9" && curId == "5"){
        $("#1").html(compVal);
        movesPlayed.push("1");
        idxToSpliceCompVal = remainingSpaces.indexOf("1");  
        remainingSpaces.splice(idxToSpliceCompVal,1);
      }   

      if(start == "1" || start == "7" || start == "3" || start == "9"){
        if(curId == "4" || curId == "6" || curId == "2" || curId == "8" ){
            $("#5").html(compVal);
            movesPlayed.push("5");
            idxToSpliceCompVal =        remainingSpaces.indexOf("5");  
            remainingSpaces.splice(idxToSpliceCompVal,1);
          } else if(curId == "1" || curId == "3" || curId == "7" || curId == "9"){
             idxToSpliceCompVal = corners.indexOf(start); 
             corners.splice(idxToSpliceCompVal, 1);
                         idxToSpliceUserVal = corners.indexOf(curId); 
             corners.splice(idxToSpliceUserVal,1);
             var randCorn = corners[Math.floor(Math.random() * corners.length)];
             $('#' + randCorn).html(compVal); 
             movesPlayed.push(randCorn);

             idxToSpliceCompVal = remainingSpaces.indexOf(randCorn);  
            remainingSpaces.splice(idxToSpliceCompVal,1);
          }
      }
      
    if(start == "5"){
       if(curId == "8" || curId == "2") {
                  var randCorn = corners[Math.floor(Math.random() * corners.length)];
                  $("#" + randCorn).html(compVal);    
                  movesPlayed.push(randCorn);
                  idxToSpliceCompVal = remainingSpaces.indexOf(randCorn);  
                  remainingSpaces.splice(idxToSpliceCompVal,1);
          } else if(curId == "1"){
                  $('#9').html(compVal);
                   movesPlayed.push("9");
                   idxToSpliceCompVal = remainingSpaces.indexOf("9");  
                   remainingSpaces.splice(idxToSpliceCompVal,1);
          } else if(curId == "3"){
                        $('#7').html(compVal);
                         movesPlayed.push("7");
                         idxToSpliceCompVal = remainingSpaces.indexOf("7");  
                         remainingSpaces.splice(idxToSpliceCompVal,1);
          } else if(curId == "7" || curId == "6"){
                        $('#3').html(compVal);
                        movesPlayed.push("3");
                        idxToSpliceCompVal = remainingSpaces.indexOf("3");  
                        remainingSpaces.splice(idxToSpliceCompVal,1);
          } else if(curId = "4" || curId == "9"){
                        $('#1').html(compVal);
                        movesPlayed.push("1");
                        idxToSpliceCompVal = remainingSpaces.indexOf("1");  
                        remainingSpaces.splice(idxToSpliceCompVal,1);
          } 
        }
      } 
      
      function fifthAndBeyondPlays(){
       movesPlayed.push(curId);
       
       curUserVal =  parseInt(curId);
       curCompVal =  parseInt(movesPlayed[(movesPlayed.length-2)]);
       lastUserVal = parseInt(movesPlayed[(movesPlayed.length-3)]);
       lastCompVal = parseInt(movesPlayed[(movesPlayed.length-4)]);
       secUserVal =  parseInt(movesPlayed[(movesPlayed.length-5)]);
       secCompVal =  parseInt(movesPlayed[(movesPlayed.length-6)]);
       initUserVal = parseInt(movesPlayed[(movesPlayed.length-7)]);
       initCompVal = parseInt(movesPlayed[(movesPlayed.length-8)]);
      
      if(win == true){;
         winSequence();
        } 
        if (win != true && userPlays < 4){
          blockSequence();
        } else if (win != true && userPlays == 4){
          drawSequence();
        } 
        if (win != true && block != true){
          centerSequence();
        } 
        if (win != true && block != true && center != true){
          cornerSequence();
        } 
        if (win != true && block != true && center != true && corner != true){
          remainingSpaceSequence();
        }
      }

      function winSequence(){
        win = false; // until proven otherwise
        for(j = 0; j< remainingSpaces.length; j++){
          for(c=0; c < classes.length; c++){
            if($("#" + remainingSpaces[j]).hasClass(classes[c]) && classes[c] != "dg"){
              if($("#" + curCompVal).hasClass(classes[c]) && $("#" + lastCompVal).hasClass(classes[c])){
                $("#" + remainingSpaces[j]).html(compVal);
                winScreen();
              } else if($("#" + curCompVal).hasClass(classes[c]) && $("#" + secCompVal).hasClass(classes[c]) && userPlays > 2){
                $("#" + remainingSpaces[j]).html(compVal);
                winScreen();
              } else if($("#" + curCompVal).hasClass(classes[c]) && $("#" + initCompVal).hasClass(classes[c]) && userPlays > 3){
                $("#" + remainingSpaces[j]).html(compVal);
                winScreen();
              } else if($("#" + lastCompVal).hasClass(classes[c]) && $("#" + secCompVal).hasClass(classes[c]) && userPlays > 2){
               $("#" + remainingSpaces[j]).html(compVal);
                winScreen();
              } else if($("#" + lastCompVal).hasClass(classes[c]) && $("#" + initCompVal).hasClass(classes[c]) && userPlays > 3){
                $("#" + remainingSpaces[j]).html(compVal);
                winScreen();
              } else if($("#" + secCompVal).hasClass(classes[c]) && $("#" + initCompVal).hasClass(classes[c]) && userPlays > 3){
                $("#" + remainingSpaces[j]).html(compVal);
                winScreen();
              } 
            } else if($("#" + remainingSpaces[j]).hasClass(classes[c]) && classes[c] == "dg"){  
              if($("#" + curCompVal).hasClass(classes[c]) && $("#" + lastCompVal).hasClass(classes[c]) && curCompVal + lastCompVal + parseInt(remainingSpaces[j]) == 15) {
                $("#" + remainingSpaces[j]).html(compVal);
                winScreen();
              } else  if($("#" + curCompVal).hasClass(classes[c]) && $("#" + secCompVal).hasClass(classes[c]) && userPlays > 2 && curCompVal + secCompVal + parseInt(remainingSpaces[j]) == 15) {
                $("#" + remainingSpaces[j]).html(compVal);
                winScreen();
            } else if($("#" + curCompVal).hasClass(classes[c]) && $("#" + initCompVal).hasClass(classes[c]) && userPlays > 3 && curCompVal + initCompVal + parseInt(remainingSpaces[j]) == 15) {
                $("#" + remainingSpaces[j]).html(compVal);
                winScreen();
            } else if($("#" + lastCompVal).hasClass(classes[c]) && $("#" + secCompVal).hasClass(classes[c]) && userPlays > 2 && lastCompVal + secCompVal + parseInt(remainingSpaces[j]) == 15) {
                $("#" + remainingSpaces[j]).html(compVal);
                winScreen();
            } else if($("#" + lastCompVal).hasClass(classes[c]) && $("#" + initCompVal).hasClass(classes[c]) && userPlays > 3 && lastCompVal + initCompVal + parseInt(remainingSpaces[j]) == 15) {
                $("#" + remainingSpaces[j]).html(compVal);
                winScreen();
            } else if($("#" + secCompVal).hasClass(classes[c]) && $("#" + initCompVal).hasClass(classes[c]) && userPlays > 3 && secCompVal + initCompVal + parseInt(remainingSpaces[j]) == 15) {
                $("#" + remainingSpaces[j]).html(compVal);
                winScreen();
            }
          }   
        }
      }
   }   

   function drawSequence() {
         $("#" + remainingSpaces[0]).html(compVal);
        movesPlayed.push(remainingSpaces[0]);
        remainingSpaces.splice(0,1);
         draw();
}
    function blockSequence() {
       block = false; // until proven otherwise
        for(i = 0; i< remainingSpaces.length; i++){
          for(x=0; x < classes.length; x++){
            if($("#"+remainingSpaces[i]).hasClass(classes[x]) && classes[x] != "dg"){
              if($("#" + curUserVal).hasClass(classes[x]) && $("#" + lastUserVal).hasClass(classes[x])){
                $("#" + remainingSpaces[i]).html(compVal);
                movesPlayed.push(remainingSpaces[i]);
                remainingSpaces.splice(i,1);
                block = true;
                break;
              } else if($("#" + curUserVal).hasClass(classes[x]) && $("#" + secUserVal).hasClass(classes[x]) && userPlays > 2){
                $("#" + remainingSpaces[i]).html(compVal);
                movesPlayed.push(remainingSpaces[i]);
                remainingSpaces.splice(i,1);
                block = true;
                break;
              } else if($("#" + curUserVal).hasClass(classes[x]) && $("#" + initUserVal).hasClass(classes[x]) && userPlays > 3){
                $("#" + remainingSpaces[i]).html(compVal);
                movesPlayed.push(remainingSpaces[i]);
                remainingSpaces.splice(i,1);
                block = true;
                break;
              } else if($("#" + lastUserVal).hasClass(classes[x]) && $("#" + secUserVal).hasClass(classes[x]) && userPlays > 2){
                $("#" + remainingSpaces[i]).html(compVal);
                movesPlayed.push(remainingSpaces[i]);
                remainingSpaces.splice(i,1);
                block = true;
                break;
              } else if($("#" + lastUserVal).hasClass(classes[x]) && $("#" + initUserVal).hasClass(classes[x]) && userPlays > 3){
                $("#" + remainingSpaces[i]).html(compVal);
                movesPlayed.push(remainingSpaces[i]);
                remainingSpaces.splice(i,1);
                block = true;
                break;
              } else if($("#" + secUserVal).hasClass(classes[x]) && $("#" + initUserVal).hasClass(classes[x]) && userPlays > 3){
                $("#" + remainingSpaces[i]).html(compVal);
                movesPlayed.push(remainingSpaces[i]);
                remainingSpaces.splice(i,1);
                block = true;
                break;
              }
            } else if ($("#"+remainingSpaces[i]).hasClass(classes[x]) && classes[x] == "dg"){
              if($("#" + curUserVal).hasClass(classes[x]) && $("#" + lastUserVal).hasClass(classes[x]) && curUserVal + lastUserVal + parseInt(remainingSpaces[i]) == 15){
                $("#" + remainingSpaces[i]).html(compVal);
                movesPlayed.push(remainingSpaces[i]);
                remainingSpaces.splice(i,1);
                block = true;
                break;
              } else if($("#" + curUserVal).hasClass(classes[x]) && $("#" + secUserVal).hasClass(classes[x]) && userPlays > 2 && curUserVal + secUserVal + parseInt(remainingSpaces[i]) == 15){
                $("#" + remainingSpaces[i]).html(compVal);
                movesPlayed.push(remainingSpaces[i]);
                remainingSpaces.splice(i,1);
                block = true;
                break;
              } else if($("#" + curUserVal).hasClass(classes[x]) && $("#" + initUserVal).hasClass(classes[x]) && userPlays > 3 && curUserVal + initUserVal + parseInt(remainingSpaces[i]) == 15){
                $("#" + remainingSpaces[i]).html(compVal);
                movesPlayed.push(remainingSpaces[i]);
                remainingSpaces.splice(i,1);
                block = true;
                break;
              } else if($("#" + lastUserVal).hasClass(classes[x]) && $("#" + secUserVal).hasClass(classes[x]) && userPlays > 2 && lastUserVal + secUserVal + parseInt(remainingSpaces[i]) == 15){
                $("#" + remainingSpaces[i]).html(compVal);
                movesPlayed.push(remainingSpaces[i]);
                remainingSpaces.splice(i,1);
                block = true;
                break;
              } else if($("#" + lastUserVal).hasClass(classes[x]) && $("#" + initUserVal).hasClass(classes[x]) && userPlays > 3 && lastUserVal + initUserVal + parseInt(remainingSpaces[i]) == 15){
                $("#" + remainingSpaces[i]).html(compVal);
                movesPlayed.push(remainingSpaces[i]);
                remainingSpaces.splice(i,1);
                block = true;
                break;
              } else if($("#" + secUserVal).hasClass(classes[x]) && $("#" + initUserVal).hasClass(classes[x]) && userPlays > 3 && secUserVal + initUserVal + parseInt(remainingSpaces[i]) == 15){
                $("#" + remainingSpaces[i]).html(compVal);
                movesPlayed.push(remainingSpaces[i]);
                remainingSpaces.splice(i,1);
                block = true;
                break;
              } //interior if/else
            } // exterior if/else
          } // interior for loop
        }    //exterior for loop 
    } //end of function
   

    function centerSequence(){
      for(ctr = 0; ctr < remainingSpaces.length; ctr++){
        center = false; //until proven otherwise
        if(remainingSpaces[ctr] == "5"){
          $("#5").html(compVal);
          center = true;
          movesPlayed.push("5");
          remainingSpaces.splice(ctr,1);
          break;
        }
      }
    }
      function cornerSequence(){ 
        corner = false; //until proven otherwise
        for(crn = 0; crn < remainingSpaces.length; crn++){
          if(remainingSpaces[crn] == "1" || remainingSpaces[crn] == "3" || remainingSpaces[crn] == "7" || remainingSpaces[crn] == "9"){
            $("#" + remainingSpaces[crn]).html(compVal);
            movesPlayed.push(remainingSpaces[crn]);
            remainingSpaces.splice(crn,1);
            corner = true;
            break;
          }
        }
      } 
      function remainingSpaceSequence(){
        $("#" + remainingSpaces[0]).html(compVal);
        movesPlayed.push(remainingSpaces[0]);
        remainingSpaces.splice(0,1);
      }
    
function winScreen(){
  win = true;
  intervalVar = setInterval(winOrDraw,1500);
  $("#draw").hide();
  $("#computer-win").show();
}
  function draw(){
     intervalVar = setInterval(winOrDraw,1500);
    $("#draw").show();
  $("#computer-win").hide();
}

  function winOrDraw(){
      for(s=0; s< 10; s++){
      $("#" + s).html("");
}
    clearInterval(intervalVar);
    //reset any other variables needing reset  
  win = true;
  movesPlayed = [];
  remainingSpaces = ["1","2", "3","4","5","6", "7", "8", "9"];
  corners = ["1", "3", "7", "9"];
  userPlays = 0;
  $('.game').hide();
$("#end-message").show();
}
    $(".x").on('click', function(){
      compVal = "o";
      userVal = "x";
      startGame();
    })
    
       $(".o").on('click', function(){
      compVal = "x";
      userVal = "o";
      startGame();
    })
 function startGame(){
    $("#end-message").hide();
    $("#start-message").hide();
    $('.game').show();

   start = acceptedStarts[Math.floor(Math.random() * acceptedStarts.length)];
 
    $("#" + start).html(compVal);
  movesPlayed.push(start);
  
    idxToSpliceCompVal = remainingSpaces.indexOf(start);
    remainingSpaces.splice(idxToSpliceCompVal,1);
  
  };
  });

Comments