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="main-container">
  <div class="game-board">
    <div class="box" data-boxnum="0">
      <p></p>
    </div>
    <div class="box" data-boxnum="1">
      <p></p>
    </div>
    <div class="box" data-boxnum="2">
      <p></p>
    </div>
    <div class="box" data-boxnum="3">
      <p></p>
    </div>
    <div class="box" data-boxnum="4">
      <p></p>
    </div>
    <div class="box" data-boxnum="5">
      <p></p>
    </div>
    <div class="box" data-boxnum="6">
      <p></p>
    </div>
    <div class="box" data-boxnum="7">
      <p></p>
    </div>
    <div class="box" data-boxnum="8">
      <p></p>
    </div>
  </div>
  <div class="config-menu">
    <div class="choose-mode top-margin">
      <p>1 Player or 2 Player mode?</p>
      <button id="one-player" type="button">1 Player</button>
      <button id="two-player" type="button">2 Player</button>
    </div>
    <div class="choose-icon top-margin">
      <p>X's or O's</p>
      <button id="x" type="button">X's</button>
      <button id="o" type="button">O's</button>
    </div>
    <div class="display-win">
      <h1>Winner! <span id="winner-icon"></span> wins!</h1>
      <p>Click to try again.</p>
    </div>
    <div class="display-draw">
      <h1>Draw</h1>
      <p>Click to try again.</p>
    </div>
  </div>
</div>

              
            
!

CSS

              
                @media screen and (max-width: 400px){
  .game-board {
    height: 200px !important;
    width: 200px !important;
  }
  
  .config-menu {
    width: 100% !important;
  }
  
  .box p {
    font-size: 20% !important;
  }
  
}

@media screen and (min-width: 401px) and (max-width: 600px){
  
  .game-board {
    height: 350px !important;
    width: 350px !important;
  }
  
  .config-menu {
    width: 100% !important;
  }
  
  .box p {
    font-size: 40% !important;
  }
  
}

@media screen and (min-width: 1200px){
  .game-board{
    height: 750px !important;
    width: 750px !important;
  }
}

