Крестики-нолики на JavaScript
В этой статье мы создадим простую веб-игру крестики-нолики с использованием HTML, CSS и JavaScript.
HTML
<html lang=«ru»>
<head>
<meta charset=«UTF-8»>
<meta name=«viewport» content=«width=device-width, initial-scale=1.0»>
<title>Крестики-нолики</title>
<link rel=«stylesheet» href=«style.css»>
</head>
<body> <div class=«container»>
<h1>Крестики-нолики</h1>
<div id=«board» class=«board»>
<!— Сюда будут добавлены ячейки игрового поля —>
</div>
<button onclick=«startGame()»>Начать заново</button>
</div>
<script src=«script.js»></script>
</body>
</html>
CSS для стилизации
.container { text-align: center; margin-top: 50px; }
.board { display: inline-block; border: 2px solid #333; }
.cell { width: 100px; height: 100px; border: 1px solid #ccc; display: inline-block; font-size: 60px; cursor: pointer; }
JavaScript для логики игры
let currentPlayer = ‘X’;
let gameStatus = [‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘];function startGame() {
gameStatus = [‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘];
document.querySelectorAll(‘.cell’).forEach(cell => cell.textContent = »);
currentPlayer = ‘X’;
}function handleCellClick(index) {
if (gameStatus[index] === ‘-‘ && !checkWinner()) {
gameStatus[index] = currentPlayer;
document.getElementById(`cell-${index}`).textContent = currentPlayer;
currentPlayer = currentPlayer === ‘X’ ? ‘O’ : ‘X’;
checkWinner();
}
}function checkWinner() {
const winningConditions = [
[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 (let condition of winningConditions) {
const [a, b, c] = condition;
if (gameStatus[a] !== ‘-‘ && gameStatus[a] === gameStatus[b] && gameStatus[a] === gameStatus[c]) {
alert(`${gameStatus[a]} победил!`);
return true;
}
}if (!gameStatus.includes(‘-‘)) {
alert(‘Ничья!’);
return true;
}return false;
}document.addEventListener(‘DOMContentLoaded’, () => {
const board = document.getElementById(‘board’);for (let i = 0; i < 9; i++) { const cell = document.createElement(‘div’); cell.className = ‘cell’; cell.id = `cell-${i}`; cell.addEventListener(‘click’, () => handleCellClick(i));
board.appendChild(cell);
}
});
Теперь, когда вы загрузите страницу, у вас будет простая игра крестики-нолики, которую можно играть в браузере! Нажмите на ячейку, чтобы поставить крестик или нолик и наслаждайтесь игрой!