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.

            
              <html>
<head>
  <title>
    Tic Tac Toe
  </title>
</head>
<body>
  <div id="frame">     
  </div>
</body>
</html>

<!--
startMenu
      <div id="menuOne">
        <h1>Tic Tac Toe</h1>
        <div id = "playChoose">
          <div id="playerOne" class = "players"><p>One Player</p></div>
          <div id="playerTwo" class = "players"><p>Two PLayers</p></div>
        </div>
      </div>

OX Choose
    <div id="menuTwo">
      <h2>Choose Icon</h2>
      <div id ="oxChoose">
        <div id="O" class = "OX"><p>One Player</p></div>
        <div id="X" class = "OX"><p>Two PLayers</p></div>
      </div>  
    </div>

gameLoad
      <div class="entrySec" id = "tL">
      </div>
      <div class="entrySec" id ="tM">
      </div>
      <div class="entrySec" id ="tR">
      </div>  
      <div class="entrySec" id ="mL">
      </div>
     <div class="entrySec" id = "mM">  
      </div>
      <div class="entrySec" id = "mR">
      </div>
      <div class="entrySec" id = "bL">
      </div>  
      <div class="entrySec" id = "bM">
      </div>
      <div class="entrySec" id = "bR">
      </div>

   X
<svg version="1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 249.3 248"><path class ="X" fill="none" stroke="#F8FF37" stroke-width="24" stroke-miterlimit="10" d="M60.2 54.5l130 130M190.2 54.5l-130 130"/></svg>
  O
<svg version="1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 249.3 248"><circle class ="O" fill="none" stroke="#F8FF37" stroke-width="24" stroke-miterlimit="10" cx="124.3" cy="119.4" r="70.8"/></svg>  

    -->
            
          
!
            
              @import url(https://fonts.googleapis.com/css?family=Geo);

body{
  background: #11161b;
  font-family:'Geo', sans-serif;
}

#frame{
  position:relative;
  height:28em;
  width:28em;
  background:#25323e;
  margin:80px auto 0 auto;
}

#board{
  height:22.5em;
  width:22.5em;
}

h1{
  color:#f8ff37;
  font-size:5em;
  padding-top:.9em;
  text-align:center;
}

h2{
  color:#f8ff37;
  font-size:5em;
  padding-top:.9em;
  text-align:center; 
}

.players,.XO,#back{
  color:white;
}

#reset, .Points{
  color:#f8ff37;
}

.players{
  font-size:2em;
}

.XO{
  font-size:3em;
}

#back{
  margin-top:3.5em;
  text-align:center;
  font-size:1.5em;
}

.players:hover,.XO:hover,#back:hover,#reset:hover{
  color: #6c5dff;
}

#playChoose,#xoChoose{   
  padding-top: 1em;
  display:flex;
  justify-content:center;
  align-items:center;
}

.players{
  padding:0 .5em 0 .5em;
}

.XO{
  padding:0 1em 0 1em;
}

.entrySec{
  float:left;
  display:flex;
  justify-content:center;
  align-items:center;
  background:#36526a;
  height: 7.5em;
  width: 7.5em;
}
#tL{
  border-bottom:.1em solid #25323e;
  border-right:.1em solid #25323e;
}

#tM{
  border-left:.1em solid #25323e;
  border-bottom:.1em solid #25323e;
  border-right:.1em solid #25323e;
}

#tR{
  border-left:.1em solid #25323e;
  border-bottom:.1em solid #25323e;
}

#mL{
  border-top:.1em solid #25323e;
  border-bottom:.1em solid #25323e;
  border-right:.1em solid #25323e;
}

#mM{
  border-top:.1em solid #25323e;
  border-left:.1em solid #25323e;
  border-bottom:.1em solid #25323e;
  border-right:.1em solid #25323e;
}

#mR{
  border-top:.1em solid #25323e;
  border-left:.1em solid #25323e;
  border-bottom:.1em solid #25323e;
}

#bL{
  border-top:.1em solid #25323e;
  border-right:.1em solid #25323e;
}

#bM{
  border-top:.1em solid #25323e;
  border-left:.1em solid #25323e;
  border-right:.1em solid #25323e;
}

#bR{
  border-top:.1em solid #25323e;
  border-left:.1em solid #25323e;
}

svg{
  transform: rotate(180deg);
  width:8em;
}

