Back to Game

Tic Tac Toe - Source Code

Play Game
JavaScript
const board = Array(9).fill('');
let currentPlayer = 'X';
let gameActive = true;

const winningConditions = [
  [0, 1, 2], [3, 4, 5], [6, 7, 8],
  [0, 3, 6], [1, 4, 7], [2, 5, 8],
  [0, 4, 8], [2, 4, 6]
];

function minimax(board, depth, isMaximizing) {
  const winner = checkWinner(board);
  
  if (winner === 'O') return 10 - depth;
  if (winner === 'X') return depth - 10;
  if (board.every(cell => cell !== '')) return 0;
  
  if (isMaximizing) {
    let bestScore = -Infinity;
    for (let i = 0; i < 9; i++) {
      if (board[i] === '') {
        board[i] = 'O';
        const score = minimax(board, depth + 1, false);
        board[i] = '';
        bestScore = Math.max(score, bestScore);
      }
    }
    return bestScore;
  } else {
    let bestScore = Infinity;
    for (let i = 0; i < 9; i++) {
      if (board[i] === '') {
        board[i] = 'X';
        const score = minimax(board, depth + 1, true);
        board[i] = '';
        bestScore = Math.min(score, bestScore);
      }
    }
    return bestScore;
  }
}

function getBestMove() {
  let bestScore = -Infinity;
  let bestMove = 0;
  
  for (let i = 0; i < 9; i++) {
    if (board[i] === '') {
      board[i] = 'O';
      const score = minimax(board, 0, false);
      board[i] = '';
      
      if (score > bestScore) {
        bestScore = score;
        bestMove = i;
      }
    }
  }
  
  return bestMove;
}

function checkWinner(gameBoard) {
  for (const condition of winningConditions) {
    const [a, b, c] = condition;
    if (gameBoard[a] && gameBoard[a] === gameBoard[b] && gameBoard[b] === gameBoard[c]) {
      return gameBoard[a];
    }
  }
  return null;
}

function handleCellClick(index) {
  if (board[index] !== '' || !gameActive || currentPlayer === 'O') return;
  
  board[index] = 'X';
  updateDisplay();
  
  const winner = checkWinner(board);
  if (winner || board.every(cell => cell !== '')) {
    gameActive = false;
    return;
  }
  
  currentPlayer = 'O';
  setTimeout(() => {
    const aiMove = getBestMove();
    board[aiMove] = 'O';
    updateDisplay();
    
    const aiWinner = checkWinner(board);
    if (aiWinner || board.every(cell => cell !== '')) {
      gameActive = false;
    } else {
      currentPlayer = 'X';
    }
  }, 500);
}

function updateDisplay() {
  board.forEach((cell, index) => {
    document.getElementById(`cell-${index}`).textContent = cell;
  });
}

function resetGame() {
  board.fill('');
  currentPlayer = 'X';
  gameActive = true;
  updateDisplay();
}

This code demonstrates the core game logic. The actual implementation may include additional features and optimizations.