用 HTML、CSS 和 JavaScript 实现五子棋人机对战游戏

发布于:2025-06-14 ⋅ 阅读:(23) ⋅ 点赞:(0)

引言

在 Web 开发的世界里,通过 HTML、CSS 和 JavaScript 可以创造出各种各样有趣的互动游戏。今天,我们将深入探讨如何实现一个简单而又富有挑战性的五子棋人机对战游戏。这个游戏不仅能让你重温经典的五子棋玩法,还能通过 AI 对战功能给你带来全新的挑战。

项目概述

五子棋游戏将采用 HTML 构建页面结构,CSS 进行样式设计,JavaScript 实现游戏的逻辑和交互。整个游戏界面将包含一个棋盘、游戏状态信息、控制按钮以及胜利提示模态框等元素。

效果图 

界面设计

开发中使用了 Tailwind CSS 框架来快速搭建界面。以下是界面的主要组成部分:

  1. 游戏标题和描述:在页面顶部显示游戏的标题和简单描述,让玩家快速了解游戏内容。
  2. 游戏区域:使用 canvas 元素绘制棋盘,玩家可以通过点击棋盘上的交叉点来落子。
  3. 游戏信息面板:显示当前回合、游戏时间、步数和游戏模式等信息,方便玩家了解游戏状态。
  4. 游戏规则说明:列出五子棋的基本规则,帮助新手玩家快速上手。
  5. 控制按钮:提供重新开始、悔棋、切换游戏模式等功能,增强游戏的交互性。
  6. 胜利提示模态框:当游戏结束时,显示获胜方信息,并提供开始新游戏的按钮。

游戏逻辑实现

JavaScript 部分是游戏的核心,负责处理游戏的各种逻辑,包括棋盘绘制、落子处理、胜利判断和 AI 对战等功能。

棋盘绘制

使用 canvas 的绘图 API 绘制棋盘的网格线、天元和星位,并根据游戏状态绘制棋子。以下是绘制棋盘的代码片段:

// 绘制棋盘
function drawBoard() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制网格线
    ctx.strokeStyle = '#8B4513';
    ctx.lineWidth = 1.5;
    
    for (let i = 0; i < BOARD_SIZE; i++) {
        // 水平线
        ctx.beginPath();
        ctx.moveTo(0, i * CELL_SIZE);
        ctx.lineTo(canvas.width, i * CELL_SIZE);
        ctx.stroke();
        
        // 垂直线
        ctx.beginPath();
        ctx.moveTo(i * CELL_SIZE, 0);
        ctx.lineTo(i * CELL_SIZE, canvas.height);
        ctx.stroke();
    }
    
    // 绘制天元和星位
    const starPoints = [
        {x: 3, y: 3}, {x: 3, y: 11}, {x: 7, y: 7}, 
        {x: 11, y: 3}, {x: 11, y: 11}
    ];
    
    starPoints.forEach(point => {
        ctx.beginPath();
        ctx.arc(point.x * CELL_SIZE, point.y * CELL_SIZE, 4, 0, Math.PI * 2);
        ctx.fillStyle = '#8B4513';
        ctx.fill();
    });
    
    // 绘制棋子
    for (let i = 0; i < BOARD_SIZE; i++) {
        for (let j = 0; j < BOARD_SIZE; j++) {
            if (gameBoard[i][j] !== 0) {
                drawPiece(i, j, gameBoard[i][j]);
            }
        }
    }
}
落子处理

当玩家点击棋盘时,程序会计算点击位置对应的格子坐标,并检查该位置是否合法。如果合法,则在该位置落子,并更新游戏状态。以下是处理点击事件的代码片段:

// 点击棋盘事件
function handleCanvasClick(e) {
    if (!gameActive) return;
    
    // 如果是AI模式且当前是AI回合,不允许玩家落子
    if (isAiMode && currentPlayer !== playerPiece) {
        return;
    }
    
    const rect = canvas.getBoundingClientRect();
    const scaleX = canvas.width / rect.width;
    const scaleY = canvas.height / rect.height;
    
    // 计算点击的格子坐标
    const x = (e.clientX - rect.left) * scaleX;
    const y = (e.clientY - rect.top) * scaleY;
    
    const col = Math.round(x / CELL_SIZE);
    const row = Math.round(y / CELL_SIZE);
    
    // 检查坐标是否在棋盘内且为空
    if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE && gameBoard[row][col] === 0) {
        // 落子
        gameBoard[row][col] = currentPlayer;
        moveHistory.push({ row, col, player: currentPlayer });
        
        // 添加落子动画效果
        drawBoard();
        
        // 检查是否胜利
        if (checkWin(row, col, currentPlayer)) {
            showWinModal(currentPlayer);
            return;
        }
        
        // 检查是否平局
        if (checkDraw()) {
            gameActive = false;
            stopTimer();
            statusText.textContent = '游戏结束 - 平局!';
            return;
        }
        
        // 切换玩家
        currentPlayer = currentPlayer === 1 ? 2 : 1;
        updateGameStatus();
        
        // 如果是AI模式且现在是AI回合,让AI落子
        if (isAiMode && currentPlayer !== playerPiece) {
            setTimeout(makeAiMove, 500);
        }
    }
}
胜利判断

在每次落子后,程序会检查是否有一方在横、竖或斜方向形成五子连线。如果有,则判定该方获胜。以下是检查胜利条件的代码片段:

// 检查胜利条件
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 * dy;
            const newCol = col + i * dx;
            
            if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
                break;
            }
            
            if (gameBoard[newRow][newCol] === player) {
                count++;
            } else {
                break;
            }
        }
        
        // 反向检查
        for (let i = 1; i < 5; i++) {
            const newRow = row - i * dy;
            const newCol = col - i * dx;
            
            if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
                break;
            }
            
            if (gameBoard[newRow][newCol] === player) {
                count++;
            } else {
                break;
            }
        }
        
        if (count >= 5) {
            return true;
        }
    }
    
    return false;
}

AI 对战

AI 对战是游戏的亮点之一。我们使用了一个简单的评估函数来评估棋盘状态,并通过遍历所有可能的落子位置,选择得分最高的位置作为最佳落子位置。以下是 AI 相关的代码片段:

// AI落子
function makeAiMove() {
    if (!gameActive || !isAiMode || currentPlayer === playerPiece) {
        return;
    }
    
    showAiThinking();
    
    // 模拟AI思考时间
    setTimeout(() => {
        const aiPiece = playerPiece === 1 ? 2 : 1;
        const bestMove = findBestMove(aiPiece);
        
        if (bestMove) {
            const { row, col } = bestMove;
            
            // 落子
            gameBoard[row][col] = aiPiece;
            moveHistory.push({ row, col, player: aiPiece });
            
            // 添加落子动画效果
            drawBoard();
            
            // 检查是否胜利
            if (checkWin(row, col, aiPiece)) {
                hideAiThinking();
                showWinModal(aiPiece);
                return;
            }
            
            // 检查是否平局
            if (checkDraw()) {
                gameActive = false;
                stopTimer();
                statusText.textContent = '游戏结束 - 平局!';
                hideAiThinking();
                return;
            }
            
            // 切换玩家
            currentPlayer = playerPiece;
            updateGameStatus();
            hideAiThinking();
        }
    }, 800);
}

// AI评估函数 - 评估棋盘状态的分数
function evaluateBoard(player) {
    const opponent = player === 1 ? 2 : 1;
    let score = 0;
    
    // 检查所有可能的5连位置
    for (let i = 0; i < BOARD_SIZE; i++) {
        for (let j = 0; j < BOARD_SIZE; j++) {
            if (gameBoard[i][j] === 0) {
                continue;
            }
            
            // 四个方向检查
            const directions = [
                [1, 0],   // 水平
                [0, 1],   // 垂直
                [1, 1],   // 对角线
                [1, -1]   // 反对角线
            ];
            
            for (const [dx, dy] of directions) {
                // 检查是否会超出边界
                if (i + 4 * dy >= BOARD_SIZE || i + 4 * dy < 0 || 
                    j + 4 * dx >= BOARD_SIZE || j + 4 * dx < 0) {
                    continue;
                }
                
                // 计算当前方向的连子数
                let count = 1;
                let emptySpaces = 0;
                let blockedEnds = 0;
                
                // 正向检查
                for (let k = 1; k < 5; k++) {
                    const row = i + k * dy;
                    const col = j + k * dx;
                    
                    if (gameBoard[row][col] === gameBoard[i][j]) {
                        count++;
                    } else if (gameBoard[row][col] === 0) {
                        emptySpaces++;
                        break;
                    } else {
                        blockedEnds++;
                        break;
                    }
                }
                
                // 反向检查
                for (let k = 1; k < 5; k++) {
                    const row = i - k * dy;
                    const col = j - k * dx;
                    
                    if (gameBoard[row][col] === gameBoard[i][j]) {
                        count++;
                    } else if (gameBoard[row][col] === 0) {
                        emptySpaces++;
                        break;
                    } else {
                        blockedEnds++;
                        break;
                    }
                }
                
                // 如果两端都被堵,这条线无效
                if (blockedEnds === 2) {
                    continue;
                }
                
                // 根据连子数和开放端计算分数
                const isPlayerPiece = gameBoard[i][j] === player;
                let lineScore = 0;
                
                if (count >= 5) {
                    lineScore = isPlayerPiece ? 10000 : -10000; // 胜利
                } else if (count === 4) {
                    if (emptySpaces === 2) {
                        lineScore = isPlayerPiece ? 1000 : -1000; // 活四
                    } else if (emptySpaces === 1) {
                        lineScore = isPlayerPiece ? 100 : -100; // 冲四
                    }
                } else if (count === 3) {
                    if (emptySpaces === 2) {
                        lineScore = isPlayerPiece ? 100 : -100; // 活三
                    } else if (emptySpaces === 1) {
                        lineScore = isPlayerPiece ? 10 : -10; // 冲三
                    }
                } else if (count === 2) {
                    if (emptySpaces === 2) {
                        lineScore = isPlayerPiece ? 5 : -5; // 活二
                    } else if (emptySpaces === 1) {
                        lineScore = isPlayerPiece ? 1 : -1; // 冲二
                    }
                }
                
                score += lineScore;
            }
        }
    }
    
    return score;
}