.X{
 /* stroke-width: 3; */
  stroke-dashoffset:0;
  stroke-dasharray:2000;
  animation-name: X; 
  animation-duration: .4s; 
  animation-iteration-count: 1;
  animation-direction: alternate;
  animation-timing-function: linear;
}

.O{ 
 /* stroke-width: 3; */
  stroke-dashoffset:0;
  stroke-dasharray:2000;
  animation-name: O; 
  animation-duration: .5s; 
  animation-iteration-count: 1;
  animation-direction: alternate;
  animation-timing-function: linear;
}

@keyframes X{
  0%
  {
    stroke-dashoffset:-200;
  }
  100%
  {
    stroke-dashoffset:0;
  }  
}

@keyframes O{
  0%
  {
    stroke-dashoffset:-400;
  }
  100%
  {
    stroke-dashoffset:0;
  }  
}

#pointsBoard{
  position:absolute;
  left: 0; 
  right: 0; 
  margin-left: auto; 
  margin-right: auto; 
  top: -.1em;
  width:7em;
  z-index:1;
  display:flex;
  justify-content:space-around;
  align-items:center;
 /* background: blue;  #25323e  */
  font-size:2em;
}

#resetDiv{
  position:absolute;
  left: 0; 
  right: 0; 
  margin-left: auto; 
  margin-right: auto; 
  bottom: -.65em;
  z-index:1;
}

#reset{
  text-align:center;
  font-size:2em;
}

.Points{
 padding-left:2em;
 padding-right:2em; 
}

#invBut{
  display:flex;
  justify-content:center;
  align-items:center;
  position:absolute; 
  height:28em;
  width:28em;
  z-index:2;
}

#winDisplay{
 /* display:flex;
  justify-content:center;
  align-items:center; */
  position:absolute; 
  left: 0; 
  right: 0; 
  margin-left: auto; 
  margin-right: auto; 
  z-index:1;
  background:#0e1215;  
  text-align:center;
  font-size:2.5em;
  color:white;
  padding-top:.5em;
  height:2.5em;
  width:4.5em;
}
            
          
!
            
              //player select
var playOneSel = false;
var playTwoSel = false;
//Player icons
var oneIco = null;
var aiIco = null;
//Icon selected
var xSel = false;
var oSel = false;
//For alternating between ai and player
var aiTurn = false;
//Winning icon
var win = "";
//Points
var onePoints = 0;
var twoPoints = 0;
var roundScore = false;
//Array of board placement names
var entryName = ["tL","tM","tR","mL","mM","mR","bL","bM","bR"];
//Array for if board placement is filled or not
var boardSwch = {"tL":false,"tM":false,"tR":false,"mL":false,"mM":false,"mR":false,"bL":false, "bM":false, "bR":false};
//2D array for entered board icons to be checked later for wins or draws
var board = [
  [null,null,null],
  [null,null,null],
  [null,null,null]
];
//Array of board indexes and entered icons to be entered into MiniMax algorythm function
var boardMM = [0,1,2,3,4,5,6,7,8];  

window.onload = function(){
  startMenu();
}

//Startmenu
function startMenu(){
  document.getElementById("frame").innerHTML = '<div id="menuOne"><h1>Tic Tac Toe</h1><div id = "playChoose"><div id="playerOne" class = "players"><p>One Player</p></div><div id="playerTwo" class = "players"><p>Two Players</p></div></div></div>';
//Player select buttons
  document.getElementById("playerOne").addEventListener("click", function(){{onePlay()};});    
  document.getElementById("playerTwo").addEventListener("click", function(){{twoPlay()};});
}

//Selected player functions
function onePlay(){
  playOneSel = true;
  playTwoSel = false;
  xoMenu();
};
function twoPlay(){
  playOneSel = false;
  playTwoSel = true;
  xoMenu();
};

//Menu to choose between O and X
function xoMenu(){
  document.getElementById("frame").innerHTML = '<div id="menuTwo"><h2>Choose Icon</h2><div id ="xoChoose"><div id="X" class = "XO"><p>X</p></div><div id="O" class = "XO"><p>O</p></div></div><div id="back"><p>Back</p></div></div>';
  document.getElementById("X").addEventListener("click", function(){{xChoose()};});
  document.getElementById("O").addEventListener("click", function(){{oChoose()};});
  document.getElementById("back").addEventListener("click", function(){{reset()};});
}

