cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

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.

Quick-add: + add another resource

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.

Quick-add: + add another resource

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.

            
              <div id='gameWrapper'>
   <div id='messg'>
  </div>
  <div id='tokenChoice' class='clearfix'>
    <button id='btnX'>X ?</button>OR<button id='btnO'>O ?</button>
  </div>
  <div id='main'>
    <canvas id='canvasBoard' width='310px' height='310px'></canvas>
  </div>
  <div id='scores'>
    <div id='scoreAI'></div>
    <div id='scorePlayer'></div>
  </div>
  <div id='btmControls'><button id='reset'>Reset</button></div>
</div>
            
          
!
            
              * {
  box-sizing: border-box;
}
canvas {
  position: relative;
}
.clearfix:after {
    content:" ";
    display:block;
    clear:both;
}
button:focus {
  outline: 0;
}
#gameWrapper {
  width: 310px;
  margin: 0 auto;
}
#tokenChoice {
  width: 310px;
position: absolute;
  top: 40%;
  padding: 1em;
  opacity: 0.8;
  background: black;
  box-shadow: 1px 1px 1px black;
  z-index: 1;
}
#btnX, #btnO {
  width: 45%;
  border-radius: 25px;
  background: white;
  font-size: 1.5em;
}
#btnX {
  float: left;
}
#btnO {
  float: right;
}
#messg {
  font-size: 2em;
  width: 310px;
  height: 2em;
  margin: 0 auto;
  text-align: center;
}
#main {
  width: 310px;
  height: 310px;
  margin: 0 auto;
  background: silver;
}
#btmControls, #scores {
  width: 310px;
  margin: 0 auto;
  text-align: center;
}
#scoreAI, #scorePlayer {
  width: 50%;
  float: left;
}
#reset {
  width: 25%;
  margin: 1em auto;
  background: whitesmoke;
}
.hide {
  display: none;
}
            
          
!
            
              var reset = document.querySelector('#reset'),
  btnX = document.querySelector('#btnX'),
  btnO = document.querySelector('#btnO'),
  messg = document.querySelector('#messg'),
  scoreAI = document.querySelector('#scoreAI'),
  scorePlayer = document.querySelector('#scorePlayer'),
  tokenChoice = document.querySelector('#tokenChoice'),
  canvasBoard = document.querySelector('#canvasBoard'),
  c = canvasBoard.getContext('2d');
canvasBoard.addEventListener('click', mouseClick, false);
reset.addEventListener('click', resetGame, false);
btnX.addEventListener('click', chooseToken, false);
btnO.addEventListener('click', chooseToken, false);

var timeout, game = [], state = [],
  tiles = [],
  AI = 'O',
  PLAYER = 'X',
  turn = PLAYER,
  SCOREAI = 0,
  SCOREPLAYER = 0,
  turnsLeft = 9,
  pause = true,
  ROWS = 3,
  COLS = 3,
  boardLength = 9,
  tileWidth = 100,
  tileHeight = 100,
  tilePadding = 20,
  tileOffsetLeft = 5,
  tileOffsetTop = 5,
  midColLX, midColRX, rigColLX;

// X and O size
c.font = (tileWidth / 2) + 'px' + ' serif';

function setup() {
  pause = true;
  drawTiles();

  midColLX = tiles[1].x;
  midColRX = midColLX + tileWidth;
  rigColLX = tiles[2].x;
}

// draw tiles on board
function drawTiles() {
  var i, j, tileX, tileY,
    count = 0;
  c.fillStyle = 'white';
  for (i = 0; i < ROWS; i++) {
    for (j = 0; j < COLS; j++) {
      tileX = j * (tileWidth + tileOffsetLeft);
      tileY = i * (tileHeight + tileOffsetTop);
      tiles[count] = {
        x: tileX,
        y: tileY
      }
      state[count] = 0;
      c.fillRect(tileX, tileY, tileWidth, tileHeight);
      count++;
    } // end inner loop
  } // end outer loop
}
game = {
startGame: function() {
  tokenChoice.classList.add('hide');
  scoreAI.innerHTML = 'Computer Wins ' + SCOREAI;
  scorePlayer.innerHTML = 'Player Wins ' + SCOREPLAYER;
  pause = false;
},
  winner: function() {
  var winner2;
  if (turn === PLAYER) {
    winner2 = 'You';
    SCOREPLAYER++;
    updateScores();
  } else {
    winner2 = 'Computer';
    SCOREAI++;
    updateScores();
  }
  messg.innerHTML = winner2 + ' Won!';
  timeout = window.setTimeout(nextGame, 2000);
},
  noWinner: function() {
  pause = true;
  messg.innerHTML = 'Draw';
  timeout = window.setTimeout(nextGame, 2000);
},
  switchTurn: function() {
  turnsLeft--;
    if (turnsLeft === 0) {
    this.noWinner();
      return;
  }
  turn = (turn === AI) ? PLAYER : AI;
},
} // end game

