Play Tic-Tac-Toe: Free Online Game - No Download Required
<html>
<head>
<title>Tic-Tac-Toe</title>
<style>
body {
font-family: sans-serif;
}
.board {
margin: 0 auto;
border: 1px solid #999;
width: 300px;
height: 300px;
display: flex;
flex-wrap: wrap;
}
.cell {
width: 100px;
height: 100px;
display: flex;
align-items: center;
justify-content: center;
}
.cell.x {
background: #f00;
}
.cell.o {
background: #00f;
}
</style>
</head>
<body>
<div class="board">
<div class="cell" id="cell1" onclick="play(this)"></div>
<div class="cell" id="cell2" onclick="play(this)"></div>
<div class="cell" id="cell3" onclick="play(this)"></div>
<div class="cell" id="cell4" onclick="play(this)"></div>
<div class="cell" id="cell5" onclick="play(this)"></div>
<div class="cell" id="cell6" onclick="play(this)"></div>
<div class="cell" id="cell7" onclick="play(this)"></div>
<div class="cell" id="cell8" onclick="play(this)"></div>
<div class="cell" id="cell9" onclick="play(this)"></div>
</div>
<script>
let currentPlayer = 'x';
let moves = 0;
const winningCombos = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[3, 5, 7]
];
function play(cell) {
const cellId = cell.id.replace('cell', '');
const currentCell = document.getElementById('cell' + cellId);
if (currentCell.innerHTML === '') {
currentCell.innerHTML = currentPlayer;
currentCell.classList.add(currentPlayer);
moves++;
if (checkForWin()) {
alert(currentPlayer + ' Wins!');
} else if (moves === 9) {
alert('Draw!');
} else {
currentPlayer = currentPlayer === 'x' ? 'o' : 'x';
}
}
}
function checkForWin() {
const playerCells = document.querySelectorAll('.' + currentPlayer);
const playerCellIds = [].map.call(playerCells, (cell) => cell.id.replace('cell', ''));
for (let i = 0; i < winningCombos.length; i++) {
let matches = 0;
for (let j = 0; j < winningCombos[i].length; j++) {
if (playerCellIds.indexOf(winningCombos[i][j].toString()) > -1) {
matches++;
}
}
if (matches === 3) {
return true;
}
}
return false;
}
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmcl 著作权归作者所有。请勿转载和采集!