|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | +<meta charset="UTF-8"> |
| 5 | +<meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| 6 | +<title>Tic Tac Toe</title> |
| 7 | +<style> |
| 8 | + body { |
| 9 | + font-family: Arial, sans-serif; |
| 10 | + display: flex; |
| 11 | + justify-content: center; |
| 12 | + align-items: center; |
| 13 | + height: 100vh; |
| 14 | + margin: 0; |
| 15 | + } |
| 16 | + #board { |
| 17 | + display: grid; |
| 18 | + grid-template-columns: repeat(3, 100px); |
| 19 | + grid-gap: 5px; |
| 20 | + background-color: black; |
| 21 | + } |
| 22 | + |
| 23 | + .cell { |
| 24 | + width: 100px; |
| 25 | + height: 100px; |
| 26 | + background-color: grey; |
| 27 | + color: aliceblue; |
| 28 | + display: flex; |
| 29 | + justify-content: center; |
| 30 | + align-items: center; |
| 31 | + font-size: 2em; |
| 32 | + cursor: pointer; |
| 33 | + } |
| 34 | +</style> |
| 35 | + |
| 36 | +</head> |
| 37 | +<body> |
| 38 | + |
| 39 | + |
| 40 | +<div id="board"> |
| 41 | +</div> |
| 42 | + |
| 43 | +<script> |
| 44 | + |
| 45 | + const board = document.getElementById('board'); |
| 46 | + let currentPlayer = 'X'; |
| 47 | + let cells = ['', '', '', '', '', '', '', '', '']; |
| 48 | + |
| 49 | + function checkWinner() { |
| 50 | + const winCombinations = [ |
| 51 | + [0, 1, 2], |
| 52 | + [3, 4, 5], |
| 53 | + [6, 7, 8], |
| 54 | + [0, 3, 6], |
| 55 | + [1, 4, 7], |
| 56 | + [2, 5, 8], |
| 57 | + [0, 4, 8], |
| 58 | + [2, 4, 6] |
| 59 | + ]; |
| 60 | + |
| 61 | + for (let combination of winCombinations) { |
| 62 | + const [a, b, c] = combination; |
| 63 | + if (cells[a] && cells[a] === cells[b] && cells[a] === cells[c]) { |
| 64 | + return cells[a]; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return null; |
| 69 | + } |
| 70 | + |
| 71 | + function checkDraw() { |
| 72 | + return cells.every(cell => cell !== ''); |
| 73 | + } |
| 74 | + |
| 75 | + function handleClick(index) { |
| 76 | + if (cells[index] === '' && !checkWinner()) { |
| 77 | + cells[index] = currentPlayer; |
| 78 | + render(); |
| 79 | + const winner = checkWinner(); |
| 80 | + if (winner) { |
| 81 | + alert(`Player ${winner} wins!`); |
| 82 | + } else if (checkDraw()) { |
| 83 | + alert('It\'s a draw!'); |
| 84 | + } else { |
| 85 | + currentPlayer = currentPlayer === 'X' ? 'O' : 'X'; |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + function render() { |
| 91 | + board.innerHTML = ''; |
| 92 | + cells.forEach((value, index) => { |
| 93 | + const cell = document.createElement('div'); |
| 94 | + cell.classList.add('cell'); |
| 95 | + cell.textContent = value; |
| 96 | + cell.addEventListener('click', () => handleClick(index)); |
| 97 | + board.appendChild(cell); |
| 98 | + }); |
| 99 | + } |
| 100 | + |
| 101 | + render(); |
| 102 | +</script> |
| 103 | +</body> |
| 104 | +</html> |
0 commit comments