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 is required to process package imports. If you need a different preprocessor remove all packages first.

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

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.

Editor Settings

Code Indentation

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

Visit your global Editor Settings.

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.

HTML

            
              <div class="modal__background">
  <div class="modal__window">
    <p>Tic Tac Toe</p>
    <p>x or o?</p>
    <button class="modal__btn btn">x</button>
    <button class="modal__btn btn">o</button>
  </div>
</div>

<div class="container">
  <div class="board">
    <div class="row">
      <span class="tile btn" data-lines="0,3,6"></span>
      <span class="tile btn" data-lines="0,4"></span>
      <span class="tile btn" data-lines="0,5,7"></span>
    </div>

    <div class="row">
      <span class="tile btn" data-lines="1,3"></span>
      <span class="tile btn" data-lines="1,4,6,7"></span>
      <span class="tile btn" data-lines="1,5"></span>
    </div>

    <div class="row">
      <span class="tile btn" data-lines="2,3,7"></span>
      <span class="tile btn" data-lines="2,4"></span>
      <span class="tile btn" data-lines="2,5,6"></span>
    </div>
  </div>
</div>
            
          
!

CSS

            
              $tile-margin: .25em;
$main-color: #00ADB5;
$highlight-color: #303841;

html {
  box-sizing: border-box;
  font-size: 36px;
  font-family: "Helvetica Neue", Helvetica, sans-serif;
  height: 100%;
}

.container {
  height: 100vh;
  display: flex;
  align-items: center;
}

*, *:before, *:after {
  box-sizing: inherit;
}

.board {
  margin: 0 auto;
}

.row {
  display: flex;
  flex-flow: row wrap;
  margin-bottom: $tile-margin;
  &:nth-child(3) {
    margin-bottom: 0;
  }
}

.tile {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  width: 3em;
  height: 3em;
  margin-right: $tile-margin;
}

// Ripple effect from https://codepen.io/sebj54/pen/oxluI
.btn {
  position: relative;
  padding: 0;
  overflow: hidden;
  border-width: 0;
  outline: none;
  border-radius: 2px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, .6);
  background-color: $main-color;
  color: #ecf0f1;
  transition: background-color .3s;
  cursor: pointer;
  
  &:nth-child(3) {
    margin-right: 0;
  }
  
  &.highlight {
    background-color: $highlight-color;
  }
  
  &:focus {
    background-color: $main-color;
  }
  
  & > * {
    position: relative;
  }
  
  &:before {
    content: "";

    position: absolute;
    top: 50%;
    left: 50%;

    display: block;
    width: 0;
    padding-top: 0;

    border-radius: 100%;

    background-color: rgba(236, 240, 241, .3);

    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
  }
  
  &:active:before {
    width: 120%;
    padding-top: 120%;

    transition: width .2s ease-out, padding-top .2s ease-out;
  }
}

