Pen Settings

HTML

CSS

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

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <body>
  <h1> Tic Tac Toe (FCC)</h1>
  
  <!-- Game board 3x3  -->
  <div class="gameBoard">
    <div> 
      <button class="button-1"> </button>
      <button class="button-2"> </button>
      <button class="button-3"> </button> 
    </div> 
    <div> 
      <button class="button-4">  </button> 
      <button class="button-5"> </button> 
      <button class="button-6"> </button> 
    </div>
    <div> 
      <button class="button-7"> </button> 
      <button class="button-8"> </button> 
      <button class="button-9"> </button> 
    </div>
  </div>

  <div>
    
    <p class="points">
      Human - AI : <span id="pointsHuman">0</span> - <span id="pointsAI">0</span>
    </p>
  </div>

  <!-- Message box used at the beggining. The human player will choose it's playing symbol (X or O) -->
  <div class="messageBox">
    Choose your symbol to play with: <br/><br/>
    <button class="symbolChoice">X</button>
    <button class="symbolChoice">O</button>
  </div>
  <!-- <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">  -->
  </canvas>

</body>
              
            
!

CSS

              
                :root {
  font-size: 14px;
  font-style: 'Helvetica';
}

html {
  /* This is needed to make a 100% height body */
  height: 92%;
  border: 0;
  background: #cdd8d5;
}

body {
  text-align: center;
  position: relative;
  min-height: 100%;
  margin: 0;
  padding: 0;
  font-size: 2em;
}

h1 {
  font-size: 1em;
}

.messageBox {
  margin: 0;
  width: 14em;
  padding: 0.7rem 0.5rem;
  background: rgba(38, 35, 47, 0.8);
  color: white;
  border-radius: 0.5rem;
  position: absolute;
  top: 11em;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 0.6em;
  font-color: #cecece;
}

.messageBox button {
  font-size: 0.8em;
  margin: 0 0.5rem;
  border-radius: 0.4rem;
}


.gameBoard div button {
  border: 1px solid black;
  vertical-align: top; /* Fix for a bad vertical alignment of empty buttons, because of the baseline. Solution from:   vertical-align: top; /* Fix for a bad vertical alignment of empty buttons, because of the baseline. */
  height: 6rem;
  width: 6rem;
  border-radius: 0.4rem;
  margin: 0.25rem 0;
  outline: 0;
  padding: 0;
  font-size: 0.8em;
}

.gameBoard div button:hover {
  box-shadow: inset 0 0 9px rgba(0, 0, 0, 0.4);
}

.points {
  font-size: 0.6em;
}
              
            
!

JS

              
                /**
 * @project Tic Tac Toe classic game. The user chooses his play symbol (X or O), then he/she can play multiple games. The score of wins is displayed at the bottom.
 */

$(document).ready(function() {
  view.gameGrid.display(game.grid);
  view.messageBox.appear();
  bindEvents();

}); // end doc ready


// Groups all the event handlers together: ------------------------------------
bindEvents = function() {

  var choiceSelector = ".symbolChoice";
  var gridSelector = ".gameBoard button";

  // THE GAME STARTS HERE, ONCE THE PLAYER SETS THE SYMBOL(X or O) TO PLAY WITH:
  $(choiceSelector).on("click", function(event) {
    var humanSymbolChoice = event.target.innerText;
    game.setFirstGame(humanSymbolChoice);
    view.messageBox.dissapear();
  });

  // THE GAME ADVANCES HERE, WHEN THE USER PRESSES THE GRID:
  $(gridSelector).on("click", function(event) {
    var nextHumanMoveIndex = parseInt(this.className.slice(-1));
    // Get the corresponding grid location (row, column). Eg index=4 => {row: 1, col: 1}
    var nextMove = game.getNextHumanMove(nextHumanMoveIndex);
    game.processMove(nextMove);
  }); // end on click inside the grid

  
  
  //--  CUSTOM events (used for pub/sub  - for loose coupling between objects)
  
  // THE GAME RESTARTS HERE, WHEN THIS CUSTOM EVENT IS RECEIVED:
  $("body").on("startGame", function(topic, data) {
    if (game.lastGameFirstTurn === "ai") {
      game.aIMove();
    }
  });

  $("body").on("view/scoreUpdated", function(topic, score) {
    view.score.updateScoreView(score);
  });
  
  $("body").on("view/gameWon", function(topic, gameWonResult) {
    view.gameGrid.indicateWinVisually(gameWonResult);
  });
  
  $("body").on("view/displayGameGrid", function(topic, gameToDisplay) {
    view.gameGrid.display(gameToDisplay.grid); 
  });

}; // end bindEvents function


