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.

            
              .container-fluid.text-center
  %h1.page-header Tic Tac Toe
  <br>
  %h2#heading Can you beat the Computer?
  <br>
  .row.clearfix.text-center
    .col-md-4.col-md-offset-4
      %table
        - (1...4).each do |i|
          %tr
            - (1...4).each do |i|
              %td.h1 
      <br>
      .row
        %button.btn.btn-default#new NEW GAME
      .row
        %br
        %h3#pick Pick X or O
        %button.btn.btn-default#playerOne
          %i.fa.fa-times
        %button.btn.btn-default#playerTwo
          %i.fa.fa-circle-o
  
            
          
!
            
              body {
  font-family: arial;
  background: #556d7c;
}

.page-header {
  font-size: 50px;
  font-family: "Lobster Two";
}

h2 {
  font-family: "Lobster Two";
}

table {
  width: 300px;
  margin: 0 auto;
  font-family:arial;
}

table td {
  width: 33.33%;
  height: 100px;
  position: relative;
  text-align:center;
  vertical-align:middle;
  
}

table tr:nth-child(1) td:nth-child(1) {
    border-bottom:2px solid #000;
    border-right:2px solid #000;
}

table tr:nth-child(1) td:nth-child(3) {
    border-bottom:2px solid #000;
    border-left:2px solid #000;
}

table tr:nth-child(3) td:nth-child(1) {
    border-top:2px solid #000;
    border-right:2px solid #000;
}

table tr:nth-child(3) td:nth-child(3) {
    border-top:2px solid #000;
    border-left:2px solid #000;
}

table tr:nth-child(2) td:nth-child(2) {
    border:2px solid #000;
}

button {
  margin: 1.5% 2% 0;
  font-family:arial;
}

#pick {
  font-family: "Lobster Two";
}

.winning {
  color: yellow;
}

            
          
!
            
              $(document).ready(function() {
  var position = [];
  var human, computer, currentPlayer, score, winning, end = false;

  // all the winning variations in tic tac toe
  var winningPositions = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ]

  // player object
  var Player = function(role, type) {
    this.role = role;
    this.type = type;
    this.play = function() {};
  }

  // assigns moves to the position array
  function move() {
    position = [].slice.call(document.querySelectorAll("td"));
    position = position.map((elem) => {
      return elem.innerText
    });
  }

  // check if player has won
  function checkWin(player, position) {
    return winningPositions.reduce(function(result, current) {
      if ((position[current[0]] == player.role && position[current[1]] == player.role && position[current[2]] == player.role)) {
        winning = current;
      }
      return result || (position[current[0]] == player.role && position[current[1]] == player.role && position[current[2]] == player.role);
    }, "");
  }

  // check if game is drawn
  function checkDraw() {
    return position.indexOf("") === -1 && checkWin(human, position) === false && checkWin(computer, position) === false;
  }

  //check result & provide feedback
  function checkResult(player, position) {
    if (checkWin(player, position)) {
      $("#heading").text(player.type + " Wins!");
      $("#heading").css('color', 'red');
      for (var i=0; i < 3; i++) $("td").eq(winning[i]).addClass('winning');
      end = true;
      setTimeout(
        function() {
          reset();
        }, 2000);
      //
    } else if (checkDraw()) {
      $("#heading").text("You draw!");
      $("#heading").css('color', 'red');
      end = true;
      setTimeout(
        function() {
          reset();
        }, 2000);
    }
  }

  //reset the board
  function reset() {
    $("td").text("");
    position = [];
    $("#heading").text("Can you beat the Computer?");
    $("#pick").text("Pick X or O");
    $("#playerOne").css('color', 'black');
    $("#playerTwo").css('color', 'black');
    $("#heading").css('color', 'black');
    $('.winning').removeClass('winning');
    end = false;
    human = null;
    computer = null;
    delete human;
    delete computer;
  }

  function BoardMove(board, move) {
    this.Board = board;
    this.Move = move;
  }

  // Used the following link as a guide to understand and implement the minimax algorithm https://blog.vivekpanyam.com/how-to-build-an-ai-that-wins-the-basics-of-minimax-search/
  
  function Minimax(position, depth, maximizingPlayer) {

    if (checkWin(computer, position)) {
      return [10 - depth, position];
    } else if (checkWin(human, position)) {
      return [depth - 10, position];
    } else if (checkDraw()) {
      return [0, position]
    } else {

      var val = null;
      var index = 0;
      // loop through each child of node
      for (var i = 0; i < 9; i++) {
        if (position[i] == "") {
          position[i] = maximizingPlayer == true ? computer.role : human.role;
          var moveval = Minimax(position, depth + 1, !maximizingPlayer)[0];
          if ((maximizingPlayer && (val == null || moveval > val)) || (!maximizingPlayer && (val == null || moveval < val))) {
            index = i;
            val = moveval;
          }
          position[i] = "";
        }
      }
      return [val, index];
    }
  }

  function humanMove() {
    move();
    checkResult(human, position);
    currentPlayer = computer;
  }

  function computerMove() {
    var result = Minimax(position, 0, true);
    position[result[1]] = computer.role;
    $("table td").eq(result[1]).text(computer.role);
    checkResult(computer, position);
    currentPlayer = human;
  }

  $("#new").click(function() {
    reset();
  });

  // human makes move and invoke key functions as described above
  $("td").click(function() {
    if ($(this).text() || (currentPlayer != human) || end) {
      return;
    }

    $(this).text(human.role);
    humanMove();
    computerMove();
  });

  // create human object that plays X and computer that plays O
  $("#playerOne").click(function() {
    if (end) {
      return;
    }
    human = new Player("X", "Human");
    computer = new Player("O", "Computer");
    currentPlayer = human;
    $("#pick").text("You are X");
    $("#playerOne").css('color', 'red');
    $("#playerTwo").css('color', 'black');
  });

  // create human object that plays O and computer that plays X
  $("#playerTwo").click(function() {
    if (end) {
      return;
    }
    human = new Player("O", "Human");
    computer = new Player("X", "Computer");
    currentPlayer = human;
    $("#pick").text("You are O");
    $("#playerTwo").css('color', 'red');
    $("#playerOne").css('color', 'black');
  });

});
            
          
!
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