Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs 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 its URL and the proper URL extension.

+ 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

Auto Save

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

              
                <header>
    <h1>Tic-tac-toe</h1>
    <p><span id="player-turn"></span>'s turn</p>
  </header>
  <main id="gameboard">
    <div class="line r r-1"></div>
    <div class="line r r-2"></div>
    <div class="line c c-1"></div>
    <div class="line c c-2"></div>
  </main>
  <div id="num-of-players">
    <p>One Player</p>
    <div id="toggle-switch">
      <div id="toggle-btn"></div>
    </div>
    <p>Two Player</p>
  </div>
  <div id="gameover-msg">
    <h3 id="winner"></h3>
    <button id="reset-btn">New Game</button>
  </div>
              
            
!

CSS

              
                @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600&display=swap');

@mixin mainFlex {
  display: flex;
  justify-content: center;
  align-items: center;
}

$onyx: #393E41;
$ivory: #F6F7EB;
$green: #16b550;

* {
  margin: 0;
  padding: 0;
}

body {
  @include mainFlex();
  flex-direction: column;
  font-family: 'Montserrat', sans-serif;
  color: $ivory;
  height: 100vh;
  background: $onyx;
  position: relative;
}

header {
  text-align: center;
  margin-bottom: 30px;
  h1 {
    margin-bottom: 20px;
  }
  #player-turn {
    font-weight: 600;
  }
}

#gameboard {
  display: flex;
  flex-wrap: wrap;
  width: 300px;
  height: 300px;
  position: relative;
  .tile {
    @include mainFlex();
    font-size: 1.8rem;
    font-weight: 600;
    width: 100px;
    height: 100px;
    box-sizing: border-box;
    &:hover {
      cursor: pointer;
    }
  }
  .line {
    position: absolute;
    z-index: 1;
    background: $ivory;
    border-radius: 2px;
  }
  .r {
    width: 300px;
    height: 4px;
  }
  .r-1 {
    top: 98px;
  }
  .r-2 {
    bottom: 98px;
  }
  .c {
    width: 4px;
    height: 300px;
  }
  .c-1 {
    left: 98px;
  }
  .c-2 {
    right: 98px;
  }
}

#num-of-players {
  @include mainFlex();
  margin-top: 30px;
  #toggle-switch {
    margin: 0 10px 0 10px;
    width: 50px;
    height: 25px;
    border-radius: 100px;
    border: 2px solid $ivory;
    #toggle-btn {
      float: left;
      width: 25px;
      height: 25px;
      border-radius: 50%;
      background: $ivory;
      &:hover {
        cursor: pointer;
      }
    }
  }
}


#gameover-msg {
  position: absolute;
  z-index: 2;
  text-align: center;
  color: $onyx;
  width: 200px;
  height: 150px;
  background: $ivory;
  border-radius: 8px;
  box-shadow: 0 0 5px black;
  display: none;
  h3 {
    margin-top: 35px;
    margin-bottom: 20px;
  }
  button {
    font-family: 'Montserrat', sans-serif;
    font-weight: 500;
    color: $ivory;
    margin: auto;
    padding: 8px;
    background: $green;
    border-radius: 4px;
    border: none;
    &:hover {
      cursor: pointer;
    }
  }
}
              
            
!

