+
91
-

回答

可以,我们以五子棋为例,后端接入任意的大模型api就可以实现和大模型下棋了

我们以chatgpt为例写一个和chatgpt下五子棋的html代码,效果如下:

800_auto

点击查看代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋 vs ChatGPT</title>
    <style>
        #board {
            display: grid;
            grid-template-columns: repeat(15, 30px);
            grid-gap: 1px;
            background-color: #deb887;
            padding: 10px;
            width: fit-content;
        }
        .cell {
            width: 30px;
            height: 30px;
            background-color: #deb887;
            border: 1px solid #000;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
        }
        .black {
            background-color: #000;
            border-radius: 50%;
        }
        .white {
            background-color: #fff;
            border-radius: 50%;
        }
    </style>
</head>
<body>
    <h1>五子棋 vs ChatGPT</h1>
    <div id="board"></div>
    <p id="status"></p>
    <script>
        const board = document.getElementById('board');
        const status = document.getElementById('status');
        const size = 15;
        let gameBoard = Array(size).fill().map(() => Array(size).fill(0));
        let currentPlayer = 1; // 1 for player, 2 for AI

        // Create the board
        for (let i = 0; i < size * size; i++) {
            const cell = document.createElement('div');
            cell.classList.add('cell');
            cell.addEventListener('click', () => makeMove(i));
            board.appendChild(cell);
        }

        function makeMove(index) {
            if (currentPlayer !== 1) return;
            const row = Math.floor(index / size);
            const col = index % size;
            if (gameBoard[row][col] !== 0) return;

            gameBoard[row][col] = 1;
            updateBoard();
            if (checkWin(row, col, 1)) {
                status.textContent = "你赢了!";
                return;
            }
            currentPlayer = 2;
            status.textContent = "AI正在思考...";
            setTimeout(aiMove, 1000);
        }

        async function aiMove() {
            try {
                const response = await fetch('https://api.openai.com/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer YOUR_API_KEY_HERE' // 替换为你的API密钥
                    },
                    body: JSON.stringify({
                        model: "gpt-3.5-turbo",
                        messages: [{
                            role: "system",
                            content: "你是一个五子棋AI。棋盘是15x15的。你的任务是根据当前棋局给出下一步最佳落子位置。请用'行,列'的格式回复,不要回复其他内容,例如'7,8'。"
                        }, {
                            role: "user",
                            content: `当前棋局:${JSON.stringify(gameBoard)}`
                        }]
                    })
                });

                const data = await response.json();
                const aiMove = data.choices[0].message.content.split(',');
                const row = parseInt(aiMove[0]);
                const col = parseInt(aiMove[1]);

                gameBoard[row][col] = 2;
                updateBoard();
                if (checkWin(row, col, 2)) {
                    status.textContent = "AI赢了!";
                    return;
                }
                currentPlayer = 1;
                status.textContent = "轮到你了";
            } catch (error) {
                console.error('Error:', error);
                status.textContent = "AI出错了,请重试";
                currentPlayer = 1;
            }
        }

        function updateBoard() {
            const cells = document.querySelectorAll('.cell');
            for (let i = 0; i < size; i++) {
                for (let j = 0; j < size; j++) {
                    const index = i * size + j;
                    cells[index].className = 'cell';
                    if (gameBoard[i][j] === 1) {
                        cells[index].classList.add('black');
                    } else if (gameBoard[i][j] === 2) {
                        cells[index].classList.add('white');
                    }
                }
            }
        }

        function checkWin(row, col, player) {
            const directions = [
                [1, 0], [0, 1], [1, 1], [1, -1]
            ];

            for (const [dx, dy] of directions) {
                let count = 1;
                for (let i = 1; i < 5; i++) {
                    const newRow = row + i * dx;
                    const newCol = col + i * dy;
                    if (newRow < 0 || newRow >= size || newCol < 0 || newCol >= size || gameBoard[newRow][newCol] !== player) {
                        break;
                    }
                    count++;
                }
                for (let i = 1; i < 5; i++) {
                    const newRow = row - i * dx;
                    const newCol = col - i * dy;
                    if (newRow < 0 || newRow >= size || newCol < 0 || newCol >= size || gameBoard[newRow][newCol] !== player) {
                        break;
                    }
                    count++;
                }
                if (count >= 5) return true;
            }
            return false;
        }
    </script>
</body>
</html>

网友回复

我知道答案,我要回答