.modal { 
 
  &__background {
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0; 
    right: 0; 
    background: #000; 
    background: rgba(0, 0, 0, 0.85);
    z-index: 3; 
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  &__window {
    text-align: center;
    color: white;
    line-height: 1.5em;
  }
  
  &__btn {
    font-size: .75em;
    height: 2em;
    width: 2em;
  }
  
}

.disabled {
  cursor: auto;
}
            
          
!

JS

            
              (function() {
  "use strict";
  
  // Logger 
  
  function Logger(name) {
    this.loggerName = name;
    this.logging = false;
    this.verboseLogging = false;
  }
  
  Logger.prototype.log = function (msg) {
    if(this.logging) {
      console.log(this.loggerName + ": " + msg);
    }
  }
  
  Logger.prototype.verboseLog = function(msg) {
    if(this.verboseLogging) {
      console.log(this.loggerName + ": " + msg);
    }
  }
  
  const tileLogger = new Logger("Tile");
  const lineLogger = new Logger("Line");
  const ticTacToeLogger = new Logger("TicTacToe");
  
  // Utils 
  
  function Utils() {}
  
  Utils.prototype.getRandomNum = function (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  
  const utils = new Utils();
  
   // Tile
  
  function Tile(el, logger) {
    this.el = el;
    this.token = "";
    this.lineNums = el.getAttribute("data-lines").split(",").map(str => parseInt(str));
    this.logger = logger;
  }
  
  Tile.prototype.type = "tile";
  
  Tile.prototype.setToken = function(newToken) {
    this.logger.verboseLog("setToken: " + newToken)
    this.el.textContent = newToken; 
    this.token = newToken;
    return this.token;
  }
  
  Tile.prototype.getToken = function() {
    this.logger.verboseLog("getToken: " + this.token);
    return this.token;
  }
  
  Tile.prototype.addClass = function(className) {
    this.logger.log("addClass: " + className);
    const el = this.el;
    if (el.classList) {
      el.classList.add(className);
    } else {
      el.className += ' ' + className;
    }
  }
  
  Tile.prototype.removeClass = function(className) {
    this.logger.log("removeClass: " + className);
    const el = this.el;
    if (el.classList) {
      el.classList.remove(className);
    } else {
      el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
    }
  }
  
  // Line
  
  function Line(tiles, logger) {
    this.logger = logger;
    this.tiles = tiles;
    this.highlighted = false;
  }
  
  Line.prototype.type = "line";
  
  Line.prototype.containsTokens = function(options) {
    // options ex: {"x": 2, "": 1}
    this.logger.verboseLog("containsTokens");
    for(let t in options) {
      let numTokens = this.tiles.filter(tile => tile.token === t).length;
      if(numTokens !== options[t]) {
        return null;
      }
    }
    return this;
  }
  
  Line.prototype.highlight = function() {
    this.logger.log("highlight");
    this.tiles.forEach(tile => {
      tile.addClass("highlight");
    });
    this.highlighted = true;
  }
  
  Line.prototype.unhighlight = function() {
    this.logger.log("unhighlight");
    this.tiles.forEach(tile => {
      tile.removeClass("highlight");
    });
    this.highlighted = false;
  }
  
  // Main game functionality
  
  function TicTacToe(utils, logger) {
    this.utils = utils;
    this.logger = logger;
    this.userToken = null;
    this.computerToken = null;
    this.board = null;
    this.lines = [];
    this.tiles = [];
  }
  
  TicTacToe.prototype.setUserToken = function(token) {
    this.logger.log("setUserToken: " + token)
    this.userToken = token;
    this.computerToken = token === "x" ? "o" : "x";
    return this.userToken;
  }
  
  TicTacToe.prototype.setBoard = function(board) {
    // Grab the tiles from the board
    this.board = board;
    this.tiles = Array.from(board.querySelectorAll(".tile")).map(tile => new Tile(tile, tileLogger));
    // Create "lines" for all possible combos
    for(let i = 0; i < 8; i++) {
      let tiles = this.tiles.filter(tile => tile.lineNums.indexOf(i) > -1);
      this.lines = this.lines.concat(new Line(tiles, lineLogger));
    }
  }
  
  TicTacToe.prototype.resetBoard = function(nextTurn) {
    this.logger.log("resetBoard");
    let highlightedLine = this.lines.find(line => line.highlighted);
    if(highlightedLine) {
      highlightedLine.unhighlight();
    }
    this.tiles.forEach(tile => {
      tile.setToken("");
      tile.removeClass("disabled");
    });
  }
  
  TicTacToe.prototype.checkBoard = function(next) {
    this.logger.log("checkBoard");
    
    let gameOver = false;
    
    const compWinningLn = this.lines.find(line => {
      return line.tiles.every(tile => tile.token === this.computerToken);
    });
    
    const userWinningLn = this.lines.find(line => {
      return line.tiles.every(tile => tile.token === this.userToken);
    });
    
    if(compWinningLn || userWinningLn) {
      gameOver = true;
      let winningLn = compWinningLn || userWinningLn;
      winningLn.highlight();
    }
    
    if(!this.getEmptyTiles().length) {
      gameOver = true;
    }
    
    if(gameOver) {
     this.logger.log("Game over");
     setTimeout(this.resetBoard.bind(this), 500);
    }
    
    setTimeout(next, 500);
  }
  
  TicTacToe.prototype.init = function() {
    this.logger.log("init");
    this.computerTurn();
  }
  
  TicTacToe.prototype.getEmptyTiles = function() {
    return this.tiles.filter(tile => tile.getToken() === "");
  }
  
  TicTacToe.prototype.getRandomTile = function() {
    this.logger.log("getRandomTile");
    let emptyTiles = this.getEmptyTiles();
    let rand = this.utils.getRandomNum(0, emptyTiles.length - 1);
    return emptyTiles[rand];
  }
  
  TicTacToe.prototype.getLine = function(tokenOptions) {
    this.logger.verboseLog("getLine")
    for(let i = 0; i < this.lines.length; i++) {
      let line = this.lines[i].containsTokens(tokenOptions);
      if(line) {
        return line;
      }
    }
  }
  
  TicTacToe.prototype.userTurn = function(tile) {
    this.logger.log("userTurn");
    tile.setToken(this.userToken);
    disablePlay();
    this.checkBoard(this.computerTurn.bind(this));
  }
  
  TicTacToe.prototype.getBestMove = function() {
    let computerWinOpt = {};
    computerWinOpt[this.computerToken] = 2;
    computerWinOpt[""] = 1;
    let computerBlockOpt = {};
    computerBlockOpt[this.userToken] = 2;
    computerBlockOpt[""] = 1;
    let computerNextBestOpt = {};
    computerNextBestOpt[this.computerToken] = 1;
    computerNextBestOpt[""] = 2;
    
    const computerWinLn = this.getLine(computerWinOpt);
    const computerBlockLn = this.getLine(computerBlockOpt);
    const computerNextBestLn = this.getLine(computerNextBestOpt);
    
    if(computerWinLn) {
      return computerWinLn.tiles.find(tile => tile.token === "");
    } else if(computerBlockLn) {
      return computerBlockLn.tiles.find(tile => tile.token === "");
    } else if(computerNextBestLn) {
      return computerNextBestLn.tiles.find(tile => tile.token === "");
    } else {
      return this.getRandomTile()
    }
  }
  
  TicTacToe.prototype.computerTurn = function() {
    this.logger.log("computerTurn");
    const tile = this.getBestMove();
    tile.setToken(this.computerToken);
    this.checkBoard(enablePlay);
  }
  
  // Initialization of game
  
  var game = new TicTacToe(utils, ticTacToeLogger);
  
  game.setBoard(document.querySelector(".board"));
  
  function boardClickHandler(e) {
    if(e.target.textContent === "") {
      // Find the Tile that has the el that matches e.target
      let tile = game.tiles.find(tile => tile.el === e.target);
      game.userTurn(tile);
    }
  }
  
  function enablePlay() {
    let tiles = game.tiles.filter(tile => tile.getToken() === "");
    tiles.forEach(tile => tile.removeClass("disabled"));
    game.board.addEventListener("click", boardClickHandler);
  }
  
  function disablePlay() {
    game.tiles.forEach(tile => tile.addClass("disabled"));
    game.board.removeEventListener("click", boardClickHandler);
  }
  
  function handleModalClick(e) {
    if(e.target.nodeName.toLowerCase() === "button") {
      game.setUserToken(e.target.textContent);
      game.init();
      let modal = document.querySelector(".modal__background");
      modal.parentNode.removeChild(modal);
    }
  }
  
  document.querySelector(".modal__window").addEventListener("click", handleModalClick);
  
})();
            
          
!
999px

Console