//Selected icon functions which load a one or two player game
function xChoose(){
  if (playOneSel == true){
    oneIco = "X"
    aiIco = "O"
    xSel = true;
    oSel = false;
    gameLoad();
  } 
  if (playTwoSel == true){
    oneIco = "X";
    xSel = true;
    oSel = false;
    gameLoad();
  }  
};
function oChoose(){
  if (playOneSel == true){
    oneIco = "O";
    aiIco = "X";
    xSel = false;
    oSel = true;
    gameLoad();
  }  
  if (playTwoSel == true){
    oneIco = "O";
    xSel = false;
    oSel = true;
    gameLoad();
  }  
};

//Resets the game
function reset(){
  //Resets frame styles
  $("#frame").css({"display":"", "justify-content":"","align-items":""});
  //Resets all variables
  roundScore = false;
  playOneSel = false;
  playTwoSel = false;
  oneIco = null;
  aiIco = null;
  xSel = false;
  oSel = false;
  aiTurn = false;
  win = "";
  onePoints = 0;
  twoPoints = 0;  
  //Resets boardSwch array
  for(var i = 0; i < entryName.length;i++){
      boardSwch[entryName[i]] = false;
  }
  //Resets board array
  for (var i = 0; i < 3; i++){
    for (var x = 0; x < 3; x++){
        board[i][x] = null;   
    }  
  }
  //Resets MiniMax board
  boardMM = [0,1,2,3,4,5,6,7,8];    
  
  startMenu();
}

//Loads the game
function gameLoad(){
  //Edits game board style
  $("#frame").css({"display":"flex", "justify-content":"space-around","align-items":"center"});
  //Inserts game board blocks, player points and reset button into frame HTML  
  document.getElementById("frame").innerHTML = '<div id ="pointsBoard"><p id = "1pPoints" class="Points">1p:<span id="onePoints">0</span></p><p id ="2pPoints" class="Points">2p:<span id="twoPoints">0</span></p></div><div id="board"><div class="entrySec" id = "tL"></div><div class="entrySec" id ="tM"></div><div class="entrySec" id ="tR"></div><div class="entrySec" id ="mL"></div><div class="entrySec" id = "mM"></div><div class="entrySec" id = "mR"></div><div class="entrySec" id = "bL"></div><div class="entrySec" id = "bM"></div><div class="entrySec" id = "bR"></div></div><div id ="resetDiv"><p id = reset>Reset</p></div>';
 //Adds event listeners to the board blocks for triggering events when they are clicked on     
 document.getElementById("tL").addEventListener("click", function(){{oxFunc("tL",0,0,0)};  });
 document.getElementById("tM").addEventListener("click", function(){{oxFunc("tM",0,1,1)};  });
 document.getElementById("tR").addEventListener("click", function(){{oxFunc("tR",0,2,2)};  });
 document.getElementById("mL").addEventListener("click", function(){{oxFunc("mL",1,0,3)};  });
 document.getElementById("mM").addEventListener("click", function(){{oxFunc("mM",1,1,4)};  });
 document.getElementById("mR").addEventListener("click", function(){{oxFunc("mR",1,2,5)};  });
 document.getElementById("bL").addEventListener("click", function(){{oxFunc("bL",2,0,6)};  });
 document.getElementById("bM").addEventListener("click", function(){{oxFunc("bM",2,1,7)};  });
 document.getElementById("bR").addEventListener("click", function(){{oxFunc("bR",2,2,8)};  });  
 //Adds an event listener to the reset button for returning to the start menu
 document.getElementById("reset").addEventListener("click", function(){{reset()};});    
}

