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="icon-bar header">
    <a href="https://chrisandsuch.github.io/" class="github">
      <i class="fab fa-github-square"></i>
    </a>
    <a href="https://www.freecodecamp.org/chrisandsuch" class="fcc">
      <i class="fab fa-free-code-camp"></i>
    </a>
  </div>
  <div class="display">
    <ul>
      <li><span id="current-player"></span></li>
      <li><span id="current-player-letter"></span></li>
    </ul>
      <h3 id="current-player"></h3>
  </div>
  <div class="container" id="game-board">
    <div id="board">
      <div class="tile column-0 row-0 diagonal-0" id="0"></div>
      <div class="tile column-1 row-0" id="1"></div>
      <div class="tile column-2 row-0 diagonal-1" id="2"></div>
      <div class="tile column-0 row-1" id="3"></div>
      <div class="tile column-1 row-1 diagonal-0 diagonal-1" id="4"></div>
      <div class="tile column-2 row-1" id="5"></div>
      <div class="tile column-0 row-2 diagonal-1" id="6"></div>
      <div class="tile column-1 row-2" id="7"></div>
      <div class="tile column-2 row-2 diagonal-0" id="8"></div>
    </div>
  </div>

  <div class="modal" id="player-menu">
    <div class="modal-content">
      <div class="modal-header">
        <h2>Welcome to TicTacToe</h1>
          <hr>
          <h5>Choose an option:</h5>
      </div>
      <div class="modal-body">
        <button id="one-player" value="one" class="button">One Player</button>
        <button id="two-player" value="two" class="button">Two Player</button>
      </div>
    </div>
  </div>

  <div class="modal" id="letter-menu">
    <div class="modal-content">
      <div class="modal-header">
        <h1>Choose a letter:</h1>
      </div>
      <div class="modal-body">
        <button id="letter-x" value="X" type="button" class="button">X</button>
        <button id="letter-o" value="O" type="button" class="button">O</button>
      </div>
    </div>
  </div>
      <div class="modal" id="count-down">
          <div class="modal-content">
            <div class="modal-header">
              
            </div>
            <div class="modal-body">
                <h1 class="count-down">Game starts in...</h1>
         </div>
          </div>
        </div>
  <div class="modal" id="winner-menu">
    <div class="modal-content">
      <div class="modal-header">
        <h1 id="winner"></h1>
      </div>
      <div class="modal-body">
        <button id="play-again" value="X" type="button" class="button">Play Again?</button>
      </div>
    </div>
  </div>

            
          
!
            
              * {
    box-sizing: border-box;
}
body {
    position: relative;
    background-color: #f4f4f4;
  } 

.container {
    overflow: hidden;
    width: 300px;
    height: 300px;
    position: absolute;
    left: 10%;
    background-image: url("https://github.com/chrisandsuch/freeCodeCamp/blob/master/projects/tic-tac-toe/chalkboard.jpg?raw=true");
    background-repeat: no-repeat;
    background-size: cover;
    display: grid;
    grid-template-columns: 1fr 4fr 1fr;
}
ul {
  list-style: none;
}
#board {
    grid-row: 2 / 2;
    grid-column: 2 / 2;
    display: grid;
    grid-template-columns: auto auto auto;
    width: 200px;
    height: 200px;
}

.tile {
    width: 65px;
    height: 65px;
    border: 1.5px solid whitesmoke;
    font-family: 'Gochi Hand', cursive;
    color: whitesmoke;
    text-align: center;
    font-size: 2.5em;  
}
.column-0 {
    grid-column: 1 / 1;
}
.column-1 {
    grid-column: 2 / 2;
}
.column-2 {
    grid-column: 3 / 3;
}
.icon-bar {
    position: fixed;
    top: 20%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
  }
.icon-bar a {
    display: block;
    text-align: center;
    padding: 2px;
    transition: all 0.3s ease;
    color: white;
    font-size: 1em;
  }
.icon-bar a:hover {
      background-color: #000;
  }
  
.github {
    background: rgba(36, 41, 46, 0.619);
    color: white;
  }
.fcc {
    background: #056312;
    color: white;
  }
.content {
    margin-left: 75px;
    font-size: 30px;
  }

#count-down {
  display: "none";
}


/* Modal */

