console
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>井字棋</title>
<style type="text/css">
.board {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 5px;
width: 300px;
margin-bottom: 10px;
}
.cell {
display: flex;
align-items: center;
justify-content: center;
height: 100px;
background-color: #fff;
border: 1px solid #ccc;
cursor: pointer;
font-size: 40px;
font-weight: bold;
}
.cell:hover {
background-color: #f2f2f2;
}
.message {
font-size: 24px;
margin-bottom: 10px;
}
.button {
padding: 10px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>井字棋</h1>
<div class="board"></div>
<div class="message">请点击开始游戏按钮</div>
<div class="button" onclick="startGame()">开始游戏</div>
<div class="button" onclick="surrender()">投降</div>
<div class="button" onclick="resetGame()">重置游戏</div>
<div class="button" onclick="newRound()">新一局</div>
<h2>记录</h2>
<ul id="record-list"></ul>
<script>
const boardSize = 3;
function createBoard() {
const board = [];
for (let i = 0; i < boardSize; i++) {
const row = [];
for (let j = 0; j < boardSize; j++) {
row.push(0);
}
board.push(row);
}
return board;
}
function checkWin(board, turn) {
for (let i = 0; i < boardSize; i++) {
let countRow = 0;
let countCol = 0;
for (let j = 0; j < boardSize; j++) {
if (board[i][j] === turn) {
countRow++;
}
if (board[j][i] === turn) {
countCol++;
}
}
if (countRow === boardSize || countCol === boardSize) {
return true;
}
}
let countDiagonal1 = 0;
let countDiagonal2 = 0;
for (let i = 0; i < boardSize; i++) {
if (board[i][i] === turn) {
countDiagonal1++;
}
if (board[i][boardSize - 1 - i] === turn) {
countDiagonal2++;
}
}
if (countDiagonal1 === boardSize || countDiagonal2 === boardSize) {
return true;
}
return false;
}
function checkTie(board) {
for (let i = 0; i < boardSize; i++) {
for (let j = 0; j < boardSize; j++) {
if (board[i][j] === 0) {
return false;
}
}
}
return true;
}
function getAvailableMoves(board) {
const moves = [];
for (let i = 0; i < boardSize; i++) {
for (let j = 0; j < boardSize; j++) {
if (board[i][j] === 0) {
moves.push({ row: i, col: j });
}
}
}
return moves;
}
function playNextMove() {
if (!gameStarted) {
return;
}
const move = minimax(board, 0, true).move;
board[move.row][move.col] = 1;
renderBoard();
if (checkWin(board, 1)) {
showMessage("AI获胜!");
record("AI 获胜");
} else if (checkTie(board)) {
showMessage("平局!");
record("平局");
}
}
function minimax(board, depth, isMaximizingPlayer) {
if (checkWin(board, -1)) {
return { score: -1 };
}
if (checkWin(board, 1)) {
return { score: 1 };
}
if (checkTie(board)) {
return { score: 0 };
}
const availableMoves = getAvailableMoves(board);
const moves = [];
for (const move of availableMoves) {
board[move.row][move.col] = isMaximizingPlayer ? 1 : -1;
const result = minimax(board, depth + 1, !isMaximizingPlayer);
moves.push({ score: result.score, move });
board[move.row][move.col] = 0;
}
if (isMaximizingPlayer) {
const maxScore = Math.max(...moves.map(move => move.score));
const bestMoves = moves.filter(move => move.score === maxScore);
return bestMoves[Math.floor(Math.random() * bestMoves.length)];
} else {
const minScore = Math.min(...moves.map(move => move.score));
const bestMoves = moves.filter(move => move.score === minScore);
return bestMoves[Math.floor(Math.random() * bestMoves.length)];
}
}
function renderBoard() {
const boardElement = document.querySelector('.board');
boardElement.innerHTML = '';
for (let i = 0; i < boardSize; i++) {
for (let j = 0; j < boardSize; j++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.textContent = getSymbol(board[i][j]);
cell.addEventListener('click', () => {
if (board[i][j] === 0 && !checkWin(board, -1) && !checkWin(board, 1)) {
board[i][j] = -1;
renderBoard();
if (checkWin(board, -1)) {
showMessage("玩家获胜!");
record("玩家获胜");
} else if (checkTie(board)) {
showMessage("平局!");
record("平局");
} else {
playNextMove();
}
}
});
boardElement.append(cell);
}
}
}
function startGame() {
if (board && !checkWin(board, -1) && !checkWin(board, 1)) {
showMessage("当前游戏尚未结束,请先完成当前局面。");
return;
}
const lastWinner = getLastWinner();
const playerFirst = lastWinner === 'AI';
if (playerFirst) {
showMessage("AI获胜,玩家先手,请点击棋盘格落子!");
} else {
showMessage("玩家获胜,AI先手,请等待AI出招...");
setTimeout(playNextMove, 1000);
}
board = createBoard();
renderBoard();
gameStarted = true;
}
function surrender() {
showMessage("玩家投降,AI获胜!");
record("玩家投降,AI获胜");
}
function resetGame() {
board = createBoard();
renderBoard();
showMessage("游戏已重置,请点击开始游戏按钮");
}
function newRound() {
const lastWinner = getLastWinner();
if (lastWinner === 'AI获胜') {
showMessage("AI获胜,玩家先手,请点击棋盘格落子!");
} else {
showMessage("玩家获胜,AI先手,请等待AI出招...");
setTimeout(playNextMove, 1000);
}
board = createBoard();
renderBoard();
}
function getLastWinner() {
const recordList = document.getElementById('record-list');
if (recordList.lastElementChild) {
const lastRecord = recordList.lastElementChild;
const winner = lastRecord.textContent.split(':')[0];
return winner.trim();
}
return '';
}
function showMessage(message) {
const messageElement = document.querySelector('.message');
messageElement.textContent = message;
}
function record(result) {
const recordList = document.getElementById('record-list');
const listItem = document.createElement('li');
listItem.textContent = result;
recordList.appendChild(listItem);
}
function getSymbol(value) {
if (value === -1) {
return 'X';
} else if (value === 1) {
return 'O';
}
return '';
}
let board;
let gameStarted = false;
startGame();
</script>
</body>
</html>