body {
	background: linear-gradient(45deg, #fecea3, #ffffff, #fab7f8);
	-webkit-animation: Gradient 60s ease infinite;
	background-size: 600% 600%;
	-moz-animation: Gradient 60s ease infinite;
	animation: Gradient 60s ease infinite;
}

@-webkit-keyframes Gradient {
  0%{background-position:0% 50%}
  50%{background-position:100% 50%}
  100%{background-position:0% 50%}
}
@-moz-keyframes Gradient {
  0%{background-position:0% 50%}
  50%{background-position:50% 50%}
  100%{background-position:0% 50%}
}
@keyframes Gradient { 
  0%{background-position:0% 50%}
  50%{background-position:100% 50%}
  100%{background-position:0% 50%}
}
    
.main-container{
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.choose-icon {
  display: none;
}

.display-win {
  display: none;
}

.display-draw {
  display: none;
}

.game-board{
  height: 450px;
  width: 450px;
  outline: 5px solid black;
  display: flex;
  flex-wrap: wrap;
}

.box {
  height: 33.333399%;
  width: 33.3333999%;
  outline: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 10em;
  font-family: helvetica;
}

.config-menu{
  width: 320px;
  height: 150px;
  background: black;
  position: absolute;
  color: white;
  text-align: center;
  left: 0;
  right: 0;
  margin: auto;
}

.top-margin {
  margin-top: 40px;
}

.display-draw h1 {
  height: 70px;
}

.display-draw p {
  height: 30px;
}

.display-win h1 {
  height: 70px;
}

.display-win p {
  height: 30px;
}
              
            
!

JS

              
                'use strict';
//contains UI manipulating functions to hide/show content. Also binds all event listeners
const ControlUi = {
  bindEventListeners: function(){
    $('.box').click(function(){
      let currentPlayer = ManagePlayers.getCurrentPlayer();
      let boxTaken = $(this).text();
      
      if (boxTaken == 0 && Game.playing && Game.numPlayers === 1) { //if box isnt already occupied
        let loc = parseInt($(this).data('boxnum'));
        GameState.incrementTurns();
        GameState.move(loc, currentPlayer);
        ControlUi.displayMove(loc, currentPlayer);
        
        if (GameState.checkForVictory(GameState.currentState)){
          ControlUi.displayWin(currentPlayer);  
        } else if (GameState.checkForDraw(GameState.currentState)){
          ControlUi.displayDraw();
        } else {
          if (!GameState.boardIsEmpty(GameState.currentState)){ 
            console.log('abou to call ai');//if board is not empty AI takes a turn. If it is empty the user takes his turn
            Ai.takeTurn();
          }
        }
      } else { //game is two player mode
        console.log('in correct else');
        console.log(Game.playing);
        if (boxTaken == 0 && Game.playing){
          console.log('in here');
          let loc = parseInt($(this).data('boxnum'));
          GameState.incrementTurns();
          GameState.move(loc, currentPlayer);
          ControlUi.displayMove(loc, currentPlayer);
          
          if (GameState.checkForVictory(GameState.currentState)){
            ControlUi.displayWin(currentPlayer);
          } else {
            if (GameState.checkForDraw(GameState.currentState)){
              ControlUi.displayDraw(); 
            }
          }
        
        }
      }
    });
    $('#one-player').click(function(){
      Game.numPlayers = 1;
      $('.choose-mode').hide();
      $('.choose-icon').show();
    });
    
    $('#two-player').click(function(){
      Game.numPlayers = 2;
      $('.choose-mode').hide();
      $('.choose-icon').show();
    });
    
    $('#x').click(function(){
      if (Game.numPlayers === 1){
        ManagePlayers.playerOne.icon = 'x';
        ManagePlayers.computerPlayer.icon = 'o';
        $('.choose-icon').hide();
        $('.config-menu').hide();
        Game.playing = true;
      } else {
        ManagePlayers.playerOne.icon = 'x';
        ManagePlayers.playerTwo.icon = 'o';
        $('.choose-icon').hide();
        $('.config-menu').hide();
        Game.playing = true;
      }
    });
    
    $('#o').click(function(){
      if (Game.numPlayers === 1){
        ManagePlayers.playerOne.icon = 'o';
        ManagePlayers.computerPlayer.icon = 'x';
        $('.choose-icon').hide();
        $('.config-menu').hide();
        Game.playing = true;
      } else {
        ManagePlayers.playerOne.icon = 'o';
        ManagePlayers.playerTwo.icon = 'x';
        $('.choose-icon').hide();
        $('.config-menu').hide();
        Game.playing = true;
      }
    });
  },
  
  displayMove : function(loc, player){
    $('.box[data-boxnum= ' + loc + '] p').text(player.icon).css('color', player.iconColor);
  },
  
  displayWin : function(player){
    $('.config-menu').show();
    $('#winner-icon').text(player.icon);
    $('.display-win').show();
    Game.playing = false;
    $('.config-menu').click(function(){
      $('.display-win').hide();
      $(this).hide();
      GameState.reset();
      Game.playing = true;
    });
  },
  
  displayDraw : function(){
    $('.config-menu').show();
    $('.display-draw').show();
    Game.playing = false;
    $('.config-menu').click(function(){
      $('.display-draw').hide();
      $(this).hide();
      GameState.reset();
      Game.playing = true; 
    });
  }
 
}
                  

//starts the game
const Game = {
  playing: false,

  start: function(){
    ControlUi.bindEventListeners();
  }
}

//contains board state and winning/draw logic
const GameState = {
  currentState : [null, null, null, null, null, null, null, null, null],
  turns : 0,
  
  move: function(location, player){
    this.currentState[location] = player.icon;  
  },
  
  checkSame : function(board, loc1, loc2, loc3){
    let arr = [board[loc1], board[loc2], board[loc3]];
    return ((board[loc1] === board[loc2] && board[loc1] === board[loc3]) && arr.indexOf(null) === -1);
  },
  
  checkForVictory : function(board){
    let winningPositions = [
      [0,1,2], [3,4,5], [6,7,8],
      [0,3,6], [1,4,7], [2,5,8],
      [0,4,8], [2,4,6],
    ];
    
    for (let i = 0; i < winningPositions.length; i++){
      if(this.checkSame(board, winningPositions[i][0], winningPositions[i][1], winningPositions[i][2])){
        return board[winningPositions[i][0]]; //returns the icon of the player that one
      }
    }
    return false;
  },
  
  checkForDraw : function(board){
    return board.indexOf(null) === -1;
  },
  
  incrementTurns : function(){
    this.turns += 1;
  },
  
  reset : function(){
    this.currentState = [null, null, null, null, null, null, null, null, null];
    this.turns = 0;
    $('.box p').text('');
  },
  
  boardIsEmpty: function(board){
    return (board.indexOf('x') === -1 && board.indexOf('o') === -1);
  }
}

//contains player info, num, icon, currentPlayer logic etc.
const ManagePlayers = {
  playerOne : {iconColor: 'red'},
  playerTwo: {iconColor: 'green'},
  computerPlayer : {iconColor: 'green'},
  
  getCurrentPlayer : function(){
    return GameState.turns % 2 === 0 ? this.playerOne : this.playerTwo;
  }
}

const Ai = {
  takeTurn : function(){
    //run minimax - determine best move pass in minPlayer so the first time it runs, it will recurse to maxPlayer
    this.miniMax(ManagePlayers.computerPlayer.icon, ManagePlayers.playerOne.icon); //max player is o (computer), min player is x (human)
    // update game state with that move
    // display the move on the board to the used
    //increment turns by 1
    GameState.incrementTurns();
    //check for victory
    if (GameState.checkForVictory(GameState.currentState, ManagePlayers.computerPlayer.icon)){
      ControlUi.displayWin(ManagePlayers.computerPlayer); 
    }
  },
  
  miniMax : function(maxPlayer, minPlayer){
    let nextMove = null;
    
    function runMM(board, player, depth){
      if(GameState.checkForVictory(board) === maxPlayer) { //o
        return 10 - depth;
      } else if (GameState.checkForVictory(board) === minPlayer){ //x
        return depth - 10;
      } else if (GameState.checkForDraw(board)){
        return 0;
      }
      
      let nextPlayer = player === 'x' ? 'o' : 'x';
      let moves = [];
      let scores = [];
      
      for (let i = 0; i < board.length; i++){
        let boardCopy = board.slice();
        if (boardCopy[i] === null){
          boardCopy[i] = nextPlayer;
          moves.push(i);
          scores.push(runMM(boardCopy, nextPlayer, depth + 1))
        }
      }
    
      if (depth === 0){
        nextMove = moves[scores.indexOf(Math.max.apply(null, scores))];
      } else {
        if (nextPlayer === maxPlayer){
          return Math.max.apply(Math, scores);
        } else {
          return Math.min.apply(Math, scores);
        }
      }
    }// run mm
    runMM(GameState.currentState, minPlayer, 0); //current board state, minPlayer = x, it will be switched to O on the first recursive call, depth is 0
    GameState.move(nextMove, ManagePlayers.computerPlayer);
    ControlUi.displayMove(nextMove, ManagePlayers.computerPlayer);
  }//minimax()
}//ai obj

Game.start();

$("#reset").click(function(){
  console.log('turns', Game.turns);
  console.log(GameState.currentState);
  console.log('playerOne', ManagePlayers.playerOne);
  console.log('playerTwo', ManagePlayers.playerTwo);
  console.log('computerPlayer', ManagePlayers.computerPlayer);
  console.log('gp', Game.playing);
});
              
            
!
999px

Console