五子棋游戏:JavaScript实现及棋盘设计
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>五子棋游戏</title>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>
<script>
// 定义二维数组board,用于存储棋子的位置信息,初始化为全0表示未落子的状态
const board = [];
for (let i = 0; i < 15; i++) {
board[i] = [];
for (let j = 0; j < 15; j++) {
board[i][j] = 0;
}
}
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let isBlack = true;
function drawBoard() {
for (let i = 0; i < 15; i++) {
ctx.moveTo(20 + i * 40, 20);
ctx.lineTo(20 + i * 40, 580);
ctx.stroke();
ctx.moveTo(20, 20 + i * 40);
ctx.lineTo(580, 20 + i * 40);
ctx.stroke();
}
}
drawBoard()
function drawPiece(x, y, isBlack) {
ctx.beginPath();
ctx.arc(20 + x * 40, 20 + y * 40, 18, 0, 2 * Math.PI);
ctx.closePath();
const gradient = ctx.createRadialGradient(20 + x * 40 + 2, 20 + y * 40 - 2, 18, 20 + x * 40 + 2, 20 + y * 40 - 2, 0);
if (isBlack) {
gradient.addColorStop(0, '#0a0a0a');
gradient.addColorStop(1, '#636766');
} else {
gradient.addColorStop(0, '#d1d1d1');
gradient.addColorStop(1, '#f9f9f9');
}
ctx.fillStyle = gradient;
ctx.fill();
}
function checkWin(x, y, isBlack) {
const color = isBlack ? 1 : 2;
let count = 1;
let i = 1;
while (x + i < 15 && board[x + i][y] === color) {
count++;
i++;
}
i = 1;
while (x - i >= 0 && board[x - i][y] === color) {
count++;
i++;
}
if (count >= 5) {
return true;
}
count = 1;
i = 1;
while (y + i < 15 && board[x][y + i] === color) {
count++;
i++;
}
i = 1;
while (y - i >= 0 && board[x][y - i] === color) {
count++;
i++;
}
if (count >= 5) {
return true;
}
count = 1;
i = 1;
while (x + i < 15 && y + i < 15 && board[x + i][y + i] === color) {
count++;
i++;
}
i = 1;
while (x - i >= 0 && y - i >= 0 && board[x - i][y - i] === color) {
count++;
i++;
}
if (count >= 5) {
return true;
}
count = 1;
i = 1;
while (x + i < 15 && y - i >= 0 && board[x + i][y - i] === color) {
count++;
i++;
}
i = 1;
while (x - i >= 0 && y + i < 15 && board[x - i][y + i] === color) {
count++;
i++;
}
if (count >= 5) {
return true;
}
return false;
}
canvas.addEventListener('click', function (e) {
const x = Math.floor((e.clientX - canvas.offsetLeft) / 40);
const y = Math.floor((e.clientY - canvas.offsetTop) / 40);
if (board[x][y] === 0) {
drawPiece(x, y, isBlack);
board[x][y] = isBlack ? 1 : 2;
if (checkWin(x, y, isBlack)) {
alert(isBlack ? '黑方胜利!' : '白方胜利!');
return;
}
isBlack = !isBlack;
}
});
</script>
</body>
<p></htm</p>
原文地址: https://www.cveoy.top/t/topic/m7pa 著作权归作者所有。请勿转载和采集!