萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

HTML5 Canvas + JavaScript 實現五子棋:完整邏輯與贏判算法

專案架構

  • 棋盤模型:15×15 二維陣列 chessData[x][y],0=空、1=白、2=黑
  • 渲染層:Canvas 繪製格線與棋子圖片
  • 邏輯層:落子驗證、勝負判定、狀態管理
  • 互動層:滑鼠點擊 → 座標換算 → 更新模型 → 重繪

核心程式碼模組化重構

1. 常數與狀態

const BOARD_SIZE = 15;
const CELL_SIZE = 40;
const CANVAS_SIZE = BOARD_SIZE * CELL_SIZE; // 600
const EMPTY = 0, WHITE = 1, BLACK = 2;

let canvas, ctx;
let chessData = [];        // 15x15 陣列
let isWhiteTurn = true;    // 白棋先行
let gameOver = false;
const imgWhite = new Image(), imgBlack = new Image();
imgWhite.src = 'images/white.png';
imgBlack.src = 'images/black.png';

2. 初始化棋盤資料結構

function initBoard() {
    chessData = Array.from({ length: BOARD_SIZE }, () => Array(BOARD_SIZE).fill(EMPTY));
}

3. Canvas 繪製

function drawBoard() {
    canvas = document.getElementById('canvas');
    ctx = canvas.getContext('2d');
    ctx.strokeStyle = '#333';
    ctx.lineWidth = 1;

    for (let i = 0; i <= CANVAS_SIZE; i += CELL_SIZE) {
        // 橫線
        ctx.beginPath();
        ctx.moveTo(0, i);
        ctx.lineTo(CANVAS_SIZE, i);
        ctx.stroke();
        // 直線
        ctx.beginPath();
        ctx.moveTo(i, 0);
        ctx.lineTo(i, CANVAS_SIZE);
        ctx.stroke();
    }
    // 星位 (可選)
    drawStarPoints();
}

function drawStarPoints() {
    const stars = [3, 7, 11];
    ctx.fillStyle = '#333';
    stars.forEach(x => stars.forEach(y => {
        ctx.beginPath();
        ctx.arc(x * CELL_SIZE + CELL_SIZE/2, y * CELL_SIZE + CELL_SIZE/2, 4, 0, Math.PI*2);
        ctx.fill();
    }));
}

4. 落子處理

function handleClick(e) {
    if (gameOver) return alert('遊戲已結束,請重新整理');

    const rect = canvas.getBoundingClientRect();
    const x = Math.floor((e.clientX - rect.left) / CELL_SIZE);
    const y = Math.floor((e.clientY - rect.top) / CELL_SIZE);

    if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE) return;
    if (chessData[x][y] !== EMPTY) return alert('該位置已有棋子');

    const player = isWhiteTurn ? WHITE : BLACK;
    placeStone(x, y, player);
    
    if (checkWin(x, y, player)) {
        gameOver = true;
        setTimeout(() => alert((player === WHITE ? '白棋' : '黑棋') + ' 獲勝!'), 100);
        return;
    }

    isWhiteTurn = !isWhiteTurn;
}

function placeStone(x, y, player) {
    chessData[x][y] = player;
    const img = player === WHITE ? imgWhite : imgBlack;
    // 圖片置中於格子
    ctx.drawImage(img, x * CELL_SIZE + CELL_SIZE/2 - img.width/2, y * CELL_SIZE + CELL_SIZE/2 - img.height/2);
}

5. 勝負判定演算法 (四方向掃描)

/**
 * 從 (x,y) 向四個方向各延伸,統計同色連線數
 * @returns {boolean} 是否連五
 */
function checkWin(x, y, player) {
    // 四個方向:水平、垂直、主對角、副對角
    const directions = [
        [1, 0],   // 水平 ←→
        [0, 1],   // 垂直 ↑↓
        [1, 1],   // 主對角 ↖↘
        [1, -1]   // 副對角 ↙↗
    ];

    for (const [dx, dy] of directions) {
        let count = 1; // 含當前落子

        // 正向
        for (let step = 1; step < 5; step++) {
            const nx = x + dx * step, ny = y + dy * step;
            if (nx < 0 || nx >= BOARD_SIZE || ny < 0 || ny >= BOARD_SIZE) break;
            if (chessData[nx][ny] !== player) break;
            count++;
        }

        // 反向
        for (let step = 1; step < 5; step++) {
            const nx = x - dx * step, ny = y - dy * step;
            if (nx < 0 || nx >= BOARD_SIZE || ny < 0 || ny >= BOARD_SIZE) break;
            if (chessData[nx][ny] !== player) break;
            count++;
        }

        if (count >= 5) return true;
    }
    return false;
}

6. 完整 HTML 整合

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>五子棋 - Canvas 版</title>
    <style>
        body { font-family: sans-serif; text-align: center; margin: 20px; }
        canvas { border: 1px solid #333; background: #f5deb3; cursor: crosshair; }
        #status { margin-top: 10px; font-size: 18px; font-weight: bold; }
        button { margin-top: 10px; padding: 8px 16px; font-size: 16px; }
    </style>
</head>
<body>
    <h1>五子棋對戰</h1>
    <div id="status">白棋先行</div>
    <canvas id="canvas" width="600" height="600">瀏覽器不支援 Canvas</canvas>
    <br>
    <button onclick="location.reload()">重新開始</button>

    <script>
        // 將上述所有 JS 程式碼放這裡
        // 最後綁定事件:
        document.getElementById('canvas').addEventListener('click', handleClick);
        drawBoard();
        initBoard();
    </script>
</body>
</html>

演算法複雜度分析

指標數值說明
時間複雜度O(1)每次落子固定掃描 4 方向 × 4 步 = 16 次檢查
空間複雜度O(1)固定 15×15 陣列 + 少量變數
檢查範圍每方向最多 4 格因為已有 1 顆,只需再找 4 顆湊滿 5

擴充功能建議

  • 悔棋:堆疊儲存 {x, y, player},pop 還原狀態
  • AI 對戰:Minimax + Alpha-Beta 剪枝 + 啟發式評估函數 (活三、眠四等)
  • 連線對戰:WebSocket + 伺服器權威邏輯,客戶端只負責渲染
  • 觸控支援:touchstart 事件座標轉換
  • 動畫落子:requestAnimationFrame 實現棋子下落動畫

總結

Canvas 五子棋核心在於:離散座標映射 (像素 → 格子)、二維陣列狀態機、四方向定長掃描勝負判定。本實作邏輯清晰、效能極佳、易於擴充,是學習 Canvas 遊戲開發的優秀入門專案。

copyright © 萬盛學電腦網 all rights reserved