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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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

              
                <div class="wrapper">
  <h1>Tic-Tac-Toe</h1>
  <button id="reset">Reset Game</button>
  <div id="overlay"><div id="text">Results</div> </div>
    <div class="gameboard">
      <!-- First row -->
      <div class="block firstrow" id="0">
        <i class="fa fa-times"></i> <i class="fa fa-circle"></i>
      </div>
      <div class="block firstrow" id="1">
        <i class="fa fa-times"></i> <i class="fa fa-circle"></i>
      </div>
      <div class="block firstrow" id="2">
        <i class="fa fa-times"></i> <i class=" fa fa-circle"></i>
      </div>
      <!-- Second row -->
      <div class="block" id="3">
        <i class="fa fa-times"></i> <i class="fa fa-circle"></i>
      </div>
      <div class="block" id="4">
        <i class="fa fa-times"></i> <i class="fa fa-circle"></i>
      </div>
      <div class="block" id="5">
        <i class="fa fa-times"></i> <i class="fa fa-circle"></i>
      </div>
      <!-- Third row -->
      <div class="block thirdrow" id="6">
        <i class="fa fa-times"></i> <i class="fa fa-circle"></i>
      </div>
      <div class="block thirdrow" id="7">
        <i class="fa fa-times"></i> <i class="fa fa-circle"></i>
      </div>
      <div class="block thirdrow" id="8">
        <i class="fa fa-times"></i> <i class="fa fa-circle"></i>
      </div>
    </div>
</div>
    <script type="text/javascript" src="script2.js"></script>
  </body>
</html>

              
            
!

CSS

              
                body {
  height: 100%;
  font-family: "Montserrat", "Avenir";
  text-align: center;
  --coral: #FA7268;
  --green: #018492;
}

h1 {
  color: var(--coral);
  border-bottom: 1px solid var(--coral);
  margin: 0 auto;
}

/* Game board and block styles */

.gameboard {
  max-width: 75vmin;
  max-height: 75vmin;
  margin: 0 auto;
}

.block {
  width: 32%;
  padding-bottom: 32%;
  float: left;
  cursor: pointer;
}

.block:nth-child(3n + 1) {
  border-right: 1vmin solid var(--green);
}

.block:nth-child(3n + 0) {
  border-left: 1vmin solid var(--green);
}

.firstrow {
  border-bottom: 1vmin solid var(--green);
}

.thirdrow {
  border-top: 1vmin solid var(--green);
}

.fa-times,
.fa-circle {
  display: none;
  margin: 0 auto;
  margin-top: 4vmin;
  margin-bottom: -50vmin;
  font-size: 15vmin;
}

.fa-times {
  color: var(--coral);
}

.controls {
  margin-bottom: 20px;
}

button {
  padding: 12px;
  border: 1px solid var(--green);
  border-radius: 5px;
  margin: 15px 0;
  outline: none;
  cursor: pointer;
  text-transform: capitalize;
}

button:hover {
  background-color: var(--coral);
  color: white;
  border: 1px solid var(--coral);
  transition: 0.1s linear;
  -webkit-transition: 0.1s linear;
}

/* Styles triggered by JS */
.clicked {
  display: block;
}


#overlay {
  position: fixed;
  display: none; 
  width: 100%; 
  height: 100%;
  top: 0; 
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.6); 
}

#text{
  position: absolute;
  top: 50%;
  left: 50%;
  font-size: 50px;
  color: white;
  transform: translate(-50%,-50%);
  -ms-transform: translate(-50%,-50%);
  display: flex;
  flex-direction: column;
}

.overlayResetButton {
  cursor: pointer;
  background-color: var(--green);
  font-weight: bold;
}
              
            
!

JS

              
                // general variables
const winningCombinations = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [2, 5, 8],
  [0, 3, 6],
  [1, 4, 7],
  [0, 4, 8],
  [2, 4, 6]
];

let playerMoves = [];
let computerMoves = [];
let whoseTurn = "";
let totalMoves = 0;
let didSomeoneWin = false;
let playerAboutToWin = false;
let smartComputerNextMove;

//reference to DOM elements
let blocks = document.querySelectorAll(".block");
let resetButton = document.getElementById("reset");

window.onload = playGame();

function playGame() {
  if (totalMoves === 9 && !didSomeoneWin) {
    displayResult("It's a tie");
    setTimeout(function() {
      reset();
    }, 1000);
  } else if (didSomeoneWin) {
    setTimeout(function() {
      reset();
    }, 1000);
  } 
  //player always starts
  else if (whoseTurn === "player" || totalMoves === 0) {
    player();
  } else if (whoseTurn === "computer") {
    setTimeout(function() {
      computer();
    }, 200);
  }
}

