Kółko i krzyżyk krok 9: zwycięska linia na zielono

Kółko i krzyżyk krok po kroku - JavaScript na stronach WWW (HTML/CSS/JS)

`winningLine` zwraca numery pól linii, więc `render` może je wyróżnić: `classList.toggle('win', warunek)` dodaje klasę polom z linii i zdejmuje pozostałym.

<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <title>Kółko i krzyżyk</title>
  <style>
    body { font-family: sans-serif; max-width: 36em; line-height: 1.4; }
    input, select, button, textarea { font: inherit; padding: 0.2em 0.4em; }
    table { border-collapse: collapse; }
    th, td { border: 1px solid #94a3b8; padding: 0.2em 0.6em; }

    #board { display: grid; grid-template-columns: repeat(3, 60px); gap: 4px; margin: 0.5em 0; }
    #board button { width: 60px; height: 60px; font-size: 1.8em; padding: 0; }
    #board .win { background: #bbf7d0; }
  </style>
</head>
<body>
  <p id="info">Ruch: X</p>
  <div id="board"></div>
  <script>
    const board = document.getElementById('board');
    const info = document.getElementById('info');
    const buttons = [];
    for (let i = 0; i < 9; i++) {
      const button = document.createElement('button');
      button.dataset.index = i;
      board.append(button);
      buttons.push(button);
    }
    // osiem linii: trzy wiersze, trzy kolumny, dwie przekątne
    const LINES = [
      [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 winningLine(cells) {
      return LINES.find(([a, b, c]) => cells[a] !== '' && cells[a] === cells[b] && cells[a] === cells[c]) ?? null;
    }
    const cells = Array(9).fill('');
    let player = 'X';
    let over = false;

    function render() {
      const line = winningLine(cells);
      buttons.forEach((button, i) => {
        button.textContent = cells[i];
        button.classList.toggle('win', line !== null && line.includes(i));
      });
    }

    board.addEventListener('click', e => {
      const button = e.target.closest('button');
      if (!button || over) return;
      const index = Number(button.dataset.index);
      if (cells[index] !== '') return;
      cells[index] = player;
      if (winningLine(cells)) {
        over = true;
        info.textContent = `Wygrywa ${player}`;
      } else if (cells.every(c => c !== '')) {
        over = true;
        info.textContent = 'Remis';
      } else {
        player = player === 'X' ? 'O' : 'X';
        info.textContent = `Ruch: ${player}`;
      }
      render();
    });
  </script>
</body>
</html>

Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.

Wszystkie lekcje kursu JavaScript na stronach WWW·Zaloguj się, aby zapisać postęp na koncie.