// 画棋盘
for (let i = 0; i < 15; i++) {
ctx.beginPath();
ctx.moveTo(15 + i * 30, 15);
ctx.lineTo(15 + i * 30, 435);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(15, 15 + i * 30);
ctx.lineTo(435, 15 + i * 30);
ctx.stroke();
}
canvas.addEventListener('click', (e) = {
const x = Math.round((e.clientX canvas.offsetLeft 15) / 30);
const y = Math.round((e.clientY canvas.offsetTop 15) / 30);
if (board[x][y] === null) {
drawPiece(x, y, currentPlayer);
board[x][y] = currentPlayer;
if (checkWin(x, y, currentPlayer)) {
alert(`${currentPlayer} wins!`);
return;
}
currentPlayer = currentPlayer === 'black' ? 'white' : 'black';
// 简单AI(随机落子)
if (currentPlayer === 'white') {
let aiX, aiY;
do {
aiX = Math.floor(Math.random() * 15);
aiY = Math.floor(Math.random() * 15);
} while (board[aiX][aiY] !== null);
drawPiece(aiX, aiY, 'white');
board[aiX][aiY] = 'white';
if (checkWin(aiX, aiY, 'white')) {
alert('white wins!');
}
currentPlayer = 'black';
}
}
});
function drawPiece(x, y, color) {
ctx.beginPath();
ctx.arc(15 + x * 30, 15 + y * 30, 13, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
}
function checkWin(x, y, color) {
// 简单的胜负判断逻辑
// 这里只实现了水平方向的检查,实际需要检查所有方向
let count = 0;
for (let i = x 4; i <= x + 4; i++) {
if (i = 0 && i < 15 && board[i][y] === color) {
count++;
if (count === 5) return true;
} else {
count = 0;
}
}
return false;
}