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.

            
              <div class = "game">
  <span>Tic Tac Toe</span>
  <div class = "row">
    <div data-i=0 data-j=0 class = "col"></div>
    <div data-i=0 data-j=1 class = "col"></div>
    <div data-i=0 data-j=2 class = "col"></div>
  </div>
  <div class = "row">
    <div data-i=1 data-j=0 class = "col"></div>
    <div data-i=1 data-j=1 class = "col"></div>
    <div data-i=1 data-j=2 class = "col"></div>
  </div>
  <div class = "row">
    <div data-i=2 data-j=0 class = "col"></div>
    <div data-i=2 data-j=1 class = "col"></div>
    <div data-i=2 data-j=2 class = "col"></div>
  </div>
  <button id = "choose" class = "O">O</button>
  <button id = "restart">Choose</button>
  <button id = "choose" class = "X">X</button>
</div>
<div class="footer">
  by <a id = "me" href="https://codepen.io/MukeshAngrish" title="See my other projects"> Mukesh K. Angrish</a>
</div>
            
          
!
            
              body{
  background : #17191F;
  text-align : center;
}
.game{
  background : #FF6767;
  width : 320px;
  margin : 5% auto auto auto;
}
span{
  font-size : 3em;
  color : white;
}
.col{
  font-size : 80px;
  vertical-align: middle;
  display : inline-block;
  border : none;
  background : white;
  margin-top : 1px;
  margin-bottom : 3px;
  width : 100px;
  height : 100px;
}
#restart{
  width : 100px;
  font-size : 30px;
  height : 100px;
  margin : 10px;
  border-radius : 50%;
  padding : 0px;
  color : #FF6767;
  border : none;
  background : white;
}
#choose{
  border : none;
  font-size : 3em;
  height : 50px;
  width : 50px;
  background : none;
  color : white;
}
.hide{
  display : none;
}
.footer{
  position: relative;
  color: white;
  width: 300px;
  margin: 10px auto 10px auto;
  font-size: 30px;
}
#me{
  text-decoration: none;
  color: white;
  font-size: 1.1em;
}
            
          
!
            
              // default tokens
var playerToken = 'X';
var aiToken = 'O';
var winner = '';
$(document).ready(function() {
  // start win an empty grid
  var grid = [
    ['', '', ''],
    ['', '', ''],
    ['', '', ''],
  ];

  // hides X and O once selected and changes the restart button
  function hide() {
    $('.O, .X').addClass('hide');
    $('#restart').html('Restart');
  }

  // opposite of hide()
  function unhide() {
    $('.O, .X').removeClass('hide');
    $('#restart').html('Choose');
  }

  // checks if the game is over
  function isGameOver(grid) {
    // check win - horizontal and vertical
    for (var i = 0; i < 3; i++) {
      if (grid[i][0] != '' &&
         grid[i][0] == grid[i][1] &&
         grid[i][0] == grid[i][2])
        return grid[i][0];
      if (grid[0][i] != '' &&
         grid[0][i] == grid[1][i] &&
         grid[0][i] == grid[2][i])
        return grid[0][i];
    }

    // check win - diagonal top-left to bottom-right and bottom-left to top-right
    if ((grid[1][1] != '' &&
        grid[1][1] == grid[0][0] &&
        grid[1][1] == grid[2][2]) ||
       (grid[1][1] != '' &&
        grid[1][1] == grid[2][0] &&
        grid[1][1] == grid[0][2]))
      return grid[1][1];

    // if no one won, check for an empty space
    for (i = 0; i < 3; i++) {
      for (var j = 0; j < 3; j++) {
        if (grid[i][j] == '')
          return false;
      }
    }

    // if a tie happens
    return null;
  }

  function displayWinner(gameState) {
    if (gameState == playerToken)
      winner = 'Player Won';
    else if (gameState == aiToken)
      winner = 'AI Won';
    else
      winner = 'TIE';
    alert('Game Over : ' + winner);
    unhide();
    setTimeout(function () {
      for (var i = 0; i < 3; i++) {
        for (var j = 0; j < 3; j++) {
          grid[i][j] = '';
          $('.col[data-i=' + i + '][data-j=' + j + ']').html('');
        }
      }
      playerToken = 'X';
      aiToken = 'O';
    }, 300); 
  }

  function minmax(newGrid, depth, player) {
    var gameState = isGameOver(newGrid);
    if (gameState == false) { // if there is empty space
      var values = [];
      for (var i = 0; i < 3; i++) {
        for (var j = 0; j < 3; j++) {
          var gridCopy = _.cloneDeep(newGrid);
          if (gridCopy[i][j] !== '') continue;
          gridCopy[i][j] = player;
          var value = minmax(gridCopy, depth + 1,
            ((player === playerToken) ? aiToken : playerToken));
          values.push({
            cost: value,
            cell: {
              i: i,
              j: j,
            },
          });
        }
      }

      if (player == aiToken) {
        // get the max
        var max = _.maxBy(values, (v) => {
          return v.cost;
        });
        if (depth == 0) {
          return max.cell;
        } else {
          return max.cost;
        }
      } else {
        var min = _.minBy(values, (v) => {
          return v.cost;
        });
        if (depth == 0) {
          return min.cell;
        } else {
          return min.cost;
        }
      }
    } else if (gameState == null) {
      return 0;
    } else if (gameState == playerToken) {
      return depth - 10;
    } else if (gameState == aiToken) {
      return 10 - depth;
    }
  }

  function moveAI() {
    return minmax(grid, 0, aiToken);
  }

  $('.O').on('click', function () {
    playerToken = 'O';
    aiToken = 'X';
    hide();
    
    setTimeout(function() {
      //update grid with ai move
      grid[0][0] = aiToken;
      $('.col[data-i=0][data-j=0]').html(aiToken);
    }, 300);
    var gameState = isGameOver(grid);
    if (gameState || gameState == null) {
      displayWinner(gameState);
    }
  });

  $('.X').on('click', function () {
    playerToken = 'X';
    aiToken = 'O';
    hide();
  });

  $('#restart').on('click', function () {
    unhide();
    for (var i = 0; i < 3; i++) {
      for (var j = 0; j < 3; j++) {
        grid[i][j] = '';
        $('.col[data-i=' + i + '][data-j=' + j + ']').html('');
      }
    }
    playerToken = 'X';
    aiToken = 'O';
  });

  $('.col').on('click', function () {
    hide();

    //get the column and row no. at which user placed the token
    var i = $(this).data('i');
    var j = $(this).data('j');
    if (grid[i][j] == '') {
      //upgrade the grid
      grid[i][j] = playerToken;
      $(this).html(playerToken);

      //check if someone won the game
      var gameState = isGameOver(grid);
      if (gameState || gameState == null) {
        displayWinner(gameState);
      } else {
        var move = moveAI();
        
        
        setTimeout(function() {
          //update grid with ai move
          grid[move.i][move.j] = aiToken;
          $('.col[data-i=' + move.i + '][data-j=' + move.j + ']').html(aiToken);
        }, 300);

        //check if someone won the game
        gameState = isGameOver(grid);
        if (gameState || gameState == null) {
          displayWinner(gameState);
        }
      }
    }
  });
});

            
          
!
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