css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

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.

            
              <body>
<div class="board">
  <div id="btn1" class="square">
  </div>
  <div id="btn2" class="square">
  </div>
  <div id="btn3" class="square">
  </div>

  <div id="btn4" class="square">
  </div>
  <div id="btn5" class="square">
  </div>
  <div id="btn6" class="square">
  </div>

  <div id="btn7" class="square">
  </div>
  <div id="btn8" class="square">
  </div>
  <div id="btn9" class="square">
  </div>
</div>

<div class="overlay"></div>

<div class="modal">
  <h2 style="margin-bottom: 20px"> Pick your side: </h2>
  <img id="xImg" src="https://raw.githubusercontent.com/GreatDanton/TicTacToe/gh-pages/x.png">
  <img id="oImg" src="https://raw.githubusercontent.com/GreatDanton/TicTacToe/gh-pages/o.png">
</div>

<div class="info"></div>
<button class="button" id="new-game">New Game </button>

</body>
</html>

            
          
!
            
              * {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Open Sans', sans-serif;
}

.board {
  min-width: 300px;
  max-width: 302px;
  margin: 50px auto;
  display: flex;
  flex-flow: row;
  flex-wrap: wrap;
}

.square {
  border: 1px solid #ccc;
  min-width: 100px;
  min-height: 100px;
  max-width: 100px;
  max-height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
/* removes selection around the image */
  -webkit-user-select: none;  /* Chrome all / Safari all */
   -moz-user-select: none;     /* Firefox all */
   -ms-user-select: none;      /* IE 10+ */
   user-select: none;
}

.square:hover {
  background: #eee;
  cursor: pointer;
}

.disabled {
  pointer-events: none;
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  opacity: 0.5;
  background: #000;
  min-width: 100%;
  min-height: 100vh;
  z-index: 1;
}

.modal {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
  background: #fff;
  min-width: 400px;
  max-width: 400px;
  text-align: center;
  margin: 0 auto;
  padding: 20px;
  z-index: 2;
  box-shadow: 0px 0px 10px rgba(0,0,0,0.3);
}

.modal img {
  padding: 20px;
  border: 2px solid transparent;
  transition: 0.4s ease;
}

.modal img:hover {
  border: 2px solid #222;
  background: #dedede;
  cursor: pointer;
}

.info {
  text-align: center;
  font-size: 20px;
}

.button {
  border: 0;
  min-height: 48px;
  padding: 0 20px;
  background-color: #ccc;
  margin: 20px auto 0 auto;
  display: flex;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
}

.button:hover {
  box-shadow: 0 0 10px rgba(0,0,0, 0.3);
}



/* ############### DEFINING GRID ###############*/

#btn1 {
  border-right: 2px solid #000;
  border-bottom: 2px solid #000;
}

#btn2 {
  border-left: 2px solid #000;
  border-bottom: 2px solid #000;
  border-right: 2px solid #000;
}

#btn3 {
  border-left: 2px solid #000;
  border-bottom: 2px solid #000;
}

#btn4 {
  border-top: 2px solid #000;
  border-bottom: 2px solid #000;
  border-right: 2px solid #000;
}

#btn5 {
  border: 2px solid #000;
}

#btn6 {
  border-top: 2px solid #000;
  border-bottom: 2px solid #000;
  border-left: 2px solid #000;
}

#btn7 {
  border-top: 2px solid #000;
  border-right: 2px solid #000;
}

#btn8 {
  border-top: 2px solid #000;
  border-left: 2px solid #000;
  border-right: 2px solid #000;
}

#btn9 {
  border-top: 2px solid #000;
  border-left: 2px solid #000;
}

            
          
