Untitled
unknown
plain_text
9 months ago
3.6 kB
2
Indexable
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Tic-Tac-Toe</title> <style> body { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; margin: 0; font-family: Arial, sans-serif; } .board { display: grid; grid-template-columns: repeat(3, 100px); grid-template-rows: repeat(3, 100px); gap: 5px; } .cell { width: 100px; height: 100px; background-color: #fff; display: flex; justify-content: center; align-items: center; font-size: 2em; cursor: pointer; border: 2px solid #000; } .cell:hover { background-color: #f9f9f9; } .message { margin-top: 20px; font-size: 1.5em; } .cell.win { background-color: #c8e6c9; } </style> </head> <body> <div> <div class="board" id="board"></div> <div class="message" id="message"></div> </div> <script> const boardElement = document.getElementById('board'); const messageElement = document.getElementById('message'); let board = ['', '', '', '', '', '', '', '', '']; let currentPlayer = 'X'; let isGameOver = false; function renderBoard() { boardElement.innerHTML = ''; board.forEach((cell, index) => { const cellElement = document.createElement('div'); cellElement.classList.add('cell'); cellElement.textContent = cell; if (winningPattern && winningPattern.includes(index)) { cellElement.classList.add('win'); } cellElement.addEventListener('click', () => handleCellClick(index)); boardElement.appendChild(cellElement); }); } function handleCellClick(index) { if (board[index] !== '' || isGameOver) return; board[index] = currentPlayer; winningPattern = checkWin(); if (checkWin()) { messageElement.textContent = `${currentPlayer} wins!`; isGameOver = true; renderBoard(); return; } if (board.every(cell => cell !== '')) { messageElement.textContent = `It's a tie!`; isGameOver = true; return; } currentPlayer = currentPlayer === 'X' ? 'O' : 'X'; renderBoard(); } function checkWin() { const winPatterns = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; for (const pattern of winPatterns) { if (pattern.every(index => board[index] === currentPlayer)) { return pattern; } } return null; } let winningPattern = null; renderBoard(); </script> </body> </html>
Editor is loading...
Leave a Comment