chessData[x][y],0=空、1=白、2=黑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';
function initBoard() {
chessData = Array.from({ length: BOARD_SIZE }, () => Array(BOARD_SIZE).fill(EMPTY));
}
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();
}));
}
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);
}
/**
* 從 (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;
}
<!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 還原狀態touchstart 事件座標轉換requestAnimationFrame 實現棋子下落動畫Canvas 五子棋核心在於:離散座標映射 (像素 → 格子)、二維陣列狀態機、四方向定長掃描勝負判定。本實作邏輯清晰、效能極佳、易於擴充,是學習 Canvas 遊戲開發的優秀入門專案。