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.

              <!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog" role="document">
    <div class="modal-content text-center">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Choose your symbol</h4>
      <button type="button" class="btn btn-info" data-dismiss="modal" id="buttonX">X</button>
      <button type="button" class="btn btn-primary" data-dismiss="modal" id="button0">O</button>
<!-- End of the modal -->
<div class="container-fluid">
  <div class="row">
    <div class="col-xs-3 square" id="b0"></div>
    <div class="col-xs-3 square" id="b1"></div>
    <div class="col-xs-3 square" id="b2"></div>
  <div class="row">
    <div class="col-xs-3 square" id="b3"></div>
    <div class="col-xs-3 square" id="b4"></div>
    <div class="col-xs-3 square" id="b5"></div>
  <div class="row text-center">
    <div class="col-xs-3 square" id="b6"></div>
    <div class="col-xs-3 square" id="b7"></div>
    <div class="col-xs-3 square" id="b8"></div>
  <div class="row text-center"><br>
    <div class="winner text-center"></div><br>
    <button type="button" class="btn btn-primary" id="reset">Let me try it again !</button>
<link href='https://fonts.googleapis.com/css?family=Corben:700' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Sigmar+One' rel='stylesheet' type='text/css'>

              body {
  background: #1F282B;
  width: 100%;
  heigth: 100%;

#button0 {
  margin: 20px 0 20px 0;

.modal-dialog {
  /* Choice box*/
  margin: auto;
  margin-top: 20vh;
  width: 250px;

.col-xs-3 {
  background: #1CD46B;
  max-width: 150px;
  width: 25vw;
  min-height: 100px;
  margin-left: 3vw;
  margin-top: 3vh;
  border-radius: 10px;
  cursor: pointer;
  text-align: center;
  font-family: 'Corben', cursive;

.row {
  margin: auto;
  max-width: 600px;
  width: 90vw;

.winner {
  margin: auto;
  max-width: 300px;
  width: 50vw;
  border-radius: 20px;
  font-size: 20px;
  background-color: #F01823;
  color: white;
  font-family: 'Sigmar One', cursive;

.userClicked {
  background: #34C2AF;

.aiClicked {
  background: #EB5454;
              $(document).ready(function() {

$('#myModal').modal('show'); // Show choices when page loads

var userSign, aiSign;
var movesSign = []; // Keep track of the sign of the moves made

function clearBoard() {
  for (var i = 0; i < 9; i++) {
    movesSign[i] = "";
    $("#b" + i).text("");
  $(".square").removeClass("clicked"); // Make boxes clickable again
  $(".square").removeClass("aiClicked"); // Remove the red background from AI clicked boxes
  $(".square").removeClass("userClicked"); // Remove the blue background from user clicked boxes

//Assign signs according to user's choice
$("#button0").on("click", function() {
  userSign = "O";
  aiSign = "X";

$("#buttonX").on("click", function() {
  userSign = "X";
  aiSign = "O";

//When there is a click on the board
$(".square").on("click", function() {
  var position = parseInt($(this).attr("id")[1]);

//When the user clicks on the board
function userTurn(pos) {
  if ($("#b" + pos).hasClass("clicked")) { // Square is filled
    //do nothing
  } else {
    if (!boardFull(movesSign) && !score(movesSign)) {
      takeTurn(pos, userSign); //Make the user's move
      $("#b" + pos).addClass("userClicked"); // Add blue background to user clicked boxes
        aiTurn(); //Switch to AI to take it's turn

//AI's turn to make a move
function aiTurn() {
  var move = miniMax(movesSign, aiSign)[1];
  takeTurn(move, aiSign);
  $("#b" + move).addClass("aiClicked"); // Add red background to AI clicked boxes

//Add the X or O on the board
function takeTurn(position, sign) {
  movesSign[position] = sign;
  $("#b" + position).append("<h1>" + sign + "</h1>");
  $("#b" + position).addClass("clicked");
  if (gameOver(movesSign, sign)) { // Check if the game is over
    if (sign == aiSign)
      $(".winner").append("<p>Guess you're not that smart !</p>"); // AI wins
      $(".winner").append("<p>You Win</p>"); // Never gonna happen
    setTimeout(function() {
    }, 2000);
  } else if (boardFull(movesSign)) { // Show draw game message
    $(".winner").append("<p>Draw Game!</p>");
    setTimeout(function() {
    }, 2000);

//Minimax algorithm
function miniMax(board, sign, pos) {
  var scoreGame = score(board); // Score board for every recursion

  if (boardFull(board) || scoreGame) { // If the game has been scored or the board is full, exit
    return [scoreGame, pos]; // Return score and the positon 

  var multi = sign === aiSign ? 1 : -1; // AI will look for the best score and user for the worst
  var moves = possibleMoves(board); // Find out the free boxes for every recursion
  var bestScore = -100;
  var positions = [pos];
  var thisScore;
  var oppSign = sign === "O" ? "X" : "O"; // Opponent's sign

  while (moves.length > 0) {
    var newPosition = moves.pop(); // Pop the last number from the array of possible moves
    var newBoard = board.slice(); // Make a copy of the current board
    newBoard[newPosition] = sign; // Push the the new sign to the new board. Sign changes with every recrusion

    var result = miniMax(newBoard, oppSign, newPosition); // Recursively call the function with new board and position
    thisScore = multi * result[0]; // "thisScore" will be +ve for AI and -ve for user

    // Choose the best possible move
    if (thisScore === bestScore) {
    } else if (thisScore > bestScore) {
      bestScore = thisScore;
      positions = [newPosition];

  // Choose a move at random from the best moves
  var randomMove = Math.floor(Math.random() * positions.length);
  return [multi * bestScore, positions[randomMove]];

// Score the game with every turn
function score(board) {
  var emptyBox = board.filter(function(square) { // Returns array for element returning true for the condition
    return square === "";
  if (win(board, aiSign)) {
    return 10 + emptyBox; // AI wins the move
  } else if (win(board, userSign)) {
    return -10 - emptyBox; // User wins the move
  } else {
    return 0; // Draw  

// Get the number of free squares available
function possibleMoves(board) { // For the arguement "board", check if it has free spaces
  var freeMoves = [];
  for (var i = 0; i < 9; i++) {
    if (board[i] === "") {
  return freeMoves;

// Check whether the game is over or not
function gameOver(board, winSign) {
  if (win(board, winSign)) {
    return true;

// Check if somebody has won the game or not
function win(board, sign) {
  var winCombo = [ // Winning combinations
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  return winCombo.some(function(subVal) { // Check the sub arrays
    return subVal.every(function(val) { // Check all the elements in the subarrays
      return board[val] === sign; // Check the position against the sign stored 

// Check if the board has any space left to fill or not
function boardFull(board) {
  return !board.some(function(square) {
    return square === "";

//Reset the game. Reloads the page and erases the board
$("#reset").on("click", function() {
  clearBoard(); // Erase all the boxes
  $('#myModal').modal('show'); // Give the user the choice again
🕑 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 ..................