//-- Groups methods to update the view (score, messageBox) -----------------------
var view = {

  score: {
    scoreHumanSelector: "#pointsHuman",
    scoreAISelector: "#pointsAI",
    messsageBoxSelector: ".messageBox",

    updateScoreView: function(score) {
      $(this.scoreHumanSelector).get(0).innerText = score.human;
      $(this.scoreAISelector).get(0).innerText = score.ai;
    }
  }, // end score

  messageBox: {
    selector: ".messageBox",
    
    appear: function() {
      $(this.selector).show();
    },

    dissapear: function() {
      $(this.selector).delay(200).slideUp(200);
    }
  }, // end messageBox
  
  gameGrid: {
    
    display: function(arr) {
      var gridButtonSelector= (".gameBoard div button");
      var row, col;
      var index = 0;
      $(gridButtonSelector).each(function() {
        row = Math.floor(index / 3);
        col = index % 3;
        this.innerText = arr[row][col];
        index++;
      });
    },
    
    indicateWinVisually: function(gameWonResult) {
      var winSelector = {
        row1 : ".button-1, .button-2, .button-3",
        row2 : ".button-4, .button-5, .button-6",
        row3 : ".button-7, .button-8, .button-9",
        col1 : ".button-1, .button-4, .button-7",
        col2 : ".button-2, .button-5, .button-8",
        col3 : ".button-3, .button-6, .button-9",
        diag1 : ".button-1, .button-5, .button-9",
        diag2 : ".button-7, .button-5, .button-3"
      }; 
      
      // Transform  (type = "row"; index = 2)  => (winType = "row3")
      var winType = gameWonResult.type + parseInt(gameWonResult.index + 1);

      if (gameWonResult.winner === "ai") {
        $(winSelector[winType]).css({background: "#dec3c2"}); // make it light red
      } else {
        $(winSelector[winType]).css({background: "#cadcc3"}); // make it light green
      }
      
      setTimeout(function() {  
         $(winSelector[winType]).css({background: "#dddddd"}); // back to grey 
      }, 1200);

    } // end indicateWinVisually
  } // end gameGrid
}; // end view


/* Game object that holds the game info (board, turn, etc) and it controls 
 * the flow of the game:  display, update, etc
 */
