В этом примере мы создаем таблицу 3×3, где каждая ячейка имеет уникальный идентификатор. Мы также создаем переменные для текущего игрока, количества ходов и таблицы игры. Затем мы добавляем обработчик событий на таблицу, который будет вызываться при клике на ячейку. Если ячейка пустая, мы записываем в нее символ текущего игрока, увеличиваем количество ходов и проверяем, не выиграл ли игрок. Если игрок выиграл, мы выводим сообщение о победе и удаляем обработчик событий, чтобы игрок не мог продолжать игру. Если количество ходов достигло 9 и никто не выиграл, мы выводим сообщение о ничьей. Если игра продолжается, мы меняем игрока и ждем следующего хода. Функция checkWin() проверяет все возможные комбинации выигрыша и возвращает true, если одна из них выполнена.
index,html
<!DOCTYPE html>
<html>
<head>
<title>Крестики-нолики</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
}
table {
margin: 0 auto;
border-collapse: collapse;
}
td {
width: 50px;
height: 50px;
border: 1px solid black;
text-align: center;
font-size: 30px;
cursor: pointer;
}
td:hover {
background-color: #eee;
}
#result {
margin-top: 20px;
font-size: 24px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Крестики-нолики</h1>
<table id="game">
<tr>
<td id="0"></td>
<td id="1"></td>
<td id="2"></td>
</tr>
<tr>
<td id="3"></td>
<td id="4"></td>
<td id="5"></td>
</tr>
<tr>
<td id="6"></td>
<td id="7"></td>
<td id="8"></td>
</tr>
</table>
<div id="result"></div>
<script>
var player = "X";
var moves = 0;
var gameTable = document.getElementById("game");
var result = document.getElementById("result");
gameTable.addEventListener("click", function(event) {
var cell = event.target;
if (cell.innerHTML === "") {
cell.innerHTML = player;
moves++;
if (checkWin()) {
result.innerHTML = "Игрок " + player + " победил!";
gameTable.removeEventListener("click", arguments.callee);
} else if (moves === 9) {
result.innerHTML = "Ничья!";
} else {
player = player === "X" ? "O" : "X";
}
}
});
function checkWin() {
var cells = gameTable.getElementsByTagName("td");
var winCombinations = [
[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 (var i = 0; i < winCombinations.length; i++) {
var a = cells[winCombinations[i][0]].innerHTML;
var b = cells[winCombinations[i][1]].innerHTML;
var c = cells[winCombinations[i][2]].innerHTML;
if (a === b && b === c && a !== "") {
return true;
}
}
return false;
}
</script>
</body>
</html>
6 Comments
Your blog is a breath of fresh air in the crowded online space. I appreciate the unique perspective you bring to every topic you cover. Keep up the fantastic work!
Be happy to e-book the resort as a substitute of testing the availability of cramped hotel rooms nearby.
After looking over a number of the articles on your site, I truly appreciate your technique of writing a blog. I book marked it to my bookmark website list and will be checking back in the near future. Please visit my website too and tell me how you feel.
Hi there, I believe your web site might be having web browser compatibility issues. Whenever I look at your web site in Safari, it looks fine however when opening in IE, it’s got some overlapping issues. I merely wanted to give you a quick heads up! Other than that, wonderful site!
After I originally commented I seem to have clicked on the -Notify me when new comments are added- checkbox and now whenever a comment is added I get 4 emails with the same comment. There has to be a means you are able to remove me from that service? Many thanks.
Spot on with this write-up, I really believe this site needs much more attention. I’ll probably be back again to read through more, thanks for the advice.