//player actions
function player() {
  //adding a cross to the clicked blocks
  for (let i = 0; i < blocks.length; i++) {
    blocks[i].addEventListener("click", function() {
      if (
        computerMoves.indexOf(Number(this.id)) !== -1 ||
        playerMoves.indexOf(Number(this.id)) !== -1
      ) {
        return;
      }
      
      this.getElementsByTagName("i")[0].classList.add("clicked");
      playerMoves.push(Number(this.id));
      nextTurn("computer", playerMoves);
      // console.log("player moves: " + playerMoves);
    });
  }
}

//computer actions
function computer() {
  smartComputer();
  let random = pickRandomBlock();
  for (let i = 0; i < blocks.length; i++) {
    if (totalMoves === 9 && !didSomeoneWin) {
      return;
    }
    //add circle for computer moves, only if the block is not already occupied
    else if (
      computerMoves.indexOf(Number(random.id)) !== -1 ||
      playerMoves.indexOf(Number(random.id)) !== -1
    ) {
      return computer();
    }
    random.getElementsByTagName("i")[1].classList.add("clicked");
  }
  //add the computer move to the moves array
  if (!computerMoves.includes(Number(random.id))) {
    computerMoves.push(Number(random.id));
  }
  nextTurn("player", computerMoves);
  // console.log("computer moves: " + computerMoves);
}

//pick random location for computer move
function pickRandomBlock() {
  //picks location for computer move
  let random;
  if (playerAboutToWin) {
    if (
      computerMoves.indexOf(smartComputerNextMove) === -1 &&
      playerMoves.indexOf(smartComputerNextMove) === -1
    ) {
      random = smartComputerNextMove;
      playerAboutToWin = false;
    } else {
      random = Math.floor(Math.random() * blocks.length);
    }
  } 
  //handling tie 
  else if (totalMoves === 9 && didSomeoneWin === false) {
    return;
  } else {
    random = Math.floor(Math.random() * blocks.length);
  }
  return blocks[random];
}

//returns the winning move for the player and assigns this to the smartComputerNext move variable
function smartComputer() {
  let playerPotentialWins = winningCombinations.filter(
    array =>
      array.filter(item => {
        return playerMoves.indexOf(item) > -1;
      }).length === 2
  );

  if (playerPotentialWins.length > 0) {
    playerAboutToWin = true;
    playerPotentialWins.filter(array =>
      //get the index of the next computer move
      array.filter(item => {
        if (
          playerPotentialWins.indexOf(item) === -1 &&
          playerMoves.indexOf(item) === -1 &&
          computerMoves.indexOf(item) === -1
        ) {
          smartComputerNextMove = item;
        }
      })
    );
  }
}


// ====HELPER FUNCTIONS ===

//Moving on to the next turn
function nextTurn(opponent, whoseMoves) {
  whoseTurn = opponent;
  totalMoves++;
  hasWon(whoseMoves, winningCombinations);
  playGame();
}

//check if someone has won
function hasWon(moves, winningCombinations) {
  let foundResults = winningCombinations.filter(
    array =>
      array.filter(item => {
        return moves.indexOf(item) > -1;
      }).length === 3
  );

  if (foundResults.length > 0) {
    if (whoseTurn === "computer") {
      displayResult("You won");
    } else if (whoseTurn === "player") {
      displayResult("The computer has won");
    }
    didSomeoneWin = true;
  }
}

//resetting the game
function reset() {
  for (let i = 0; i < blocks.length; i++) {
    blocks[i].getElementsByTagName("i")[0].classList.remove("clicked");
    blocks[i].getElementsByTagName("i")[1].classList.remove("clicked");
  }
  playerMoves = [];
  computerMoves = [];
  totalMoves = 0;
  didSomeoneWin = false;
  playerAboutToWin = false;
  hideResult();
}

//resetting the game manually
resetButton.addEventListener("click", function() {
  reset();
});

function displayResult(winningMessage) {
  document.getElementById("overlay").style.display = "block";
  document.getElementById("text").textContent = winningMessage;
    // ===un-comment this to add a manual reset button to the overlay===
  
  // if (document.getElementById("text").textContent === "It's a tie") {
  //   let resetButton = document.createElement("button");
  //   resetButton.classList.add("overlayResetButton");
  //   resetButton.textContent = "Reset Game";
  //   resetButton.addEventListener("click", function() {
  //     reset();
  //   });
  //   document.getElementById("text").appendChild(resetButton);
  // }
}

function hideResult() {
  document.getElementById("overlay").style.display = "none";
}

              
            
!
999px

Console