//O or X gets placed when a part of the board is clicked
function oxFunc(blockHTML, row, col,num){
 //Player one or two plays as "X" 
 if (xSel==true && boardSwch[blockHTML] == false && aiTurn == false){
   boardSwch[blockHTML] = true;
   board[row][col] = "X";
   boardMM[num]= "X";
   xSel = false;
   oSel = true;
   xFunc(blockHTML);
   //Allows ai turn if it is playing
   if (playOneSel == true){
    aiTurn = true; 
   }    
 } 
 //AI plays as "O"
 if (aiIco == "O" && aiTurn == true){
   var bestShot = myMiniMax(boardMM,aiIco);
   var rowCol = convRowCol(bestShot.index)
   boardSwch[entryName[bestShot.index]] = true;
   board[rowCol.row][rowCol.col] = "O";
   boardMM[bestShot.index]= "O";
   xSel = true;
   oSel = false;
   oFunc(entryName[bestShot.index]);
   aiTurn = false;
 }
  
 if(oSel==true && boardSwch[blockHTML] == false && aiTurn == false){
   //Player one or two plays as "O"
   boardSwch[blockHTML] = true;
   board[row][col] = "O";
   boardMM[num] = "O";
   xSel = true;
   oSel = false;
   oFunc(blockHTML);
   //Allows ai turn if it is playing
   if (playOneSel == true){
    aiTurn = true; 
   }
  } 
 //AI plays as "X"
 if (aiIco == "X" && aiTurn == true){ 
   var bestShot = myMiniMax(boardMM,aiIco);
   var rowCol = convRowCol(bestShot.index);
   boardSwch[entryName[bestShot.index]] = true;
   board[rowCol.row][rowCol.col] = "X";
   boardMM[bestShot.index]= "X";
   xSel = false;
   oSel = true;
   xFunc(entryName[bestShot.index]);
   aiTurn = false;
  }  
}

//Places "X" svg on board
function xFunc(blockHTML){
  document.getElementById(blockHTML).innerHTML = '<svg id="svg" version="1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 249.3 248"><path class ="X" fill="none" stroke="#F8FF37" stroke-width="24" stroke-miterlimit="10" d="M60.2 54.5l130 130M190.2 54.5l-130 130"/></svg>';  
  icoWinCheck();  
}
//Places "O" svg on board
function oFunc(blockHTML){
  document.getElementById(blockHTML).innerHTML ='<svg id="svg" version="1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 249.3 248"><circle class ="O" fill="none" stroke="#F8FF37" stroke-width="24" stroke-miterlimit="10" cx="124.3" cy="119.4" r="70.8"/></svg> ';
  icoWinCheck(); 
}

//Checks if an winning line has been made by an icon
function scoreCheck(boarded,ico){ 
      if(boarded[0][0] == ico){
        if(boarded[1][1] == ico){
          if(boarded[2][2] == ico){
            return true;
          }
        }
      }     
      if(boarded[0][2] == ico){
        if(boarded[1][1] == ico){
          if(boarded[2][0] == ico){         
            return true;
          }        
        }   
      } 
      for (var i = 0; i < 3; i++){
        if (boarded[i][0] == ico){
          if (boarded[i][1] == ico){
            if(boarded[i][2] == ico){
              return true;
            }
          }
        }      
      }
      for (var i = 0; i < 3; i++){
        if (boarded[0][i] == ico){
          if (boarded[1][i] == ico){
            if(boarded[2][i] == ico){            
              return true;
            }
          }
        }     
      }
   return false;
}

//Checks which icon has won and then activates the winner function with that icon 
function icoWinCheck(){ 
   if (scoreCheck(board,"X") == true){
    winner("X");
    roundScore = true; 
  }else if (scoreCheck(board,"O") == true){
    winner("O");
    roundScore = true;
  }  
  //Checks if there was a draw and then activates the winner function with 'Draw'
  var entryCheck = [];  
  for(var i = 0; i < entryName.length;i++){
     if (boardSwch[entryName[i]] == true){
       entryCheck.push(true);
     }    
  }    
  if(entryCheck.length == entryName.length && roundScore == false){
     winner("Draw");
  }  
}

//Determines which player had the winning icon
function winner(winIco){
  if (oneIco == "X" && winIco == "X"){
    winDisplay("1P");
    win = "1P";
    xSel = true;
    oSel = false;
  }else if (oneIco == "O" && winIco == "O"){
    winDisplay("1P");
    win = "1P";
    xSel = false;
    oSel = true;
  }else if (oneIco == "O" && winIco == "X"){
    winDisplay("2P");
    win = "2P";
    xSel = false;
    oSel = true;
  }else if (oneIco == "X" && winIco == "O"){
    winDisplay("2P");
    win = "2P";
    xSel = true;
    oSel = false;
  }else if (oneIco == "X" && winIco == "Draw"){
    winDisplay("Draw");
    xSel = true;
    oSel = false;
  }else if (oneIco == "O" && winIco == "Draw"){
    winDisplay("Draw");
    xSel = false;
    oSel = true;
 } 

//Displays the winner  
 function winDisplay(playWin){    
    if (playWin == "Draw"){
      $( "#frame" ).append("<div id='invBut'><div id = 'winDisplay'><p>" + playWin + "!</p></div></div>");
      $("#winDisplay").hide().fadeIn('slow');    
    }else{
      $( "#frame" ).append("<div id='invBut'><div id = 'winDisplay'><p>" + playWin + " WINS!</p></div></div>");
      $("#winDisplay").hide().fadeIn('slow');
    }
 }
 //Removes the winner display if the board is clicked on
 document.getElementById("invBut").addEventListener("click", function(){{addPoint()};});  
}

