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

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

              
                #tic_tac_toe

              
            
!

CSS

              
                @import url('https://fonts.googleapis.com/css?family=Comfortaa&display=swap');

* {
  font-family: 'Comfortaa', cursive;
}

#tic_tac_toe {
  background-image: linear-gradient(#1fa5ff 0% 30%, #57f9ff 70% 100%);
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tiles {
  --cell-size: 15vmin;
  --shadow-opacity: 0.4;
  background-color: rgba(#000000, 0.15);
  padding: 10vmin;
  border-radius: 5vmin;
  display: grid;
  grid-template-rows: repeat(3, var(--cell-size));
  grid-template-columns: repeat(3, var(--cell-size));
  grid-gap: 1.75vmin;
  box-shadow: 0 1.5vmin rgba(#000000, var(--shadow-opacity));
}

.tile {
  --shadow-size: 0.75vmin;
  --transition-time: 150ms;
  background-color: #ffc417;
  background-image: linear-gradient(to bottom right, rgba(#ffffff, 0.4) 0 30%, rgba(#ffffff, 0) 70% 100%);
  min-width: 0;
  min-height: 0;
  padding: 0;
  margin: 0;
  border: none;
  border-radius: 2vmin;
  outline: none;
  box-shadow:
    0 var(--shadow-size) rgba(#000000, var(--shadow-opacity)),
    0 0 0 rgba(#000000, var(--shadow-opacity)) inset;
  transition:
    background-color var(--transition-time) ease-out,
    box-shadow var(--transition-time) ease-out,
    transform var(--transition-time) ease-out;
  &:active:not(.disabled), &.active, &.disabled.active {
    box-shadow:
      0 0 rgba(#000000, var(--shadow-opacity)),
      0 var(--shadow-size) calc(var(--shadow-size) * 2) rgba(#000000, var(--shadow-opacity)) inset;
    transform: translateY(var(--shadow-size));
  }
  &.disabled {
    background-color: #9f9f9f;
  }
  &.active {
    background-color: #e2e2e2;
  }
  &.match {
    background-color: #ffe11f;
  }
}

.turn {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  vertical-align: top;
}

.turn-0 {
  --draw-time: 250ms;
  position: relative;
  &:before, &:after {
    content: '';
    background-color: #0049bf;
    width: 12%;
    height: 0;
    position: absolute;
    top: 22%;
    transform-origin: top center;
  }
  &:before {
    left: 15.5%;
    transform: rotate(-45deg);
    animation: turn-0 var(--draw-time) ease-out forwards;
  }
  &:after {
    right: 15.5%;
    transform: rotate(45deg);
    animation: turn-0 var(--draw-time) ease-out var(--draw-time) forwards;
  }
}

@keyframes turn-0 {
  0%   { height: 0; }
  100% { height: 80%; }
}

.turn-1 {
  // circumference = 2 * PI * 10 (rounded to 10 thousandths)
  transform: rotate(-90deg);
  animation: turn-1 500ms ease-out forwards;
}

@keyframes turn-1 {
  0%   { stroke-dasharray: 0 62.8319; }
  100% { stroke-dasharray: 62.8319 62.8319; }
}

.modal-window {
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  transform: scale(0);
  transition: transform 250ms ease-out;
  &.shown {
    transform: scale(1);
  }
}

.dialog-box {
  font-size: 16px;
  text-align: center;
  background-image: linear-gradient(
    to bottom right,
    rgba(#dfdfdf, 0.90) 0% 30%,
    rgba(#ffffff, 0.90) 70% 100%);
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  p {
    padding: 0;
    margin: 0 0 0.5em 0;
    &:last-child {
      margin: 0;
    }
  }
}

.dialog-content {
  padding: 0.5em 0;
}

.btn {
  --shadow-size: 0.75vmin;
  --shadow-opacity: 0.5;
  padding: 0.5em 0.8em;
  &:active {
    --shadow-opacity: 0.25;
  }
}

.btn-turn {
  width: 3em;
  height: 3em;
  padding: 0;
  vertical-align: middle;
}

.text-bold {
  font-weight: bold;
}

              
            
!

JS

              
                // Title of the game
const GameTitle = 'TicTacToe v.3.5';

// 'Player' of the game
const Player = {
  X: 1,
  O: 2
};

// The player name
const PlayerName = ['', 'X', 'O'];

// AI Difficulty
const Difficulty = {
  Easy: 1,
  Medium: 2,
  Hard: 3
};

// Match count (used for AI)
const Matches = {
  Two: 2,
  One: 4
};

// Available combinations for the game
const Combinations = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6],
];

class TicTacToe extends React.Component {
  // Class constructor
  constructor(props) {
		super(props);
    
    // React state
    this.state = {
      buttons: [],
      aiPlayer: 0,
      aiDifficulty: 0,
      turn: 0,
      play: true,
      match: [],
      showDialog: true,
      winningPlayer: '',
      dialogStep: 0
    }
	}
  
  // ReactJS componentDidMount() method to initialize
	componentDidMount() {
    this.initialize();
  }
  
  // Initialize the game
  async initialize() {
    await this.setState({ aiPlayer : 0 });
    await this.setState({ aiDifficulty : 0 });
    
    await this.playAgain();
    
    this.setState({ showDialog : true });
    this.setState({ dialogStep : 0 });
  }
  
  // Start the game with same settings
  async playAgain() {
    await this.setState({ buttons : [] });
    await this.setState({ turn : ((this.state.aiPlayer === Player.X) ? Player.O : Player.X) });
    await this.setState({ play : true });
    await this.setState({ match : [] });
    await this.setState({ winningPlayer : '' });
    await this.setState({ showDialog : false });
    await this.setState({ dialogStep : 4 });

    this.createMap();

    if (this.state.aiPlayer === Player.X) {
      this.robotMove();
    }
  }
  
  // Creates the tic tac toe map
  createMap() {
    let buttons = [];
    
    for (let i = 0; i < 9; i++) {
      buttons.push({
        player: 0,
        active: false,
        match: false,
      });
    }
    
    this.setState({ buttons : buttons });
  }
  
  // Event when the tile is clicked
  tileClick(e) {
    if (this.state.play === true) {
      if (this.state.turn === this.state.aiPlayer) {
        return false;
      }

      let elm = e.target;

      this.humanMove(elm);
    }
  }
  
  // Proceed to next step of the dialog
  proceedToNext() {
    this.setState({ dialogStep : this.state.dialogStep + 1 });
  }
  
  // Choose the opponent to play with
  chooseOpponent(isRobot) {
    if (isRobot === true) {
      this.proceedToNext();
    }
    else {
      this.setState({ turn : Player.X });
      this.setState({ dialogStep : 4 });
      this.setState({ showDialog : false });
    }
  }
  
  // Choose your player (VS AI)
  choosePlayer(chosenPlayer) {
    this.setState({ aiPlayer : ((chosenPlayer === Player.X) ? Player.O : Player.X) });

    this.proceedToNext();
  }
  
  // Choose the AI difficulty
  async chooseDifficulty(difficulty) {
    await this.setState({ aiDifficulty : difficulty });

    await this.setState({ dialogStep : 4 });
    await this.setState({ showDialog : false });

    if (this.state.aiPlayer === Player.X) {
      this.robotMove();
    }
  }
  
  // Analyze the provided combination if the player gets
  // 3 consecutives. For AI purposes, +2 of each was added
  // if has 2 combinations. +4 if has 1 combination.
  analyzeCombination(open) {
    open.sort();

    let countX = 0;
    let countO = 0;

    for (let i in open) {
      if (open[i] === Player.X) {
        countX++;
      }
      else if (open[i] === Player.O) {
        countO++;
      }
    }

    if (countX === 3) {
      return Player.X;
    }
    else if (countO === 3) {
      return Player.O;
    }
    else if (countX === 2) {
      return Player.X + Matches.Two;
    }
    else if (countO === 2) {
      return Player.O + Matches.Two;
    }
    else if (countX === 1) {
      return Player.X + Matches.One;
    }
    else if (countO === 1) {
      return Player.O + Matches.One;
    }
    else {
      return null;
    }
  }
  
  // Create array of opened combination
  createOpened(combination) {
    let open = [];

    for (let i = 0; i < combination.length; i++) {
      let index = combination[i];

      open.push(this.state.buttons[index].player);
    }
    
    return open;
  }
  
  // Find the combinations of the opened tiles
  findCombination() {
    for (let i = 0; i < Combinations.length; i++) {
      let combination = Combinations[i];
      let open = this.createOpened(combination);
      let analysis = this.analyzeCombination(open);

      if (analysis === Player.X || analysis === Player.O) {
        this.setState({ play : false });
        this.setState({ match : combination });

        return true;
      }
    }

    return false;
  }
  
  // Get the buttons that aren't yet opened
  getFreeButtons() {
    let freeButtons = [];

    for (let i = 0; i < this.state.buttons.length; i++) {
      if (this.state.buttons[i].match === true) {
        continue;
      }
      
      if (this.state.buttons[i].active === false) {
        freeButtons.push(i);
      }
    }

    return freeButtons;
  }
  
  // Insert the possible turn of AI
  robotInsertTurn(combination) {
    let turn = null;

    for (let j = 0; j < combination.length; j++) {
      if (this.state.buttons[combination[j]].player === 0) {
        turn = combination[j];
        
        break;
      }
    }

    return turn;
  }
  
  // Random move by AI
  robotRandom() {
    let freeButtons = this.getFreeButtons();
    let random = Math.round(Math.random() * (freeButtons.length - 1));

    if (random >= 0) {
      return freeButtons[random];
    }
    else {
      return null;
    }
  }
  
  // Find combination for AI move
  robotCombinaton(selectedMatches) {
    let turn = null;
    
    for (let i = 0; i < Combinations.length; i++) {
      let combination = Combinations[i];
      let open = this.createOpened(combination);
      let analysis = this.analyzeCombination(open);
    
      // First priority is 2 matches, then 1
      if (analysis === selectedMatches) {
        turn = this.robotInsertTurn(combination);

        break;
      }
    }

    return turn;
  }
  
  // Attack move by AI
  robotAttack(tileIndex) {
    if (tileIndex === null) {
      tileIndex = this.robotCombinaton(this.state.aiPlayer + Matches.Two);
    }

    if (tileIndex === null) {
      tileIndex = this.robotCombinaton(this.state.aiPlayer + Matches.One);
    }

    return tileIndex;
  }
  
  // Defend move by AI
  robotDefend() {
    let tileIndex = null;
    let human = (this.state.aiPlayer === Player.X) ? Player.O : Player.X;

    tileIndex = this.robotCombinaton(human + Matches.Two);

    return tileIndex;
  }
  
  // Move of the player (AI)
  robotMove() {
    if (this.state.turn === this.state.aiPlayer) {
      let tileIndex = null;

      switch (this.state.aiDifficulty) {
        case Difficulty.Easy:
          tileIndex = this.robotRandom();

          break;
        case Difficulty.Medium:
          tileIndex = this.robotAttack(tileIndex);

          if (tileIndex === null) {
            tileIndex = this.robotRandom();
          }

          break;
        case Difficulty.Hard:
          tileIndex = this.robotCombinaton(this.state.aiPlayer + Matches.Two);

          if (tileIndex === null) {
            tileIndex = this.robotDefend();
          }

          if (tileIndex === null) {
            tileIndex = this.robotCombinaton(this.state.aiPlayer + Matches.One);
          }

          if (tileIndex === null) {
            tileIndex = this.robotRandom();
          }

          break;
      }

      if (tileIndex !== null) {
        this.makeDecision(tileIndex);
      }
    }
  }
  
  // Move of the player (human)
  async humanMove(elm) {
    if (!elm.classList.contains('active')) {
      let tileIndex = elm.dataset.tile;

      await this.makeDecision(tileIndex);
      
      if (this.state.aiPlayer === this.state.turn) {
        this.robotMove();
      }
    }
  }
  
  // Make decision on rendering the board
  async makeDecision(tileIndex) {
    let buttons = this.state.buttons;
    
    if (tileIndex !== null) {
      buttons[tileIndex].active = true;
      buttons[tileIndex].player = this.state.turn;
    }
    
    this.setState({ buttons: buttons });

    if (this.findCombination() === true) {
      this.decideGameWin();

      return;
    }

    if (this.findAnotherTile() === false) {
      this.setState({ showDialog : true });

      return;
    }

    if (this.state.turn === Player.X) {
      await this.setState({ turn : Player.O });
    }
    else if (this.state.turn === Player.O) {
      await this.setState({ turn : Player.X });
    }
  }
  
  // Changes the buttons color into match
  changeButtonsToMatch() {
    let buttons = this.state.buttons;
    
    for (let i = 0; i < this.state.match.length; i++) {
      let j = this.state.match[i];

      buttons[j].match = true;
    }
    
    this.setState({ buttons: buttons });
  }
  
  // Find another available tile
  findAnotherTile() {
    let hasTile = false;

    for (let i = 0; i < this.state.buttons.length; i++) {
      if (this.state.buttons[i].active === false) {
        hasTile = true;

        break;
      }
    }

    return hasTile;
  }

  // Game win event
  decideGameWin() {
    this.changeButtonsToMatch();

    this.setState({ showDialog : true });
    this.setState({ winningPlayer : PlayerName[this.state.turn] });
  }
  
  // Render the value of each tiles
  renderTileValue(i) {
    if (this.state.buttons[i].player === Player.X) {
      return (
        <div className="turn turn-0"></div>
      )
    }
    else if (this.state.buttons[i].player === Player.O) {
      return(
        <svg viewBox="0 0 30 30" className="turn turn-1">
          <circle fill="transparent"
                  stroke="#d10827"
                  stroke-width="3"
                  r="10" cx="15" cy="15" />
        </svg>
      )
    }
  }
  
  // Render the tiles
  renderTiles() {
    let tiles = [];
    
    for (let i = 0; i < this.state.buttons.length; i++) {
      let className = "tile";
      
      if (this.state.buttons[i].active === true) {
        className += " active";
      }
      
      if (this.state.buttons[i].match === true) {
        className += " match";
      }
      
      if (this.state.play === false) {
        className += " disabled";
      }
      
      tiles.push(
        <button
          data-tile={ i }
          className={ className }
          onClick={ this.tileClick.bind(this)}>{ this.renderTileValue(i) }
        </button>
      );
    }
    
    return tiles;
  }
  
  // Render modal dialog boxes 
  renderModal() {
    if (this.state.dialogStep === 0) {
      return (
        <div className="dialog-box">
          <div className="dialog-content">
            <p className="text-bold">{ GameTitle }</p>
            <p>Welcome to the example TicTacToe game I made.</p>
            <p>You may play this with your friend, or versus the computer.</p>
          </div>
          <div className="dialog-content">
            <button className="btn tile"
                    onClick={ this.proceedToNext.bind(this) }>
              Proceed to Game</button>
          </div>
        </div>
      );
    }
    else if (this.state.dialogStep === 1) {
      return (
        <div class="dialog-box">
          <div class="dialog-content">
            <p class="text-bold">{ GameTitle }</p>
            <p>Choose your opponent to play with.</p>
          </div>
          <div class="dialog-content">
            <button class="btn tile"
                    onClick={ this.chooseOpponent.bind(this, false) }>
              Friend</button> <button class="btn tile"
                    onClick={ this.chooseOpponent.bind(this, true) }>
              Computer</button>
          </div>
        </div>
      );
    }
    else if (this.state.dialogStep === 2) {
      return (
        <div class="dialog-box">
          <div class="dialog-content">
            <p class="text-bold">{ GameTitle }</p>
            <p>Choose your player.</p>
          </div>
          <div class="dialog-content">
            <button class="btn btn-turn tile"
                    onClick={ this.choosePlayer.bind(this, Player.X) }>
              <div class="turn turn-0"></div>
            </button> <button class="btn btn-turn tile"
                    onClick={ this.choosePlayer.bind(this, Player.O) }>
              <svg viewBox="0 0 30 30"
               class="turn turn-1">
                <circle fill="transparent"
                        stroke="#d10827"
                        stroke-width="3"
                        r="10" cx="15" cy="15" />
              </svg>
            </button>
          </div>
        </div>
      );
    }
    else if (this.state.dialogStep === 3) {
      return (
        <div class="dialog-box">
          <div class="dialog-content">
            <p class="text-bold">{ GameTitle }</p>
            <p>Choose the computer's difficulty.</p>
          </div>
          <div class="dialog-content">
          </div>
          <div class="dialog-content">
            <button class="btn tile"
                    onClick={ this.chooseDifficulty.bind(this, Difficulty.Easy) }>
              Easy</button> <button class="btn tile"
                    onClick={ this.chooseDifficulty.bind(this, Difficulty.Medium) }>
              Medium</button> <button class="btn tile"
                    onClick={ this.chooseDifficulty.bind(this, Difficulty.Hard) }>
              Hard</button>
          </div>
        </div>
      );
    }
    else if (this.state.dialogStep === 4) {
      let endMessage = '';
      
      if (this.state.winningPlayer !== '') {
        endMessage = (
          <p>
            Player '{ this.state.winningPlayer }' won the game! Would you like to play again?
          </p>
        );
      }
      else {
        endMessage = (
          <p>
            The match is a draw! Would you like to play again?
          </p>
        );
      }
      
      return (
        <div class="dialog-box">
          <div class="dialog-content">
            <p class="text-bold">Game ended!</p>
            { endMessage }
          </div>
          <div class="dialog-content">
            <button class="btn tile"
                    onClick={ this.initialize.bind(this) }>
              Start New</button> <button class="btn tile"
                    onClick={ this.playAgain.bind(this) }>
              Play Again</button>
          </div>
        </div>
      );
    }
  }
  
  // Method to render the ReactJS Component
  render() {
    let elms = [];
    
    elms.push(<div className="tiles">{ this.renderTiles() }</div>);
    
    let modalWindow = "modal-window";
    
    if (this.state.showDialog === true) {
      modalWindow += " shown";
    }
    
    elms.push(<div className={ modalWindow }>{ this.renderModal() }</div>);
    
    return elms;
  }
}

ReactDOM.render(
  <TicTacToe />,
  document.querySelector('#tic_tac_toe')
);

              
            
!
999px

Console