.modal {
    /* display: grid; */
    position: fixed;
    z-index: 1;
    /* higher index means more up front (depth) */
    left: 0;
    top: 0%;
    padding-top: 10%;
    height: 100%;
    width: 100%;
    overflow: auto;
  }
  
  .modal-content {
    margin: 0% auto;
    padding: 20px;
    width: 70%;
    box-shadow: 5px 5px 8px 0 rgba(0, 0, 0, 0.2),
      5px 7px 20px 0 rgba(0, 0, 0, 0.6);
    border: 2px solid black;
    border-radius: 20px;
    animation-name: modalopen;
    animation-duration: 2s;
  }
  
  @keyframes modalopen {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }
  
  .modal-header {
    color: green;
    text-align: center;
  }
  
  .modal-body {
    color: green;
    font-size: 1em;
    text-align: center;
    width: 100%;
    height: auto;
    border-radius: 20px;
  }
            
          
!
            
              //@ts-check
const P1 = {
  name: "P1",
  full_name: "Player 1",
  letter: ""
};
const P2 = {
  name: "P2",
  full_name: "Player 2",
  letter: ""
};
const AI = {
  name: "AI",
  full_name: "Computer",
  letter: "",
  move() {
    let rows = ["", "", ""];
    let columns = ["", "", ""];
    let diagonals = ["", ""];
    let hasMoved = false;
    let opponent = new RegExp(P1.letter + "{2}", "g");
    let self = new RegExp(AI.letter + "{2}", "g");
    let OO = /O{2}/g;
    let id = /\d/;
    document.querySelectorAll(".row-0").forEach(function(tile) {
      if (tile.textContent === "") {
        rows[0] += tile.id;
      } else {
        rows[0] += tile.textContent;
      }
    });
    document.querySelectorAll(".row-1").forEach(function(tile) {
      if (tile.textContent === "") {
        rows[1] += tile.id;
      } else {
        rows[1] += tile.textContent;
      }
    });
    document.querySelectorAll(".row-2").forEach(function(tile) {
      if (tile.textContent === "") {
        rows[2] += tile.id;
      } else {
        rows[2] += tile.textContent;
      }
    });
    document.querySelectorAll(".column-0").forEach(function(tile) {
      if (tile.textContent === "") {
        columns[0] += tile.id;
      } else {
        columns[0] += tile.textContent;
      }
    });
    document.querySelectorAll(".column-1").forEach(function(tile) {
      if (tile.textContent === "") {
        columns[1] += tile.id;
      } else {
        columns[1] += tile.textContent;
      }
    });
    document.querySelectorAll(".column-2").forEach(function(tile) {
      if (tile.textContent === "") {
        columns[2] += tile.id;
      } else {
        columns[2] += tile.textContent;
      }
    });
    document.querySelectorAll(".diagonal-0").forEach(function(tile) {
      if (tile.textContent === "") {
        diagonals[0] += tile.id;
      } else {
        diagonals[0] += tile.textContent;
      }
    });
    document.querySelectorAll(".diagonal-1").forEach(function(tile) {
      if (tile.textContent === "") {
        diagonals[1] += tile.id;
      } else {
        diagonals[1] += tile.textContent;
      }
    });
    if (/\d/.test(rows[0]) && hasMoved === false) {
      let tileId = /\d/.exec(rows[0]);
      if (self.test(rows[0])) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      } else if (self.test(rows[0]) && hasMoved === false) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      }
    }
    if (/\d/.test(rows[1]) && hasMoved === false) {
      let tileId = /\d/.exec(rows[1]);
      if (self.test(rows[1])) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      } else if (opponent.test(rows[1]) && hasMoved === false) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      }
    }
    if (/\d/.test(rows[2]) && hasMoved === false) {
      let tileId = /\d/.exec(rows[2]);
      if (self.test(rows[2])) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      } else if (opponent.test(rows[1]) && hasMoved === false) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      }
    }
    if (/\d/.test(columns[0]) && hasMoved === false) {
      let tileId = /\d/.exec(columns[0]);
      if (self.test(columns[0])) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      } else if (opponent.test(columns[0]) && hasMoved === false) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      }
    }
    if (/\d/.test(columns[1]) && hasMoved === false) {
      let tileId = /\d/.exec(columns[1]);
      if (self.test(columns[1])) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      } else if (opponent.test(columns[1]) && hasMoved === false) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      }
    }
    if (/\d/.test(columns[2]) && hasMoved === false) {
      let tileId = /\d/.exec(columns[2]);
      if (self.test(columns[2])) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      } else if (opponent.test(columns[2]) && hasMoved === false) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      }
    }
    if (/\d/.test(diagonals[0]) && hasMoved === false) {
      let tileId = /\d/.exec(diagonals[0]);
      if (self.test(diagonals[0])) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      } else if (opponent.test(diagonals[0]) && hasMoved === false) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      }
    }
    if (/\d/.test(diagonals[1]) && hasMoved === false) {
      let tileId = /\d/.exec(diagonals[1]);
      if (self.test(diagonals[1])) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      } else if (opponent.test(diagonals[1]) && hasMoved === false) {
        document.getElementById(tileId.join("")).textContent = AI.letter;
        document
          .getElementById(tileId.join(""))
          .removeEventListener("click", BOARD.mark);
        hasMoved = true;
      }
    }
    if (hasMoved === false) {
      rows.forEach(function(row) {
        if (hasMoved === false && /\d/.test(row) === true) {
          let tileId = /\d/.exec(row);
          document.getElementById(tileId.join("")).textContent = AI.letter;
          document
            .getElementById(tileId.join(""))
            .removeEventListener("click", BOARD.mark);
          hasMoved = true;
        }
      });
    }
    checkStatus();
  }
};
const BOARD = {
  mark(e) {
    document.getElementById(e.target.id).textContent =
      GAME.state.current_player.letter;
    document
      .getElementById(e.target.id)
      .removeEventListener("click", BOARD.mark);
    checkStatus();
  }
};
const GAME = {
  state: {
    two_player: false,
    current_player: P1,
    hasWon: false,
    isTie: false
  },
  view: {
    playerMenu: document.getElementById("player-menu"),
    letterMenu: document.getElementById("letter-menu"),
    winnerMenu: document.getElementById("winner-menu"),
    gameScreen: document.getElementById("game-board"),
    countDown: document.getElementById("count-down")
  }
};
const reset = () => {
  document.querySelectorAll(".tile").forEach(tile => {
    tile.textContent = "";
  });
  P1.letter = "";
  P2.letter = "";
  AI.letter = "";
  GAME.state.isTie = false;
  GAME.state.hasWon = false;
  GAME.state.current_player = P1;
  GAME.state.two_player = false;
  document.getElementById("current-player").textContent = "";
  document.getElementById("current-player-letter").textContent = "";
  showPlayerMenu();
};