JS

              
                document.addEventListener('DOMContentLoaded', () => {

  const gameboard = document.getElementById('gameboard');
  const gameOverMsg = document.getElementById('gameover-msg');
  const winner = document.getElementById('winner');
  const resetBtn = document.getElementById('reset-btn');
  const playerToggleBtn = document.getElementById('toggle-btn');
  const playerTurn = document.getElementById('player-turn');
  playerTurn.textContent = 'X';

  const $ivory = '#F6F7EB';
  const $green = '#16b550';

  let tilesArr = [
    0, 1, 2,
    3, 4, 5,
    6, 7, 8
  ];

  let isOnePlayer = true;
  let isComputerTurn = false;
  let isXTurn = true;
  let isGameOver = false;
  let validPlays = 0;
  let winningCombo;

  const addTiles = () => {
    tilesArr.forEach((index) => {
      const tile = document.createElement('div');
      tile.id = index;
      tile.classList.add('tile');
      tile.addEventListener('click', () => handleClick(tile));
      gameboard.appendChild(tile);
    });
  }

  addTiles();

  const tiles = document.querySelectorAll('.tile');

  const handleClick = (tile) => {
    if (isOnePlayer === true) {
      if (isXTurn && tile.textContent === '') {
        markX(tile);
        isComputerTurn = true;
        !isGameOver ? 
        setTimeout(() => computerMarkO(), 1000) :
        false;
      }
    }
    if (isOnePlayer === false) {
      if (isXTurn && tile.textContent === '') {
        markX(tile);
      } else if (!isXTurn && tile.textContent === '') {
        markO(tile);
      }
    }
  }

  const markX = (tile) => {
    tile.textContent = 'X';
    tilesArr[tile.id] = 'X';
    validPlays++;
    isXTurn = !isXTurn;
    isXTurn ? playerTurn.textContent = 'X' : playerTurn.textContent = 'O';
    checkForWin();
    validPlays === 9 ? displayMessage() : false;
  }

  const markO = (tile) => {
    tile.textContent = 'O';
    tilesArr[tile.id] = 'O';
    validPlays++;
    isXTurn = !isXTurn;
    isXTurn ? playerTurn.textContent = 'X' : playerTurn.textContent = 'O';
    checkForWin();
    validPlays === 9 ? displayMessage() : false;
  }

  const getRandomTile = () => {
    const availTilesArr = [];
    for (let i = 0; i < tilesArr.length; i++) {
      if (tilesArr[i] !== 'X' && tilesArr[i] !== 'O') {
        availTilesArr.push(i);
      }
    }
    const randomIndex = Math.floor(Math.random() * availTilesArr.length);
    return availTilesArr[randomIndex];
  }

  const computerMarkO = () => {
    if (isComputerTurn) {
      let randomID = getRandomTile();
      let randomTile = document.getElementById(randomID);
      randomTile.textContent = 'O';
      tilesArr[randomID] = 'O';
      validPlays++;
      isXTurn = !isXTurn;
      isXTurn ? playerTurn.textContent = 'X' : playerTurn.textContent = 'O';
      checkForWin();
      validPlays === 9 ? displayMessage() : false;
    }
    isComputerTurn = false;
  }

  const checkForWin = () => {
    // winning combos
    // [0,1,2], [3,4,5], [6,7,8], [0,3,6], 
    // [1,4,7], [2,5,8], [0,4,8], [2,4,6]
    tilesArr[0] === tilesArr[1] &&
    tilesArr[1] === tilesArr[2] &&
    tilesArr[0] === tilesArr[2] ?
    gameOver(0) :
    false;

    tilesArr[3] === tilesArr[4] &&
    tilesArr[4] === tilesArr[5] &&
    tilesArr[3] === tilesArr[5] ?
    gameOver(1) :
    false;

    tilesArr[6] === tilesArr[7] &&
    tilesArr[7] === tilesArr[8] &&
    tilesArr[6] === tilesArr[8] ?
    gameOver(2) :
    false;

    tilesArr[0] === tilesArr[3] &&
    tilesArr[3] === tilesArr[6] &&
    tilesArr[0] === tilesArr[6] ?
    gameOver(3) :
    false;

    tilesArr[1] === tilesArr[4] &&
    tilesArr[4] === tilesArr[7] &&
    tilesArr[1] === tilesArr[7] ?
    gameOver(4) :
    false;

    tilesArr[2] === tilesArr[5] &&
    tilesArr[5] === tilesArr[8] &&
    tilesArr[2] === tilesArr[8] ?
    gameOver(5) :
    false;

    tilesArr[0] === tilesArr[4] &&
    tilesArr[4] === tilesArr[8] &&
    tilesArr[0] === tilesArr[8] ?
    gameOver(6) :
    false;

    tilesArr[2] === tilesArr[4] &&
    tilesArr[4] === tilesArr[6] &&
    tilesArr[2] === tilesArr[6] ?
    gameOver(7) :
    false;

  }

  const gameOver = (val) => {
    isGameOver = true;
    winningCombo = val;
    switch (winningCombo) {
      case 0:
        tiles[0].style.color = $green;
        tiles[1].style.color = $green;
        tiles[2].style.color = $green;
        break;
      case 1:
        tiles[3].style.color = $green;
        tiles[4].style.color = $green;
        tiles[5].style.color = $green;
        break;
      case 2:
        tiles[6].style.color = $green;
        tiles[7].style.color = $green;
        tiles[8].style.color = $green;
        break;
      case 3:
        tiles[0].style.color = $green;
        tiles[3].style.color = $green;
        tiles[6].style.color = $green;
        break;
      case 4: 
        tiles[1].style.color = $green;
        tiles[4].style.color = $green;
        tiles[7].style.color = $green;
        break;
      case 5:
        tiles[2].style.color = $green;
        tiles[5].style.color = $green;
        tiles[8].style.color = $green;
        break;
      case 6:
        tiles[0].style.color = $green;
        tiles[4].style.color = $green;
        tiles[8].style.color = $green;
        break;
      case 7:
        tiles[2].style.color = $green;
        tiles[4].style.color = $green;
        tiles[6].style.color = $green;
    }
    displayMessage();
  }

  const displayMessage = () => {
    if (isGameOver) {
      setTimeout(() => {
        gameOverMsg.style.display = 'block';
        playerTurn.textContent === 'X' ? 
        winner.textContent = 'Player O Wins!' : 
        winner.textContent = 'Player X Wins!';
      }, 1000);
    } 
    if (!isGameOver) {
      gameOverMsg.style.display = 'block';
      winner.textContent = 'Tie Game!'
    }
  }

  const reset = () => {
    tiles.forEach((tile) => {
      tile.textContent = '';
      tile.style.color = $ivory;
    });
    tilesArr = [
      0, 1, 2,
      3, 4, 5,
      6, 7, 8
    ];
    winningCombo = '';
    isXTurn = true;
    isGameOver = false;
    validPlays = 0;
    playerTurn.textContent = 'X';
    gameOverMsg.style.display = 'none';
  }

  const handleNumPlayers = () => {
    isOnePlayer = !isOnePlayer;
    isOnePlayer ? 
    playerToggleBtn.style.float = 'left' : 
    playerToggleBtn.style.float = 'right';
  }

  resetBtn.addEventListener('click', () => reset());
  playerToggleBtn.addEventListener('click', () => handleNumPlayers());
});
              
            
!
999px

Console