const board = Array(9).fill(0); const winPatterns = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], // poziome [0, 3, 6], [1, 4, 7], [2, 5, 8], // pionowe [0, 4, 8], [2, 4, 6] // przekątne ]; function checkWin(board) { for (let pattern of winPatterns) { const [a, b, c] = pattern; if (board[a] !== 0 && board[a] === board[b] && board[a] === board[c]) { return board[a]; } } return 0; } function initializeBoard() { const boardElement = document.querySelector('.board'); boardElement.innerHTML = ''; for(let i = 0; i < 9; i++) { const div = document.createElement('div'); div.className = 'cell'; div.id = 'cell-' + i; div.addEventListener('click', () => handleMove(i)); boardElement.appendChild(div); } updateBoardDisplay(); } function updateBoardDisplay() { board.forEach((value, index) => { const cell = document.getElementById('cell-' + index); cell.className = 'cell'; if (value === 1) { cell.classList.add('o'); } else if (value === -1) { cell.classList.add('x'); } }); const winner = checkWin(board); const messageElement = document.querySelector('.message'); if (winner === 1) { messageElement.textContent = 'Komputer wygrał!'; } else if (winner === -1) { messageElement.textContent = 'Wygrałeś!'; } else if (!board.includes(0)) { messageElement.textContent = 'Remis!'; } else { messageElement.textContent = ''; } } async function handleMove(index) { if (board[index] !== 0 || checkWin(board)) return; // Ruch gracza board[index] = -1; updateBoardDisplay(); if (checkWin(board)) return; try { // Wysłanie stanu planszy do API const response = await fetch('/move', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ board: board }) }); const data = await response.json(); if (data.status === 'success' && data.move >= 0 && data.move < 9) { // Ruch komputera board[data.move] = 1; updateBoardDisplay(); } } catch (error) { console.error('Błąd podczas komunikacji z API:', error); } } // Inicjalizacja gry i pobranie aktualnego stanu async function initGame() { try { const response = await fetch('/status'); const data = await response.json(); // Tutaj możesz zaktualizować planszę zgodnie z danymi z serwera console.log(data); } catch (error) { console.error('Błąd podczas pobierania stanu gry:', error); } initializeBoard(); } initGame();