const attachListeners = () => {
  document.querySelectorAll(".tile").forEach(tile => {
    tile.addEventListener("click", BOARD.mark);
  });
};
const showCurrentPlayer = () => {
  document.getElementById("current-player").textContent = `Turn: ${
    GAME.state.current_player.full_name
  }`;
  document.getElementById("current-player-letter").textContent = `Letter: ${
    GAME.state.current_player.letter
  }`;
};

const checkStatus = () => {
  let total = 0;
  let rows = [0, 0, 0];
  let columns = [0, 0, 0];
  let diagonals = [0, 0];
  document.querySelectorAll(".row-0").forEach(function(tile) {
    if (tile.textContent === GAME.state.current_player.letter) {
      rows[0] = rows[0] + 1;
    }
  });
  document.querySelectorAll(".row-1").forEach(function(tile) {
    if (tile.textContent === GAME.state.current_player.letter) {
      rows[1] = rows[1] + 1;
    }
  });
  document.querySelectorAll(".row-2").forEach(function(tile) {
    if (tile.textContent === GAME.state.current_player.letter) {
      rows[2] = rows[2] + 1;
    }
  });
  document.querySelectorAll(".column-0").forEach(function(tile) {
    if (tile.textContent === GAME.state.current_player.letter) {
      columns[0] = columns[0] + 1;
    }
  });
  document.querySelectorAll(".column-1").forEach(function(tile) {
    if (tile.textContent === GAME.state.current_player.letter) {
      columns[1] = columns[1] + 1;
    }
  });
  document.querySelectorAll(".column-2").forEach(function(tile) {
    if (tile.textContent === GAME.state.current_player.letter) {
      columns[2] = columns[2] + 1;
    }
  });
  document.querySelectorAll(".diagonal-0").forEach(function(tile) {
    if (tile.textContent === GAME.state.current_player.letter) {
      diagonals[0] = diagonals[0] + 1;
    }
  });
  document.querySelectorAll(".diagonal-1").forEach(function(tile) {
    if (tile.textContent === GAME.state.current_player.letter) {
      diagonals[1] = diagonals[1] + 1;
    }
  });
  document.querySelectorAll(".tile").forEach(function(tile) {
    if (/X|O/.test(tile.textContent)) {
      total = total + 1;
    }
  });
  if (rows.includes(3)) {
    GAME.state.hasWon = true;
  } else if (columns.includes(3)) {
    GAME.state.hasWon = true;
  } else if (diagonals.includes(3)) {
    GAME.state.hasWon = true;
  } else if (total === 9) {
    GAME.state.hasWon = true;
    GAME.state.isTie = true;
  }
  gameLogic();
};