function chooseToken(e) {
  PLAYER = (e.target.id === 'btnX') ? 'X' : 'O';
  AI = (PLAYER === 'O') ? 'X' : 'O';
  turn = PLAYER;
  game.startGame();
}
function score(game, player) {
  var result = checkForWin(game);
  if (result === 0) {
    return 0;
  } else if (result === AI) {
    return 10;
  } else {
    return -10;
  }
}
// actions after mouse click function
function process() {
  var i, v = 0,
    moves = [],
    scores = [],
    result = 0,
    bestScore = -1000,
    bestMove = 0;
  if (checkForWin(state) !== 0) {
    game.winner();
    return;
  }
  game.switchTurn();
  moves = nextMoves(state, AI);
  for (i = 0; i < moves.length; i++) {
    result = minimax(moves[i], turnsLeft - 1, PLAYER);
    scores[i] = result;
  }
  for (i = 0; i < moves.length; i++) {
    if (scores[i] > bestScore) {
      bestScore = scores[i];
      bestMove = i;
    }
  }
  state = [];
  state = moves[bestMove].slice(0);
  for (i = 0; i < boardLength; i++) {
    if (state[i] !== 0) {
      drawShape(state[i], i);
    }
  }
  if (checkForWin(state) !== 0) {
    game.winner();
    return;
  }
  game.switchTurn();
  pause = false;
  console.log(pause);
} // end process

// minimax algorithm, AI pick best move
function minimax(game, depth, player) {
  var i = 0,
    bestScore = 0,
    v = 0,
    scoreNum = 0,
    moves = [];
  scoreNum = score(game, player);
  if ((depth === 0) || (scoreNum !== 0)) {
    return scoreNum; // return score
  }
  if (player === AI) {
    bestScore = -100;
    moves = nextMoves(game, AI);
    for (i = 0; i < moves.length; i++) {
      v = minimax(moves[i], depth - 1, PLAYER);
      if (v > bestScore) {
        bestScore = v;
      }
    }
    return bestScore;
  } else {
    bestScore = 100;
    moves = nextMoves(game, PLAYER);
    for (i = 0; i < moves.length; i++) {
      v = minimax(moves[i], depth - 1, AI);
      if (v < bestScore) {
        bestScore = v;
      }
    }
    return bestScore;
  }

} // end minimax

// generate next possible moves
function nextMoves(currGame, player) {
  var i, list = [];
  for (i = 0; i < boardLength; i++) {
    if (currGame[i] === 0) {
      list[list.length] = currGame.slice(0);
      list[list.length - 1][i] = player;
    }
  }
  return list;
} // end nextMoves

// check if three are the same
function checkIfSame(c1, c2, c3) {
  if ((c1 == c2) && (c1 == c3)) {
    return true;
  } else {
    return false;
  }
}

// check for winner
function checkForWin(game) {
  var i;
  // check rows
  for (i = 0; i < 7; i += 3) {
    if (game[i] !== 0) {
      if (checkIfSame(game[i], game[i + 1], game[i + 2])) {
        return game[i];
      }
    }
  }
  // check columns
  for (i = 0; i < 3; i++) {
    if (game[i] !== 0) {
      if (checkIfSame(game[i], game[i + 3], game[i + 6])) {
        return game[i];
      }
    }
  }
  // check diagonals
  if (checkIfSame(game[0], game[4], game[8])) {
    return game[4];
  }
  if (checkIfSame(game[2], game[4], game[6])) {
    return game[4];
  }
  return 0;
} // end checkForWin

// Main mouse click function
function mouseClick(e) {
  if (pause === true) {
    return;
  } else { 
    pause = true
  var mouseX = (e.pageX - canvasBoard.offsetLeft);
  var mouseY = (e.pageY - canvasBoard.offsetTop);
  var clickLoc, a, b;
  // y pos
  if (mouseY <= tileWidth) {
    a = 0;
  } else if (mouseY >= midColLX && mouseY < midColRX) {
    a = 3;
  } else if (mouseY >= rigColLX) {
    a = 6;
  } else {
    pause = false;
    return;
  }
  // x pos
  if (mouseX <= tileWidth) {
    clickLoc = a;
  } else if (mouseX >= midColLX && mouseX < midColRX) {
    clickLoc = a + 1;
  } else if (mouseX >= rigColLX) {
    clickLoc = a + 2;
  } else {
    pause = false;
    return;
  }
  // place token if tile is empty, if tile not empty, get out of here
  if (state[clickLoc] === 0) {
    state[clickLoc] = turn;
    drawShape(turn, clickLoc);
    process();
  } else {
    pause = false;
    return;
  }
  } // end main else
} // end mouseClick

function drawShape(shape, tileNum) {
  c.fillStyle = 'red';
  c.fillText(shape, (tiles[tileNum].x + tileWidth / 3), (tiles[tileNum].y + tileWidth / 1.5));
}

function resetGame() {
  pause = true;
  var i;
  clearTimeout(timeout);
  tokenChoice.classList.remove('hide');
  c.clearRect(0, 0, canvasBoard.width, canvasBoard.height);
  c.fillStyle = 'white';
  state = [];
  turnsLeft = 9;
  SCOREAI = 0;
  SCOREPLAYER = 0;
  PLAYER = 'X';
  AI = 'O';
  turn = PLAYER;
  messg.innerHTML = '';
  for (i = 0; i < boardLength; i++) {
    c.fillRect(tiles[i].x, tiles[i].y, tileWidth, tileHeight);
    state[i] = 0;
  }
  updateScores();
}

function nextGame() {
  var i;
  c.clearRect(0, 0, canvasBoard.width, canvasBoard.height);
  c.fillStyle = 'white';
  state = [];
  turnsLeft = 9;
  messg.innerHTML = '';
  turn = PLAYER;
  for (i = 0; i < boardLength; i++) {
    c.fillRect(tiles[i].x, tiles[i].y, tileWidth, tileHeight);
    state[i] = 0;
  }
  pause = false;
}

function updateScores() {
  scoreAI.innerHTML = 'Computer Wins ' + SCOREAI;
  scorePlayer.innerHTML = 'Player Wins ' + SCOREPLAYER;
}

// create the board and start
setup();
            
          
!
999px
Loading ..................

Console