// AI寻找最佳落子位置
function findBestMove(player) {
    const opponent = player === 1 ? 2 : 1;
    let bestScore = -Infinity;
    let bestMove = null;
    
    // 只考虑已有棋子周围的空位
    const possibleMoves = getPossibleMoves();
    
    for (const { row, col } of possibleMoves) {
        // 尝试落子
        gameBoard[row][col] = player;
        
        // 检查是否直接获胜
        if (checkWin(row, col, player)) {
            gameBoard[row][col] = 0; // 恢复棋盘
            return { row, col };
        }
        
        // 评估这个位置的分数
        let score = evaluateBoard(player);
        
        // 恢复棋盘
        gameBoard[row][col] = 0;
        
        // 更新最佳移动
        if (score > bestScore) {
            bestScore = score;
            bestMove = { row, col };
        }
    }
    
    // 如果没有找到最佳移动,随机选择一个空位
    if (!bestMove && possibleMoves.length > 0) {
        const randomIndex = Math.floor(Math.random() * possibleMoves.length);
        return possibleMoves[randomIndex];
    }
    
    // 如果棋盘为空,选择中心点
    if (!bestMove) {
        return { row: Math.floor(BOARD_SIZE / 2), col: Math.floor(BOARD_SIZE / 2) };
    }
    
    return bestMove;
}