//Point is added to winner's score
function addPoint(){
  boardClear();
  $("#invBut").remove();
  if(win == "1P"){
    onePoints += 1;
    {document.getElementById("onePoints").innerHTML = onePoints;}
    win = "";
  }else if (win == "2P"){
    twoPoints += 1;
    {document.getElementById("twoPoints").innerHTML = twoPoints;}
    win = "";
  }  
}

//Clears board for the next round
function boardClear(){
  roundScore = false;
  aiTurn = false;
  //Resets boardSwch array
  for(var i = 0; i < entryName.length;i++){
      boardSwch[entryName[i]] = false;
  }
  //Resets board array
  for (var i = 0; i < 3; i++){
    for (var x = 0; x < 3; x++){
        board[i][x] = null;   
    }
  //Resets MiniMax array
  boardMM = [0,1,2,3,4,5,6,7,8];  
    
  }  
  //Removes icon svg graphics from board
  for(var i = 0; i < entryName.length;i++){
        $('#svg').remove();  
  }   
}

function myMiniMax(boardNew,ico){
  //indexes of empty spaces
  var spaces = nullGet(boardNew); 
  //Checks for the terminal state. Returns score if there is a win,lose or draw
  if (scoreCheck(convBBoard(boardNew),oneIco) == true){
    return {score:-10};
  }else if(scoreCheck(convBBoard(boardNew),aiIco) == true){
    return {score:10};
  }else if(spaces.length === 0){
    return {score:0};
  }    
  //For collecting scores from each empty spot to evaluate later
  var moves = [];  
  //Loops through available spots
  for (var i = 0; i < spaces.length; i++){
    //Creates on object for each empty spot and stores its index
    var move = {};
        move.index = boardNew[spaces[i]];   
    //Sets the empty spot to the current player
    boardNew[spaces[i]] = ico;  
    //Collects the score resulted from calling minimax on the opponent of the current player
    if(ico == aiIco){
      var result = myMiniMax(boardNew, oneIco);
      move.score = result.score;
    }else{
      var result = myMiniMax(boardNew, aiIco);
      move.score = result.score;
    } 
    //Resets the spot to empty
    boardNew[spaces[i]] = move.index;
      
    //Pushes the object to the array
    moves.push(move);  
  }
  
  //If its the ai's turn, loops over the moves and chooses the move with the highest score
  var bestMove;
  if(ico == aiIco){
    var bestScore = -10000;
    for(var i = 0; i < moves.length; i++){
      if(moves[i].score > bestScore){
        bestScore = moves[i].score;
        bestMove = i;
      }
    }
  }else{
  //Otherwise loops over the moves and chooses the move with the lowest score 
    var bestScore = 10000;
    for(var i = 0; i < moves.length;i++){
      if(moves[i].score < bestScore){
        bestScore = moves[i].score;
        bestMove = i;
      }
    }  
  }
  //Returns the chosen move from the moves array
  return moves[bestMove];
}

//Returns the elements of the MiniMax board array which have not been overwritten with an icon and still contain numbers of their indexes
function nullGet(boardCurr){
  return boardCurr.filter(s => typeof s == 'number');
}

//Converts a 2D array into a 1D array
function flatBoard(toFlat){
   var flatCopy = toFlat.slice(0);  
   var flattenBoard = [].concat.apply([], flatCopy);
   return flattenBoard;
//   console.log(flattenBoard);
 }  

//Converts a 1D array back to a 2D array
function convBBoard(flat){
  var toConv = flat.slice(0);
  var boarded = [];
  for(var i = 0; i < 3; i++){
    boarded[i] = toConv.splice(0,3);
  } 
  return boarded;
}

//Converts a board Minimax index number to rows and column numbers adn returns them in an object 
function convRowCol(num){
  if (num < 3){
    return {row: 0, col: num};
  }else if(num >= 3 && num < 6){
    return {row: 1, col: num - 3};
  }else if(num >= 6){
    return {row: 2, col: num - 6};
  }
}
            
          
!
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.

Console