HTML Tic Tac Toe Game: No Instructions Needed
<html>
<head>
<title>Tic Tac Toe</title>
<style>
.board {
display: flex;
flex-direction: column;
}
<pre><code>.row {
display: flex;
}
.cell {
width: 50px;
height: 50px;
border: 1px solid black;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
cursor: pointer;
}
.player-1 {
color: #e60000;
}
.player-2 {
color: #009933;
}
</code></pre>
</style>
</head>
<body>
<div class='board'>
<div class='row'>
<div class='cell' data-col='0' data-row='0'></div>
<div class='cell' data-col='1' data-row='0'></div>
<div class='cell' data-col='2' data-row='0'></div>
</div>
<div class='row'>
<div class='cell' data-col='0' data-row='1'></div>
<div class='cell' data-col='1' data-row='1'></div>
<div class='cell' data-col='2' data-row='1'></div>
</div>
<div class='row'>
<div class='cell' data-col='0' data-row='2'></div>
<div class='cell' data-col='1' data-row='2'></div>
<div class='cell' data-col='2' data-row='2'></div>
</div>
</div>
<script>
const board = document.querySelector('.board');
let player = 1;
let winner = null;
<pre><code>board.addEventListener('click', handleClick);
function handleClick(e) {
if (e.target.classList.contains('cell')) {
const col = e.target.dataset.col;
const row = e.target.dataset.row;
if (e.target.textContent !== '') {
return;
}
e.target.textContent = player === 1 ? 'X' : 'O';
e.target.classList.add(`player-${player}`);
checkWinner();
player = player === 1 ? 2 : 1;
}
}
function checkWinner() {
const cells = document.querySelectorAll('.cell');
const winningCombos = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
winningCombos.forEach((combo) => {
if (
cells[combo[0]].textContent === cells[combo[1]].textContent &&
cells[combo[1]].textContent === cells[combo[2]].textContent &&
cells[combo[0]].textContent !== ''
) {
winner = cells[combo[0]].textContent;
alert(`Player ${winner} wins!`);
}
});
}
</code></pre>
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnkl 著作权归作者所有。请勿转载和采集!