const gameLogic = () => {
  switch (GAME.state.hasWon) {
    case true:
      viewController(
        GAME.view.winnerMenu,
        GAME.view.countDown,
        GAME.view.playerMenu,
        GAME.view.letterMenu,
        GAME.view.gameScreen
      );
      if (GAME.state.isTie) {
        document.getElementById("winner").textContent = "GAME ENDED IN A TIE!";
        document.getElementById("play-again").addEventListener("click", reset);
      } else if (GAME.state.isTie === false) {
        document.getElementById("winner").textContent = `${
          GAME.state.current_player.full_name
        } HAS WON!`;
        document.getElementById("play-again").addEventListener("click", reset);
      }
      break;
    case false:
      if (GAME.state.two_player) {
        if (GAME.state.current_player.name === "P1") {
          GAME.state.current_player = P2;
        } else if (GAME.state.current_player.name === "P1") {
          GAME.state.current_player = P1;
        }
      } else if (GAME.state.two_player === false) {
        if (GAME.state.current_player.name === "P1") {
          GAME.state.current_player = AI;
          AI.move();
        } else if (GAME.state.current_player.name === "AI") {
          GAME.state.current_player = P1;
        }
      }
      showCurrentPlayer();
      break;
  }
};
const viewController = (show, ...hide) => {
  hide.forEach(view => {
    view.style.display = "none";
  });
  show.id === "game-board"
    ? (show.style.display = "grid")
    : (show.style.display = "block");
};

const countDown = () => {
  viewController(
    GAME.view.countDown,
    GAME.view.playerMenu,
    GAME.view.letterMenu,
    GAME.view.winnerMenu,
    GAME.view.gameScreen
  );
  setTimeout(() => {
    document.querySelector(".count-down").textContent = "3";
  }, 1000);
  setTimeout(() => {
    document.querySelector(".count-down").textContent = "2";
  }, 2000);
  setTimeout(() => {
    document.querySelector(".count-down").textContent = "1";
  }, 3000);
  setTimeout(() => {
    document.querySelector(".count-down").textContent = "Game starts in...";
    viewController(
      GAME.view.gameScreen,
      GAME.view.playerMenu,
      GAME.view.letterMenu,
      GAME.view.playerMenu,
      GAME.view.winnerMenu,
      GAME.view.countDown
    );
    showCurrentPlayer();
    if (GAME.state.current_player.name === AI.name) {
      AI.move();
    }
    attachListeners();
  }, 4000);
};
const showPlayerMenu = () => {
  let players = [];
  let random = Math.floor(Math.random() * 2);
  viewController(
    GAME.view.playerMenu,
    GAME.view.letterMenu,
    GAME.view.winnerMenu,
    GAME.view.gameScreen,
    GAME.view.countDown
  );
  document.getElementById("one-player").addEventListener("click", () => {
    players = [P1, AI];
    GAME.state.two_player = false;
    GAME.state.current_player = players[random];
    showLetterMenu();
  });
  document.getElementById("two-player").addEventListener("click", () => {
    players = [P1, P2];
    GAME.state.two_player = true;
    GAME.state.current_player = players[random];
    showLetterMenu();
  });
};
const showLetterMenu = () => {
  viewController(
    GAME.view.letterMenu,
    GAME.view.playerMenu,
    GAME.view.winnerMenu,
    GAME.view.gameScreen,
    GAME.view.countDown
  );
  document.getElementById("letter-x").addEventListener("click", () => {
    P1.letter = "X";
    GAME.state.two_player ? (P2.letter = "O") : (AI.letter = "O");
    countDown();
  });
  document.getElementById("letter-o").addEventListener("click", () => {
    P1.letter = "O";
    GAME.state.two_player ? (P2.letter = "X") : (AI.letter = "X");
    countDown();
  });
};
showPlayerMenu();

            
          
!
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