井字棋 自动下棋 玩家先下,计算机后下
源码在图片后面 点赞❤️收藏⭐️关注😍
效果图
源代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tic Tac Toe Game</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f9f9f9;
}
#game-board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-auto-rows: 100px;
gap: 2px;
margin-bottom: 20px;
border: 4px solid #ff0000;
border-radius: 10px;
}
.cell {
display: flex;
justify-content: center;
align-items: center;
background-color: #ffffff;
color: #ff0000;
font-size: 2em;
cursor: pointer;
}
#reset-button {
padding: 10px 20px;
background-color: #ff0000;
color: #ffffff;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="game-board"></div>
<button id="reset-button">重新开局</button>
<script>
const board = document.getElementById('game-board');
const cells = [];
let currentPlayer = 'X';
let gameOver = false;
// Initialize game board
for (let i = 0; i < 9; i++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.dataset.index = i;
cell.addEventListener('click', handleCellClick);
board.appendChild(cell);
cells.push(cell);
}
// Reset game
document.getElementById('reset-button').addEventListener('click', resetGame);
function handleCellClick() {
if (!gameOver && this.innerText === '') {
this.innerText = currentPlayer;
checkWin();
if (!gameOver) {
setTimeout(computerMove, 500);
}
}
}
function computerMove() {
const emptyCells = cells.filter(cell => cell.innerText === '');
const randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)];
randomCell.innerText = 'O';
checkWin();
}
function checkWin() {
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]
];
for (const combo of winningCombos) {
const [a, b, c] = combo;
if (cells[a].innerText && cells[a].innerText === cells[b].innerText && cells[a].innerText === cells[c].innerText) {
gameOver = true;
setTimeout(() => {
if (currentPlayer === 'X') {
alert('Player wins!');
} else {
alert('Computer wins!');
}
}, 200);
break;
}
}
if (!cells.some(cell => cell.innerText === '')) {
gameOver = true;
setTimeout(() => {
alert('It\'s a draw!');
}, 200);
}
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}
function resetGame() {
cells.forEach(cell => {
cell.innerText = '';
});
currentPlayer = 'X';
gameOver = false;
}
</script>
</body>
</html>