console
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AI井字游戏</title>
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
background-color: #f9f9f9;
margin: 0;
padding: 0;
}
h1 {
text-align: center;
margin-top: 30px;
margin-bottom: 10px;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
border-radius: 5px;
}
.board {
display: inline-block;
position: relative;
margin-top: 30px;
}
.row {
height: 100px;
clear: both;
}
.cell {
box-sizing: border-box;
float: left;
width: 100px;
height: 100px;
border: 1px solid #ccc;
font-size: 80px;
text-align: center;
cursor: pointer;
background-color: #fff;
transition: background-color 0.3s ease;
}
.cell:hover {
background-color: #eee;
}
.x {
color: blue;
}
.o {
color: red;
}
.win-line {
position: absolute;
width: 230px;
height: 10px;
background-color: green;
border-radius: 5px;
transform: rotate(45deg);
top: 45px;
left: 50%;
margin-left: -115px;
}
button {
display: block;
margin: 20px auto 0;
padding: 10px 20px;
background-color: #2196F3;
border: none;
border-radius: 5px;
color: #fff;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #1976D2;
}
</style>
</head>
<body>
<div class="container">
<h1>AI井字游戏</h1>
<div class="board"></div>
<button id="resetBtn">重置</button>
</div>
<script>
// 获取棋盘和重置按钮
const board = document.querySelector('.board');
const resetBtn = document.querySelector('#resetBtn');
// 定义游戏状态
let cells = [];
let player = 'x';
let gameOver = false;
let winLine;
// 初始化棋盘
for (let i = 0; i < 3; i++) {
const row = document.createElement('div');
row.className = 'row';
board.appendChild(row);
for (let j = 0; j < 3; j++) {
const cell = document.createElement('div');
cell.className = 'cell';
cell.dataset.row = i;
cell.dataset.col = j;
cell.addEventListener('click', handleClick);
row.appendChild(cell);
cells.push(cell);
}
}
// 处理玩家点击事件
function handleClick() {
if (gameOver) return;
if (this.innerHTML !== '') return;
this.innerHTML = player.toUpperCase();
this.classList.add(player);
checkWin();
if (!gameOver) {
player = player === 'x' ? 'o' : 'x';
setTimeout(() => {
handleAI(); // 转换为AI进行下一步操作
}, 500);
}
}
// 处理AI下棋事件
function getEmptyCells() {
return cells.filter(cell => cell.innerHTML === '');
}
function handleAI() {
const emptyCells = getEmptyCells();
if (emptyCells.length === 0) return;
const aiPlayer = player;
let selectedCell = null;
for (let i = 0; i < 2; i++) { // 随机选择两个空单元格并评估
const index = Math.floor(Math.random() * emptyCells.length);
const cell = emptyCells[index];
cell.innerHTML = aiPlayer.toUpperCase();
cell.classList.add(aiPlayer);
let maxScore = -Infinity;
let bestPosition = null;
cells.forEach(function(cell) {
if (cell.innerHTML !== '') return;
const [row, col] = [parseInt(cell.dataset.row), parseInt(cell.dataset.col)];
const positionScore = [
evaluateLine([cells[row * 3], cells[row * 3 + 1], cells[row * 3 + 2]], aiPlayer, player),
evaluateLine([cells[col], cells[col + 3], cells[col + 6]], aiPlayer, player)
];
if (row === col) {
positionScore.push(evaluateLine([cells[0], cells[4], cells[8]], aiPlayer, player));
}
if (row + col === 2) {
positionScore.push(evaluateLine([cells[2], cells[4], cells[6]], aiPlayer, player));
}
const totalScore = positionScore.reduce((sum, score) => sum + score, 0);
if (totalScore > maxScore) {
maxScore = totalScore;
bestPosition = cell;
}
});
cell.innerHTML = '';
cell.classList.remove(aiPlayer);
if (selectedCell === null || maxScore > selectedCell.score) {
selectedCell = {cell: bestPosition, score: maxScore};
}
}
selectedCell.cell.innerHTML = aiPlayer.toUpperCase();
selectedCell.cell.classList.add(aiPlayer);
if (checkWin()) {
return;
}
if (!gameOver) {
player = player === 'x' ? 'o' : 'x';
}
}
// 估价函数,评估一条线上的分数
function evaluateLine(line, aiPlayer, opponent) {
const [a, b, c] = line;
const opponents = line.filter(cell => cell.innerHTML === opponent.toUpperCase()).length;
if (opponents === 3) return -10;
const ais = line.filter(cell => cell.innerHTML === aiPlayer.toUpperCase()).length;
if (ais === 3) return 10;
if (opponents === 2 && ais === 0) return -1;
if (ais === 2 && opponents === 0) return 1;
return 0;
}
// 检查是否获胜
function checkWin() {
const lines = [
[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 i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (cells[a].innerHTML !== '' && cells[a].innerHTML === cells[b].innerHTML && cells[b].innerHTML === cells[c].innerHTML) {
gameOver = true;
if (cells[a].classList.contains('o')) { // 判断胜利方
alert('AI赢了!');
} else {
alert('您赢了!');
}
return true;
}
}
if (cells.every(cell => cell.innerHTML !== '')) {
gameOver = true;
alert('平局!');
return true;
}
return false;
}
// 重置游戏
function reset() {
cells.forEach(function(cell) {
cell.innerHTML = '';
cell.classList.remove('x', 'o');
});
if (winLine) {
winLine.remove();
winLine = null;
}
player = 'x';
gameOver = false;
}
// 绑定重置按钮的点击事件
resetBtn.addEventListener('click', reset);
</script>
</body>
</html>