//-----------------------------------------------------------
var game = {

  grid: [
    [" ", " ", " "],
    [" ", " ", " "],
    [" ", " ", " "]
  ],

  symbol: {
    human: "",
    ai: ""
  },

  turn: "human",

  lastGameFirstTurn: "human", // used to alternate the turn of a new game ( human, AI, human, ...)

  score: {
    human: 0,
    ai: 0
  },

  
  // Commun algorithm for processing the moves (human and AI):
  processMove: function(move) {
    var isAllowed = this.checkIfAllowed(move);
    var self = this;

    if (isAllowed) {
      this.updateGrid(move);
      $("body").trigger("view/displayGameGrid", {grid: this.grid});
      
      checkWinResult = this.checkWin(move);
      var isGameOver = checkWinResult.gameStatus === "won" || checkWinResult.gameStatus === "draw";
      if (isGameOver) {
        this.updateScore(checkWinResult.gameStatus);
        this.changeLastGameFirstTurn(); 

        // Trigger an update on the view Game board, to indicate visually that the game was won:
        $("body").trigger("view/gameWon", checkWinResult);
        
        // After 1.4 secs, reset the grid:
        setTimeout(function() {
          self.resetGrid(); // standard workaround to access the game object
          $("body").trigger("view/displayGameGrid", {grid: self.grid});
          $("body").trigger("startGame", {
            turn: self.turn
          });
        }, 1400);

      } else {
        // Game not won yet. Initiate the process of the AI move:
        this.changeTurn();

        // If this is AI's turn, get it's move:
        if (this.turn == "ai") {
          this.aIMove();
        } // end if AI's turn
      } // end else (no win)
    } // end if allowed 
    else {
      // The move of the human is not allowed.
      console.log("move not allowed");
      return;
    }

  },

  //---------------------------------------------------------
  aIMove: function() {
    setTimeout(function() {  
      var nextAIMove = game.getNextAIMove();
      game.processMove(nextAIMove);
    }, 200);
  },
  
  //-------------------------------------------------------
  checkIfAllowed: function(move) {
    var isAllowed;

    // If it's human's turn, check if the selected cell is empty: 
    if (this.turn === "human" && this.grid[move.row][move.col] !== " ") {
      isAllowed = false;
    } else {
      isAllowed = true;
    }

    return isAllowed;
  },

  //----------------------------------------------------------
  updateScore: function(gameStatus) {
    var isGameOver = checkWinResult.gameStatus === "won" || checkWinResult.gameStatus === "draw";
    var hasGameWinner = checkWinResult.gameStatus === "won";
    // Only update if we have a winner (not draw):
    if (gameStatus === "won") {
       this.score[this.turn]++;
       // send a trigger to update the view (score)
       $("body").trigger("view/scoreUpdated", this.score);
    }
  },

  //-------------------------------------------------------
  setFirstGame: function(humanSymbolChoice) {

    this.turn = "human";
    this.symbol["human"] = humanSymbolChoice;

    // Set the AI symbol:
    if (humanSymbolChoice === "X") {
      this.symbol["ai"] = "O";
    } else {
      this.symbol["ai"] = "X";
    }
  },

  //-------------------------------------------------------
  changeTurn: function() {
    if (this.turn === "human") {
      this.turn = "ai";
    } else {
      this.turn = "human";
    }
  },

  //-------------------------------------------------------
  changeLastGameFirstTurn: function () {
    if (this.lastGameFirstTurn === "human") {
      this.lastGameFirstTurn = "ai";
    } else {
      this.lastGameFirstTurn = "human";
    }
    // Also advance the normal turn:
    this.turn = this.lastGameFirstTurn;
  },

  //-------------------------------------------------------
  resetGrid: function () {
    for (var row = 0; row < this.grid.length; row++) {
      for (var col = 0; col < this.grid.length; col++) {
        this.grid[row][col] = " ";
      }
    }
  }, // end resetGrid

  
  //-------------------------------------------------------
  checkWin: function (lastMove) {
    // Check if there is any 3x of the symbol: turn
    // Search 3X on any row:

    var result = {
      gameStatus: "playing", // can also be: won, or draw
      type: "", // row, col or diag
      index: 0, // [0-2] if row/col or [1-2] if diag
      winner: "" 
    };
    var arr = this.grid;
    var n = arr.length;
    currentSymbol = this.symbol[this.turn];
    var symbol3X = currentSymbol + currentSymbol + currentSymbol;
    var rowAfterLastMove, colAfterLastMove, diag1, diag2;

    // For rows and columns, the check is done only on the lastMove row&column:

    // - check first if win on the row:
    rowAfterLastMove = arr[lastMove.row].join("");
    if (rowAfterLastMove === symbol3X) {
      result.gameStatus = "won";
      result.type = "row";
      result.index = lastMove.row;
    }

    // - then on the col:
    colAfterLastMove = arr[0][lastMove.col] + arr[1][lastMove.col] + arr[2][lastMove.col];
    if (colAfterLastMove === symbol3X) {
      result.gameStatus = "won";
      result.type = "col";
      result.index = lastMove.col;
    }

    // - then on the 1st diag:
    diag1 = arr[0][0] + arr[1][1] + arr[2][2];
    if (diag1 === symbol3X) {
      result.gameStatus = "won";
      result.type = "diag";
      result.index = 0; // 0 instead of 1 to be align with the index of row & col (starting at 0).
    }

    // - then on the 2nd diag:
    diag2 = arr[2][0] + arr[1][1] + arr[0][2];
    if (diag2 === symbol3X) {
      result.gameStatus = "won";
      result.type = "diag";
      result.index = 1;
    }

    // Finally, check if the game is in a draw situation (status) = all the available places filled:
    var hasEmptyPlace = false;
    for (var i = 0; i < n; i++) {
      for (var j = 0; j < n; j++) {
        if (arr[i][j] === " ") {
          hasEmptyPlace = true;
          break;
        }
      }
    }
    if (!hasEmptyPlace) {
      result.gameStatus = "draw";
    }
    
    //Indicate who won:
    result.winner = this.turn;

    return result;
  }, // end checkWin

  //-------------------------------------------------------
  getNextAIMove: function() {
    // Call the solver from the separate object tttAISolver
    currentSymbol = this.symbol[this.turn];
    nextMove = tttAISolver.getNextAIMove(this.grid, currentSymbol);

    return nextMove;
  }, // end getNextAIMove

  //-------------------------------------------------------
  getNextHumanMove: function(index) {
    var row, col;
    row = Math.floor((index - 1) / 3);
    col = (index - 1) % 3;

    return {
      row: row,
      col: col
    };
  }, // getNextHumanMove

  //-------------------------------------------------------
  updateGrid: function(move) {
      this.grid[move.row][move.col] = this.symbol[this.turn];
    } // end updateGrid

}; // end game


