SOURCE

console 命令行工具 X clear

                    
>
console
<!doctype html>
<html>
    <!--
        程序多少还有些漏洞,各位可自行修改以增加自己的编程场景经验
        作者在未来将会陆续处理这些漏洞

        本程序/网页源代码按照CC BY-SA 3.0协议授权
    -->
    <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) {    //这么聪明的AI,你就说你怎么赢吧
                // 检查行和列
                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;
            }

            // AI 下一步棋
            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>