All files / tictactoe/public game.js

100% Statements 45/45
100% Branches 19/19
100% Functions 7/7
100% Lines 42/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 7019x 19x             19x 19x 19x 19x 19x 19x 19x     24x 24x 24x 24x 216x 216x   24x       81x 587x 10x     71x       85x 85x   81x 81x 81x 81x   81x 81x 12x 12x 2x 2x 2x   10x 10x 30x 10x     69x 69x       171x 19x   19x    
(function () {
  const WINS = [
    [0,1,2],[3,4,5],[6,7,8],
    [0,3,6],[1,4,7],[2,5,8],
    [0,4,8],[2,4,6]
  ];
 
  let board, current, over;
  const score = { X: 0, O: 0, draw: 0 };
  const cells = document.querySelectorAll('.cell');
  const status = document.getElementById('status');
  const resetBtn = document.getElementById('reset');
  const scoreX = document.getElementById('score-x');
  const scoreO = document.getElementById('score-o');
  const scoreDraw = document.getElementById('score-draw');
 
  function init() {
    board = Array(9).fill(null);
    current = 'X';
    over = false;
    cells.forEach(c => {
      c.textContent = '';
      c.className = 'cell';
    });
    status.textContent = "Player X's turn";
  }
 
  function checkWinner() {
    for (const [a, b, c] of WINS) {
      if (board[a] && board[a] === board[b] && board[a] === board[c]) {
        return { winner: board[a], line: [a, b, c] };
      }
    }
    return board.every(Boolean) ? { winner: null, draw: true } : null;
  }
 
  function handleClick(e) {
    const idx = parseInt(e.target.dataset.index);
    if (over || board[idx]) return;
 
    board[idx] = current;
    const cell = cells[idx];
    cell.textContent = current;
    cell.classList.add('taken', current.toLowerCase());
 
    const result = checkWinner();
    if (result) {
      over = true;
      if (result.draw) {
        score.draw++;
        scoreDraw.textContent = score.draw;
        status.textContent = "It's a draw!";
      } else {
        score[result.winner]++;
        (result.winner === 'X' ? scoreX : scoreO).textContent = score[result.winner];
        result.line.forEach(i => cells[i].classList.add('winner'));
        status.textContent = `Player ${result.winner} wins!`;
      }
    } else {
      current = current === 'X' ? 'O' : 'X';
      status.textContent = `Player ${current}'s turn`;
    }
  }
 
  cells.forEach(c => c.addEventListener('click', handleClick));
  resetBtn.addEventListener('click', init);
 
  init();
})();