/*--- Tick Tac Toe (TTT) solver ---------------------------*/
var tttAISolver = {

  getNextAIMove: function(oldArr, aISymbol) {
      /* The algorithm uses a set of rules, in order:
       * 1. Check if any 2x (row, column, or diagonal) for the AI player. If so, win.
       * 2. Check if any 2x for the human player. If so, block it.
       * 3. Test each move and take the one that will maximize the nr of 2x in line for you. 
       * 4. Take the middle (used if AI starts)
       * 5. Take the 1st corner(useful for the 1st AI move, when human starts)
       * 6. Take the 1st available spot.
       */
      var n = oldArr.length;
      var index, row, column, humanSymbol, aIMove;
      var solutionFound = false;
      var solutionArr = oldArr;

      if (aISymbol === "O") {
        humanSymbol = "X";
      } else {
        humanSymbol = "O";
      }

      // 1. Check if any 2x (row, column, or diagonal) for the AI player. If so, win.
      aIMove = search2X(oldArr, aISymbol);

      // If not: 2. Check if any 2x for the human player. If so, block it.
      if (!aIMove.solutionFound) {
        aIMove = search2X(oldArr, humanSymbol);
      }

      // If not: 3. maximize the nr of 2x in line for you. If more than one solution: a. Take the mid if available. b. If unavailable, take a corner if available. c. If unavailable, take the first available.

      if (!aIMove.solutionFound) {
        aIMove = maximizePredicted2X(oldArr, aISymbol);
      }

      if (!aIMove.solutionFound) {
        // Put in the mid
        if (oldArr[1][1] === " ") {
          aIMove.firstResult.row = 1;
          aIMove.firstResult.col = 1;
          aIMove.solutionFound = true;
        }
      }
      // Put in the 1st corner:
      if (!aIMove.solutionFound) {
        if (oldArr[0][0] === " ") {
          aIMove.firstResult.row = 0;
          aIMove.firstResult.col = 0;
          aIMove.solutionFound = true;
        }
      }
      // Otherwise put in the 1st any free place (" "):
      if (!aIMove.solutionFound) {
        for (var i = 0; i < n; i++) {
          for (var j = 0; j < n; j++) {
            if (oldArr[i][j] === ' ') {
              aIMove.firstResult.row = i;
              aIMove.firstResult.col = j;
              aIMove.solutionFound = true;
            } // end if
          } // end for j
        } // end for i
      }

      return aIMove.firstResult;

      
      //-------------------------------------------------------
      function search2X(arr, symbol) {
        var combinations2X = [
          " " + symbol + symbol,
          symbol + " " + symbol,
          symbol + symbol + " "
        ];

        var result = {
          solutionFound: false,
          firstResult: {
            row: 0,
            col: 0
          },
          nrOfSolutions: 0
        };

        // search any 2X in a row: 
        for (var i = 0; i < n; i++) {
          row = arr[i].join("");
          index = combinations2X.indexOf(row);
          if (index > -1) {
            result.solutionFound = true;
            result.firstResult.row = i;
            result.firstResult.col = index;
            result.nrOfSolutions++;
            break;
          } // end if
        } // end for i (row)

        //search any 2x in a column:
        for (var j = 0; j < n; j++) {
          column = arr[0][j] + arr[1][j] + arr[2][j];
          index = combinations2X.indexOf(column);
          if (index > -1) {
            if (!result.solutionFound) {
              result.solutionFound = true;
              result.firstResult.row = index;
              result.firstResult.col = j;
              result.nrOfSolutions++;
              break;
            } // end if !solution found 
            else {
              //Solution already found. Only increment the nr of 2X possible
              result.nrOfSolutions++;
            } // end else (solution already found)
          } // end if 2X found
        } // end for i (column)

        //check any 2x in diagonal:
        // -1st diagonal:
        var diag1 = arr[0][0] + arr[1][1] + arr[2][2];
        index = combinations2X.indexOf(diag1);
        if (index > -1) {
          if (!result.solutionFound) {
            result.solutionFound = true;
            result.firstResult.row = index;
            result.firstResult.col = index;
            result.nrOfSolutions++;
          } // end if !solution found 
          else {
            //Solution already found. Only increment the nr of 2X possible
            result.nrOfSolutions++;
          } // end else (solution already found)
        } // end if solution found

        // -2nd diag:
        var diag2 = arr[2][0] + arr[1][1] + arr[0][2];
        index = combinations2X.indexOf(diag2);
        if (index > -1) {
          if (!result.solutionFound) {
            result.solutionFound = true;
            result.firstResult.row = n - index - 1;
            result.firstResult.col = index;
            result.nrOfSolutions++;
          } // end if !solution found 
          else {
            //Solution already found. Only increment the nr of 2X possible
            result.nrOfSolutions++;
          } // end else (solution already found)

        } // end if solution found

        return result;
      } //end search2x

    
      //------------------------------------------------------
      function maximizePredicted2X(arr, symbol) {
        var n = arr.length;
        var bestMove = {
          nrOfSolutions: 0,
          firstResult: {}
        };
        // Use jQuery way to deep clone an object:
        var futureProjectedGrid = $.extend(true, {}, arr);
        var testedMove = {};

        for (var i = 0; i < n; i++) {
          for (var j = 0; j < n; j++) {
            // move in each empty spot (" "), then create a future projected grid
            if (arr[i][j] === " ") {
              // reset the futureProjectedGrid, then try the next move option:
              futureProjectedGrid = $.extend(true, {}, arr);
              futureProjectedGrid[i][j] = symbol;
              // Test this move, and get the nrOfSolutions:
              testedMove = search2X(futureProjectedGrid, symbol);
              if (testedMove.nrOfSolutions > bestMove.nrOfSolutions) {
                bestMove.nrOfSolutions = testedMove.nrOfSolutions;
                bestMove.firstResult.row = i;
                bestMove.firstResult.col = j;
                bestMove.solutionFound = true;
              } // end if better solution (more 2x created)
            } // end if empty spot (" ")
          } // end for j (col) 
        } // end for i (row)

        return bestMove;

      } // end maximisePredicted2X

    } //end calculateNextMove

}; // end solve
              
            
!
999px

Console