!
            
              $(document).ready(function() {

// ##################   VARIABLES #####################
  var imgO = 'https://raw.githubusercontent.com/GreatDanton/TicTacToe/gh-pages/o.png';
  var imgX = 'https://raw.githubusercontent.com/GreatDanton/TicTacToe/gh-pages/x.png';
  var selected;
  var comp;
  var userMoves = [];
  var computerMoves = [];
  var allMoves = [1,2,3,4,5,6,7,8,9];
  var choices;
  var notAllowedMoves = [];
  var corners = [1,3,7,9];
  var winningMoves = [[2,5,8], [4,5,6], [1,2,3], [7,8,9], [1, 4, 7], [3,6,9], [1,5,9], [3, 5, 7]];



// ################# FUNCTIONS ########################
// AI move

// function for displaying moves.
function move(currentCompMove) {
  computerMoves.push(parseInt(currentCompMove));
  notAllowedMoves.push(parseInt(currentCompMove));
  $('#btn' + currentCompMove).append('<img class="no-select" src="'+ comp + '"/>');
  $('#btn' + currentCompMove).addClass('disabled');
}

function filter(tempArr, i) {
    var arr = winningMoves[i].filter(function(item){
      return tempArr.indexOf(item) === -1;
    });
    return arr;
}

// ############### PLAY FUNCTION ##############
function play() {
  var tempMove;
    // which choices AI has
    choices = allMoves.filter(function(el) {
      return notAllowedMoves.indexOf(el) < 0;
    });
    var check = notAllowedMoves.join('');
    switch (true) {

      case computerMoves.length === 0 && selected === imgO:
        var options = [1,3,7,9,5];
        aiMove = options[Math.floor(Math.random() * options.length)];
        move(aiMove);
      break;

      case computerMoves.length === 0:
          if ('5'.indexOf(userMoves[0]) == -1) {
            aiMove = 5;
          } else {
            aiMove = corners[Math.floor(Math.random() * 4)];
          }
          move(aiMove);
      break;

      case computerMoves.length == 1:
      // loop through winning Moves => block it or prevent bla bla;
      // if user got two in a row
      aiMove = 0; // resets aiMove
      for (i = 0; i < winningMoves.length; i++) {
        tempMove = filter(userMoves, i);
        if (tempMove.length == 1 && choices.join('').indexOf(tempMove) > -1) {
          aiMove = tempMove;
          move(aiMove);
          break;
        }
      }
      // if user doesnt have two in a row:
      if (aiMove === 0) {
        // loop through possible moves
        //console.log('I AM HERE');
        for (i = 0; i < winningMoves.length; i++) {
          // remove computer moves from winningMove[i] and check if boxes are free.
          tempMove = filter(computerMoves, i);
          if (tempMove.length == 2 && check.indexOf(tempMove[0]) == -1 && check.indexOf(tempMove[1]) == -1) {
            if (userMoves[1] == 2 || userMoves[1] == 4) {
              aiMove = tempMove[0];
            } else if (userMoves[1] == 7 || userMoves[1] == 1) {
              aiMove = tempMove[0];
            } else {
              aiMove = tempMove[1];
            }
            move(aiMove);
            break;
          }
        }
      }
      break;

      case computerMoves.length > 1:
      var aiMove = 0;
        // check if AI can win?
      aiCombinations = k_combinations(computerMoves, 2);
      for (i = 0; i< winningMoves.length; i++) {
        for (j = 0; j < aiCombinations.length; j++) {
          tempMove = filter(aiCombinations[j], i);
          if (tempMove.length == 1 && check.indexOf(tempMove) == -1) {
            aiMove = tempMove;
            move(aiMove[0]);
            break;
          }
        }
      } // end of for loop
      // if AI can't win:

      if (aiMove === 0) {
        var userCombinations = k_combinations(userMoves, 2);
        for (i = 0; i < winningMoves.length; i++) {
          for (j = 0; j <userCombinations.length; j++) {
            tempMove = filter(userCombinations[j], i);
            if (tempMove.length == 1 && check.indexOf(tempMove) == -1) {
              aiMove = tempMove[0];
              move(aiMove);
              return;
            }
          }
        }
        aiMove = 20;
      }
      if (aiMove == 20) {
        //console.log('stopped here');
        aiMove = choices[Math.floor(Math.random() * choices.length)];
        move(aiMove);
      }
      break;
      default:
        break;
    }
} // end of function play

// function to make combinations (took from internet)
function k_combinations(set, k) {
	var i, j, combs, head, tailcombs;
	if (k > set.length || k <= 0) {
		return [];
	}
	if (k == set.length) {
		return [set];
	}
	if (k == 1) {
		combs = [];
		for (i = 0; i < set.length; i++) {
			combs.push([set[i]]);
		}
		return combs;
	}
	// Assert {1 < k < set.length}
	combs = [];
	for (i = 0; i < set.length - k + 1; i++) {
		head = set.slice(i, i+1);
		tailcombs = k_combinations(set.slice(i + 1), k - 1);
		for (j = 0; j < tailcombs.length; j++) {
			combs.push(head.concat(tailcombs[j]));
		}
	}
	return combs;
}
// end of combinations

// checks if your moves are in winning moves
function state(userMoves) {
  // create combinations from user presses and check if user got a wining combination
  var userCombs = k_combinations(userMoves, 3);
    for (j = 0; j < userCombs.length; j++) {
      userCombs[j].sort(function(a,b) {
        return a - b;
      });
      for (i = 0; i < winningMoves.length; i++) {
      if (userCombs[j][0] == winningMoves[i][0] && userCombs[j][1] == winningMoves[i][1] && userCombs[j][2] == winningMoves[i][2]) {
        $('.square').addClass('disabled');
        return 'won';
      }
    }
  }
}
// end of state
// ##################### END OF FUNCTIONS ######################

// ##################### PICKING SIDE ###################

$('#xImg').click(function() {
  selected = imgX;
  comp = imgO;
  $('.modal').fadeOut(500);
  $('.overlay').fadeOut(350);
  gameOver = false;
});

$('#oImg').click(function() {
  selected = imgO;
  comp = imgX;
  $('.modal').fadeOut(500);
  $('.overlay').fadeOut(350);
  gameOver = false;
  play();
});

// ############## GAME ##################
$('.square').click(function() {
 if (selected == imgX) {
// X is first, AI plays when .squared is clicked;
     $(this).append('<img class="no-select" src="'+ selected + '"/>');
     $(this).addClass('disabled');

     // get id of the clicked square and return last number
     var move = $(this).attr('id');
     // get number of
     move = move.substr(move.length - 1);
     userMoves.push(parseInt(move));
     notAllowedMoves.push(parseInt(move));

     if (state(userMoves) == 'won') {
       $('.info').html('You won the game');
       return;
     }

       // AI should wait for your first move
       if (userMoves.length > computerMoves.length){
       // pick random number of the left moves and append picture at that position.
         play();
         if (state(computerMoves) == 'won') {
           $('.info').html('You lost the game');
           return;
         }
       } // end of usermoves if

     // if the game is not over, its a draw!
     if (notAllowedMoves.length >= 9){
       $('.info').html("it's a draw!");
       return;
     }
     // ################### PICK O #####################
 } else if (selected == imgO) {
     $(this).append('<img class="no-select" src="'+ selected + '"/>');
     $(this).addClass('disabled');
     // get id of the clicked square and return last number
     var move = $(this).attr('id');
     // get number of
     move = move.substr(move.length - 1);
     userMoves.push(parseInt(move));
     notAllowedMoves.push(parseInt(move));
     if (state(userMoves) == 'won') {
       $('.info').html('You won the game');
       return;
     }
// computer move
     play();
     if (state(computerMoves) == 'won') {
       $('.info').html('You lost the game');
       return;
     }

     if (notAllowedMoves.length >= 9){
       $('.info').html("It's a draw!");
       return;
     }
 }
});

// clean the board and pick your side
  $('#new-game').click(function(){
    computerMoves = [];
    userMoves = [];
    notAllowedMoves = [];
    choices = [];
    currentCompMove = 0;
    tempMove = 0;
    tempArr = [];
    $('.square').html('');
    $('.square').removeClass('disabled');
    $('.info').html('');
    $('.modal').fadeIn(350);
    $('.overlay').fadeIn(350);
  });
});
            
          
!
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