完整代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋游戏</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#8B5A2B',
                        secondary: '#D2B48C',
                        board: '#DEB887',
                        black: '#000000',
                        white: '#FFFFFF',
                        ai: '#FF6B6B',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .board-grid {
                background-size: 100% 100%;
                background-image: linear-gradient(to right, rgba(0,0,0,0.6) 1px, transparent 1px),
                                  linear-gradient(to bottom, rgba(0,0,0,0.6) 1px, transparent 1px);
            }
            .piece-shadow {
                filter: drop-shadow(0 4px 3px rgb(0 0 0 / 0.07)) drop-shadow(0 2px 2px rgb(0 0 0 / 0.06));
            }
            .piece-transition {
                transition: all 0.2s ease-out;
            }
            .btn-hover {
                transition: all 0.2s ease;
            }
            .btn-hover:hover {
                transform: translateY(-2px);
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            }
            .pulse-animation {
                animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
            }
            @keyframes pulse {
                0%, 100% {
                    opacity: 1;
                }
                50% {
                    opacity: 0.5;
                }
            }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen flex flex-col items-center justify-center p-4 font-sans">
    <div class="max-w-4xl w-full bg-white rounded-2xl shadow-xl overflow-hidden">
        <div class="bg-primary text-white p-6 text-center">
            <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold">五子棋</h1>
            <p class="text-secondary mt-2">经典对弈游戏</p>
        </div>
        
        <div class="p-6 md:p-8 flex flex-col md:flex-row gap-6">
            <!-- 游戏区域 -->
            <div class="flex-1 relative">
                <div class="aspect-square bg-board rounded-lg shadow-lg overflow-hidden board-grid" style="background-size: calc(100% / 14) calc(100% / 14);">
                    <canvas id="gameCanvas" class="w-full h-full cursor-pointer"></canvas>
                </div>
                
                <div id="gameStatus" class="mt-4 p-3 bg-secondary/20 rounded-lg text-center">
                    <p id="statusText" class="font-medium">游戏开始! 黑棋先行</p>
                </div>
            </div>
            
            <!-- 游戏控制和信息 -->
            <div class="w-full md:w-80 flex flex-col gap-6">
                <div class="bg-gray-50 rounded-lg p-5 shadow-sm">
                    <h2 class="text-lg font-semibold mb-3 flex items-center">
                        <i class="fa-solid fa-info-circle mr-2 text-primary"></i>游戏信息
                    </h2>
                    <div class="space-y-3">
                        <div class="flex items-center justify-between">
                            <span class="text-gray-600">当前回合</span>
                            <div class="flex items-center">
                                <div id="currentPlayer" class="w-6 h-6 rounded-full bg-black mr-2 piece-shadow"></div>
                                <span id="playerText">黑棋</span>
                            </div>
                        </div>
                        <div class="flex items-center justify-between">
                            <span class="text-gray-600">游戏时间</span>
                            <span id="gameTime" class="font-mono">00:00</span>
                        </div>
                        <div class="flex items-center justify-between">
                            <span class="text-gray-600">步数</span>
                            <span id="moveCount">0</span>
                        </div>
                        <div class="flex items-center justify-between">
                            <span class="text-gray-600">游戏模式</span>
                            <div id="gameMode" class="flex items-center">
                                <div class="w-3 h-3 rounded-full bg-green-500 mr-2"></div>
                                <span id="modeText">人机对战</span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="bg-gray-50 rounded-lg p-5 shadow-sm">
                    <h2 class="text-lg font-semibold mb-3 flex items-center">
                        <i class="fa-solid fa-crown mr-2 text-primary"></i>游戏规则
                    </h2>
                    <ul class="text-sm text-gray-600 space-y-2">
                        <li class="flex items-start">
                            <i class="fa-solid fa-circle text-xs mt-1.5 mr-2 text-primary"></i>
                            <span>黑棋和白棋轮流在棋盘上落子</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fa-solid fa-circle text-xs mt-1.5 mr-2 text-primary"></i>
                            <span>先在横、竖或斜方向形成五子连线者获胜</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fa-solid fa-circle text-xs mt-1.5 mr-2 text-primary"></i>
                            <span>点击棋盘上的交叉点放置棋子</span>
                        </li>
                    </ul>
                </div>
                
                <div class="flex flex-col gap-3">
                    <div class="flex gap-3">
                        <button id="restartBtn" class="flex-1 bg-primary hover:bg-primary/90 text-white py-3 px-4 rounded-lg font-medium btn-hover flex items-center justify-center">
                            <i class="fa-solid fa-refresh mr-2"></i>重新开始
                        </button>
                        <button id="undoBtn" class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-700 py-3 px-4 rounded-lg font-medium btn-hover flex items-center justify-center">
                            <i class="fa-solid fa-undo mr-2"></i>悔棋
                        </button>
                    </div>
                    
                    <div class="flex gap-3">
                        <button id="humanBtn" class="flex-1 bg-white border border-gray-300 hover:bg-gray-50 text-gray-700 py-3 px-4 rounded-lg font-medium btn-hover flex items-center justify-center">
                            <i class="fa-solid fa-user mr-2"></i>人人对战
                        </button>
                        <button id="aiBtn" class="flex-1 bg-green-500 hover:bg-green-600 text-white py-3 px-4 rounded-lg font-medium btn-hover flex items-center justify-center">
                            <i class="fa-solid fa-robot mr-2"></i>人机对战
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="bg-gray-50 p-4 text-center text-sm text-gray-500">
            <p>© 2025 五子棋游戏 | 一个简单的 Web 游戏</p>
        </div>
    </div>

    <!-- 胜利提示模态框 -->
    <div id="winModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden opacity-0 transition-opacity duration-300">
        <div class="bg-white rounded-xl p-8 max-w-md w-full mx-4 transform transition-transform duration-300 scale-95">
            <div class="text-center">
                <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fa-solid fa-trophy text-3xl text-yellow-500"></i>
                </div>
                <h2 class="text-2xl font-bold mb-2" id="winnerText">黑棋获胜!</h2>
                <p class="text-gray-600 mb-6">恭喜您赢得了这场精彩的比赛!</p>
                <button id="newGameBtn" class="bg-primary hover:bg-primary/90 text-white py-3 px-8 rounded-lg font-medium btn-hover">
                    开始新游戏
                </button>
            </div>
        </div>
    </div>

    <!-- AI思考提示 -->
    <div id="aiThinking" class="fixed inset-0 bg-black/30 flex items-center justify-center z-40 hidden">
        <div class="bg-white rounded-xl p-6 max-w-xs w-full mx-4 flex items-center">
            <div class="mr-4">
                <i class="fa-solid fa-circle-notch fa-spin text-2xl text-primary"></i>
            </div>
            <div>
                <h3 class="font-bold text-lg">AI思考中</h3>
                <p class="text-gray-600 text-sm">电脑正在思考下一步...</p>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // 游戏常量
            const BOARD_SIZE = 15; // 15x15的棋盘
            const CELL_SIZE = Math.min(window.innerWidth * 0.8 / BOARD_SIZE, window.innerHeight * 0.6 / BOARD_SIZE);
            const PIECE_SIZE = CELL_SIZE * 0.8;
            
            // 游戏状态
            let gameBoard = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(0));
            let currentPlayer = 1; // 1: 黑棋, 2: 白棋
            let gameActive = true;
            let moveHistory = [];
            let gameTime = 0;
            let timerInterval;
            let isAiMode = true; // 默认开启AI模式
            let playerPiece = 1; // 玩家默认执黑
            
            // DOM元素
            const canvas = document.getElementById('gameCanvas');
            const ctx = canvas.getContext('2d');
            const statusText = document.getElementById('statusText');
            const currentPlayerEl = document.getElementById('currentPlayer');
            const playerText = document.getElementById('playerText');
            const moveCountEl = document.getElementById('moveCount');
            const gameTimeEl = document.getElementById('gameTime');
            const restartBtn = document.getElementById('restartBtn');
            const undoBtn = document.getElementById('undoBtn');
            const winModal = document.getElementById('winModal');
            const winnerText = document.getElementById('winnerText');
            const newGameBtn = document.getElementById('newGameBtn');
            const aiBtn = document.getElementById('aiBtn');
            const humanBtn = document.getElementById('humanBtn');
            const gameMode = document.getElementById('gameMode');
            const modeText = document.getElementById('modeText');
            const aiThinking = document.getElementById('aiThinking');
            
            // 设置Canvas尺寸
            canvas.width = CELL_SIZE * (BOARD_SIZE - 1);
            canvas.height = CELL_SIZE * (BOARD_SIZE - 1);
            
            // 绘制棋盘
            function drawBoard() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                // 绘制网格线
                ctx.strokeStyle = '#8B4513';
                ctx.lineWidth = 1.5;
                
                for (let i = 0; i < BOARD_SIZE; i++) {
                    // 水平线
                    ctx.beginPath();
                    ctx.moveTo(0, i * CELL_SIZE);
                    ctx.lineTo(canvas.width, i * CELL_SIZE);
                    ctx.stroke();
                    
                    // 垂直线
                    ctx.beginPath();
                    ctx.moveTo(i * CELL_SIZE, 0);
                    ctx.lineTo(i * CELL_SIZE, canvas.height);
                    ctx.stroke();
                }
                
                // 绘制天元和星位
                const starPoints = [
                    {x: 3, y: 3}, {x: 3, y: 11}, {x: 7, y: 7}, 
                    {x: 11, y: 3}, {x: 11, y: 11}
                ];
                
                starPoints.forEach(point => {
                    ctx.beginPath();
                    ctx.arc(point.x * CELL_SIZE, point.y * CELL_SIZE, 4, 0, Math.PI * 2);
                    ctx.fillStyle = '#8B4513';
                    ctx.fill();
                });
                
                // 绘制棋子
                for (let i = 0; i < BOARD_SIZE; i++) {
                    for (let j = 0; j < BOARD_SIZE; j++) {
                        if (gameBoard[i][j] !== 0) {
                            drawPiece(i, j, gameBoard[i][j]);
                        }
                    }
                }
            }
            
            // 绘制棋子
            function drawPiece(row, col, player) {
                const x = col * CELL_SIZE;
                const y = row * CELL_SIZE;
                
                // 棋子阴影
                ctx.beginPath();
                ctx.arc(x, y, PIECE_SIZE / 2 + 2, 0, Math.PI * 2);
                ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
                ctx.fill();
                
                // 棋子本体
                ctx.beginPath();
                ctx.arc(x, y, PIECE_SIZE / 2, 0, Math.PI * 2);
                
                if (player === 1) {
                    // 黑棋 - 渐变效果
                    const gradient = ctx.createRadialGradient(
                        x - PIECE_SIZE / 6, y - PIECE_SIZE / 6, PIECE_SIZE / 10,
                        x, y, PIECE_SIZE / 2
                    );
                    gradient.addColorStop(0, '#555');
                    gradient.addColorStop(1, '#000');
                    ctx.fillStyle = gradient;
                } else if (player === 2) {
                    // 白棋 - 渐变效果
                    const gradient = ctx.createRadialGradient(
                        x - PIECE_SIZE / 6, y - PIECE_SIZE / 6, PIECE_SIZE / 10,
                        x, y, PIECE_SIZE / 2
                    );
                    gradient.addColorStop(0, '#fff');
                    gradient.addColorStop(1, '#ddd');
                    ctx.fillStyle = gradient;
                }
                
                ctx.fill();
                
                // 棋子边缘
                ctx.strokeStyle = player === 1 ? '#333' : '#ccc';
                ctx.lineWidth = 1;
                ctx.stroke();
            }
            
            // 检查胜利条件
            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 * dy;
                        const newCol = col + i * dx;
                        
                        if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
                            break;
                        }
                        
                        if (gameBoard[newRow][newCol] === player) {
                            count++;
                        } else {
                            break;
                        }
                    }
                    
                    // 反向检查
                    for (let i = 1; i < 5; i++) {
                        const newRow = row - i * dy;
                        const newCol = col - i * dx;
                        
                        if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
                            break;
                        }
                        
                        if (gameBoard[newRow][newCol] === player) {
                            count++;
                        } else {
                            break;
                        }
                    }
                    
                    if (count >= 5) {
                        return true;
                    }
                }
                
                return false;
            }
            
            // 检查平局
            function checkDraw() {
                for (let i = 0; i < BOARD_SIZE; i++) {
                    for (let j = 0; j < BOARD_SIZE; j++) {
                        if (gameBoard[i][j] === 0) {
                            return false; // 还有空位,不是平局
                        }
                    }
                }
                return true; // 棋盘已满,平局
            }
            
            // 更新游戏状态显示
            function updateGameStatus() {
                if (gameActive) {
                    if (isAiMode && currentPlayer !== playerPiece) {
                        statusText.textContent = `游戏进行中 - AI思考中...`;
                        currentPlayerEl.className = `w-6 h-6 rounded-full ${currentPlayer === 1 ? 'bg-black' : 'bg-white border border-gray-300'} mr-2 piece-shadow pulse-animation`;
                        playerText.textContent = 'AI';
                    } else {
                        statusText.textContent = `游戏进行中 - ${currentPlayer === 1 ? '黑棋' : '白棋'}回合`;
                        currentPlayerEl.className = `w-6 h-6 rounded-full ${currentPlayer === 1 ? 'bg-black' : 'bg-white border border-gray-300'} mr-2 piece-shadow`;
                        playerText.textContent = currentPlayer === 1 ? '黑棋' : '白棋';
                    }
                }
                moveCountEl.textContent = moveHistory.length;
            }
            
            // 更新游戏时间
            function updateGameTime() {
                gameTime++;
                const minutes = Math.floor(gameTime / 60).toString().padStart(2, '0');
                const seconds = (gameTime % 60).toString().padStart(2, '0');
                gameTimeEl.textContent = `${minutes}:${seconds}`;
            }
            
            // 开始计时
            function startTimer() {
                clearInterval(timerInterval);
                timerInterval = setInterval(updateGameTime, 1000);
            }
            
            // 停止计时
            function stopTimer() {
                clearInterval(timerInterval);
            }
            
            // 显示胜利模态框
            function showWinModal(winner) {
                gameActive = false;
                stopTimer();
                
                let winnerTextContent = '';
                if (isAiMode) {
                    winnerTextContent = winner === playerPiece ? '恭喜您获胜!' : 'AI获胜!';
                } else {
                    winnerTextContent = `${winner === 1 ? '黑棋' : '白棋'}获胜!`;
                }
                
                winnerText.textContent = winnerTextContent;
                winModal.classList.remove('hidden');
                
                // 添加动画效果
                setTimeout(() => {
                    winModal.classList.add('opacity-100');
                    winModal.querySelector('div').classList.remove('scale-95');
                    winModal.querySelector('div').classList.add('scale-100');
                }, 10);
            }
            
            // 隐藏胜利模态框
            function hideWinModal() {
                winModal.classList.remove('opacity-100');
                winModal.querySelector('div').classList.remove('scale-100');
                winModal.querySelector('div').classList.add('scale-95');
                
                setTimeout(() => {
                    winModal.classList.add('hidden');
                }, 300);
            }
            
            // 重置游戏
            function resetGame() {
                gameBoard = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(0));
                currentPlayer = 1;
                gameActive = true;
                moveHistory = [];
                gameTime = 0;
                
                drawBoard();
                updateGameStatus();
                gameTimeEl.textContent = '00:00';
                
                stopTimer();
                startTimer();
                
                hideWinModal();
                
                // 如果是AI模式且玩家执白,让AI先行
                if (isAiMode && playerPiece === 2) {
                    setTimeout(makeAiMove, 500);
                }
            }
            
            // 悔棋
            function undoMove() {
                if (moveHistory.length === 0 || !gameActive) {
                    return;
                }
                
                // 如果是AI模式,需要撤销两步(玩家一步,AI一步)
                if (isAiMode && moveHistory.length >= 2) {
                    for (let i = 0; i < 2; i++) {
                        const lastMove = moveHistory.pop();
                        gameBoard[lastMove.row][lastMove.col] = 0;
                        currentPlayer = lastMove.player; // 回到上一个玩家
                    }
                } else if (!isAiMode) {
                    const lastMove = moveHistory.pop();
                    gameBoard[lastMove.row][lastMove.col] = 0;
                    currentPlayer = lastMove.player; // 回到上一个玩家
                }
                
                drawBoard();
                updateGameStatus();
            }
            
            // 显示AI思考提示
            function showAiThinking() {
                aiThinking.classList.remove('hidden');
                setTimeout(() => {
                    aiThinking.classList.add('opacity-100');
                }, 10);
            }
            
            // 隐藏AI思考提示
            function hideAiThinking() {
                aiThinking.classList.remove('opacity-100');
                setTimeout(() => {
                    aiThinking.classList.add('hidden');
                }, 300);
            }
            
            // AI落子
            function makeAiMove() {
                if (!gameActive || !isAiMode || currentPlayer === playerPiece) {
                    return;
                }
                
                showAiThinking();
                
                // 模拟AI思考时间
                setTimeout(() => {
                    const aiPiece = playerPiece === 1 ? 2 : 1;
                    const bestMove = findBestMove(aiPiece);
                    
                    if (bestMove) {
                        const { row, col } = bestMove;
                        
                        // 落子
                        gameBoard[row][col] = aiPiece;
                        moveHistory.push({ row, col, player: aiPiece });
                        
                        // 添加落子动画效果
                        drawBoard();
                        
                        // 检查是否胜利
                        if (checkWin(row, col, aiPiece)) {
                            hideAiThinking();
                            showWinModal(aiPiece);
                            return;
                        }
                        
                        // 检查是否平局
                        if (checkDraw()) {
                            gameActive = false;
                            stopTimer();
                            statusText.textContent = '游戏结束 - 平局!';
                            hideAiThinking();
                            return;
                        }
                        
                        // 切换玩家
                        currentPlayer = playerPiece;
                        updateGameStatus();
                        hideAiThinking();
                    }
                }, 800);
            }
            
            // AI评估函数 - 评估棋盘状态的分数
            function evaluateBoard(player) {
                const opponent = player === 1 ? 2 : 1;
                let score = 0;
                
                // 检查所有可能的5连位置
                for (let i = 0; i < BOARD_SIZE; i++) {
                    for (let j = 0; j < BOARD_SIZE; j++) {
                        if (gameBoard[i][j] === 0) {
                            continue;
                        }
                        
                        // 四个方向检查
                        const directions = [
                            [1, 0],   // 水平
                            [0, 1],   // 垂直
                            [1, 1],   // 对角线
                            [1, -1]   // 反对角线
                        ];
                        
                        for (const [dx, dy] of directions) {
                            // 检查是否会超出边界
                            if (i + 4 * dy >= BOARD_SIZE || i + 4 * dy < 0 || 
                                j + 4 * dx >= BOARD_SIZE || j + 4 * dx < 0) {
                                continue;
                            }
                            
                            // 计算当前方向的连子数
                            let count = 1;
                            let emptySpaces = 0;
                            let blockedEnds = 0;
                            
                            // 正向检查
                            for (let k = 1; k < 5; k++) {
                                const row = i + k * dy;
                                const col = j + k * dx;
                                
                                if (gameBoard[row][col] === gameBoard[i][j]) {
                                    count++;
                                } else if (gameBoard[row][col] === 0) {
                                    emptySpaces++;
                                    break;
                                } else {
                                    blockedEnds++;
                                    break;
                                }
                            }
                            
                            // 反向检查
                            for (let k = 1; k < 5; k++) {
                                const row = i - k * dy;
                                const col = j - k * dx;
                                
                                if (gameBoard[row][col] === gameBoard[i][j]) {
                                    count++;
                                } else if (gameBoard[row][col] === 0) {
                                    emptySpaces++;
                                    break;
                                } else {
                                    blockedEnds++;
                                    break;
                                }
                            }
                            
                            // 如果两端都被堵,这条线无效
                            if (blockedEnds === 2) {
                                continue;
                            }
                            
                            // 根据连子数和开放端计算分数
                            const isPlayerPiece = gameBoard[i][j] === player;
                            let lineScore = 0;
                            
                            if (count >= 5) {
                                lineScore = isPlayerPiece ? 10000 : -10000; // 胜利
                            } else if (count === 4) {
                                if (emptySpaces === 2) {
                                    lineScore = isPlayerPiece ? 1000 : -1000; // 活四
                                } else if (emptySpaces === 1) {
                                    lineScore = isPlayerPiece ? 100 : -100; // 冲四
                                }
                            } else if (count === 3) {
                                if (emptySpaces === 2) {
                                    lineScore = isPlayerPiece ? 100 : -100; // 活三
                                } else if (emptySpaces === 1) {
                                    lineScore = isPlayerPiece ? 10 : -10; // 冲三
                                }
                            } else if (count === 2) {
                                if (emptySpaces === 2) {
                                    lineScore = isPlayerPiece ? 5 : -5; // 活二
                                } else if (emptySpaces === 1) {
                                    lineScore = isPlayerPiece ? 1 : -1; // 冲二
                                }
                            }
                            
                            score += lineScore;
                        }
                    }
                }
                
                return score;
            }
            
            // AI寻找最佳落子位置
            function findBestMove(player) {
                const opponent = player === 1 ? 2 : 1;
                let bestScore = -Infinity;
                let bestMove = null;
                
                // 只考虑已有棋子周围的空位
                const possibleMoves = getPossibleMoves();
                
                for (const { row, col } of possibleMoves) {
                    // 尝试落子
                    gameBoard[row][col] = player;
                    
                    // 检查是否直接获胜
                    if (checkWin(row, col, player)) {
                        gameBoard[row][col] = 0; // 恢复棋盘
                        return { row, col };
                    }
                    
                    // 评估这个位置的分数
                    let score = evaluateBoard(player);
                    
                    // 恢复棋盘
                    gameBoard[row][col] = 0;
                    
                    // 更新最佳移动
                    if (score > bestScore) {
                        bestScore = score;
                        bestMove = { row, col };
                    }
                }
                
                // 如果没有找到最佳移动,随机选择一个空位
                if (!bestMove && possibleMoves.length > 0) {
                    const randomIndex = Math.floor(Math.random() * possibleMoves.length);
                    return possibleMoves[randomIndex];
                }
                
                // 如果棋盘为空,选择中心点
                if (!bestMove) {
                    return { row: Math.floor(BOARD_SIZE / 2), col: Math.floor(BOARD_SIZE / 2) };
                }
                
                return bestMove;
            }
            
            // 获取所有可能的落子位置(已有棋子周围的空位)
            function getPossibleMoves() {
                const moves = [];
                const directions = [
                    [0, 1], [1, 0], [1, 1], [1, -1],
                    [0, -1], [-1, 0], [-1, -1], [-1, 1]
                ];
                
                // 先检查是否有任何棋子
                let hasPieces = false;
                for (let i = 0; i < BOARD_SIZE; i++) {
                    for (let j = 0; j < BOARD_SIZE; j++) {
                        if (gameBoard[i][j] !== 0) {
                            hasPieces = true;
                            break;
                        }
                    }
                    if (hasPieces) break;
                }
                
                // 如果棋盘为空,返回中心点
                if (!hasPieces) {
                    return [{ row: Math.floor(BOARD_SIZE / 2), col: Math.floor(BOARD_SIZE / 2) }];
                }
                
                // 检查已有棋子周围的空位
                for (let i = 0; i < BOARD_SIZE; i++) {
                    for (let j = 0; j < BOARD_SIZE; j++) {
                        if (gameBoard[i][j] !== 0) {
                            // 检查周围8个方向
                            for (const [dx, dy] of directions) {
                                const newRow = i + dy;
                                const newCol = j + dx;
                                
                                // 检查是否在棋盘内且为空
                                if (newRow >= 0 && newRow < BOARD_SIZE && 
                                    newCol >= 0 && newCol < BOARD_SIZE && 
                                    gameBoard[newRow][newCol] === 0) {
                                    
                                    // 避免重复添加
                                    const isDuplicate = moves.some(move => 
                                        move.row === newRow && move.col === newCol);
                                    
                                    if (!isDuplicate) {
                                        moves.push({ row: newRow, col: newCol });
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 如果没有找到周围的空位,返回所有空位
                if (moves.length === 0) {
                    for (let i = 0; i < BOARD_SIZE; i++) {
                        for (let j = 0; j < BOARD_SIZE; j++) {
                            if (gameBoard[i][j] === 0) {
                                moves.push({ row: i, col: j });
                            }
                        }
                    }
                }
                
                return moves;
            }
            
            // 点击棋盘事件
            function handleCanvasClick(e) {
                if (!gameActive) return;
                
                // 如果是AI模式且当前是AI回合,不允许玩家落子
                if (isAiMode && currentPlayer !== playerPiece) {
                    return;
                }
                
                const rect = canvas.getBoundingClientRect();
                const scaleX = canvas.width / rect.width;
                const scaleY = canvas.height / rect.height;
                
                // 计算点击的格子坐标
                const x = (e.clientX - rect.left) * scaleX;
                const y = (e.clientY - rect.top) * scaleY;
                
                const col = Math.round(x / CELL_SIZE);
                const row = Math.round(y / CELL_SIZE);
                
                // 检查坐标是否在棋盘内且为空
                if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE && gameBoard[row][col] === 0) {
                    // 落子
                    gameBoard[row][col] = currentPlayer;
                    moveHistory.push({ row, col, player: currentPlayer });
                    
                    // 添加落子动画效果
                    drawBoard();
                    
                    // 检查是否胜利
                    if (checkWin(row, col, currentPlayer)) {
                        showWinModal(currentPlayer);
                        return;
                    }
                    
                    // 检查是否平局
                    if (checkDraw()) {
                        gameActive = false;
                        stopTimer();
                        statusText.textContent = '游戏结束 - 平局!';
                        return;
                    }
                    
                    // 切换玩家
                    currentPlayer = currentPlayer === 1 ? 2 : 1;
                    updateGameStatus();
                    
                    // 如果是AI模式且现在是AI回合,让AI落子
                    if (isAiMode && currentPlayer !== playerPiece) {
                        setTimeout(makeAiMove, 500);
                    }
                }
            }
            
            // 切换到人机对战模式
            function switchToAiMode() {
                isAiMode = true;
                playerPiece = 1; // 默认玩家执黑
                modeText.textContent = '人机对战';
                gameMode.querySelector('div').className = 'w-3 h-3 rounded-full bg-green-500 mr-2';
                aiBtn.className = 'flex-1 bg-green-500 hover:bg-green-600 text-white py-3 px-4 rounded-lg font-medium btn-hover flex items-center justify-center';
                humanBtn.className = 'flex-1 bg-white border border-gray-300 hover:bg-gray-50 text-gray-700 py-3 px-4 rounded-lg font-medium btn-hover flex items-center justify-center';
                resetGame();
            }
            
            // 切换到人人对战模式
            function switchToHumanMode() {
                isAiMode = false;
                modeText.textContent = '人人对战';
                gameMode.querySelector('div').className = 'w-3 h-3 rounded-full bg-blue-500 mr-2';
                aiBtn.className = 'flex-1 bg-white border border-gray-300 hover:bg-gray-50 text-gray-700 py-3 px-4 rounded-lg font-medium btn-hover flex items-center justify-center';
                humanBtn.className = 'flex-1 bg-blue-500 hover:bg-blue-600 text-white py-3 px-4 rounded-lg font-medium btn-hover flex items-center justify-center';
                resetGame();
            }
            
            // 事件监听
            canvas.addEventListener('click', handleCanvasClick);
            restartBtn.addEventListener('click', resetGame);
            undoBtn.addEventListener('click', undoMove);
            newGameBtn.addEventListener('click', resetGame);
            aiBtn.addEventListener('click', switchToAiMode);
            humanBtn.addEventListener('click', switchToHumanMode);
            
            // 鼠标悬停预览效果
            canvas.addEventListener('mousemove', (e) => {
                if (!gameActive) return;
                
                // 如果是AI模式且当前是AI回合,不显示预览
                if (isAiMode && currentPlayer !== playerPiece) {
                    return;
                }
                
                const rect = canvas.getBoundingClientRect();
                const scaleX = canvas.width / rect.width;
                const scaleY = canvas.height / rect.height;
                
                // 计算鼠标所在的格子坐标
                const x = (e.clientX - rect.left) * scaleX;
                const y = (e.clientY - rect.top) * scaleY;
                
                const col = Math.round(x / CELL_SIZE);
                const row = Math.round(y / CELL_SIZE);
                
                // 清除之前的预览
                drawBoard();
                
                // 如果坐标在棋盘内且为空,绘制预览棋子
                if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE && gameBoard[row][col] === 0) {
                    ctx.beginPath();
                    ctx.arc(col * CELL_SIZE, row * CELL_SIZE, PIECE_SIZE / 2, 0, Math.PI * 2);
                    
                    if (currentPlayer === 1) {
                        ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
                    } else {
                        ctx.fillStyle = 'rgba(255, 255, 255, 0.6)';
                    }
                    
                    ctx.fill();
                }
            });
            
            // 鼠标离开棋盘时重绘
            canvas.addEventListener('mouseleave', () => {
                drawBoard();
            });
            
            // 初始化游戏
            drawBoard();
            updateGameStatus();
            startTimer();
        });
    </script>
</body>
</html>
    

总结

通过 HTML、CSS 和 JavaScript 的组合,实现了一个功能丰富的五子棋人机对战游戏。这个游戏不仅具有基本的五子棋玩法,还通过 AI 对战功能增加了游戏的趣味性和挑战性。在开发过程中,我们学习了如何使用 canvas 进行图形绘制,如何处理用户交互事件,以及如何实现简单的 AI 算法。希望这篇文章能对你有所帮助,让你在 Web 开发的道路上更进一步。

你可以根据自己的需求对游戏进行扩展和优化,例如添加更复杂的 AI 算法、改进界面设计、增加游戏音效等。祝你在开发过程中取得成功!


网站公告

今日签到

点亮在社区的每一天
去签到