网站首页 > 技术文章 正文
完整代码如下,大家可以保存到html文件点击打开,就可以看到如上效果
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>五子棋游戏</title>
<style>
body {
font-family: 'Microsoft YaHei', sans-serif;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f5f5dc;
margin: 0;
padding: 20px;
}
h1 {
color: #8B4513;
text-shadow: 1px 1px 2px rgba(0,0,0,0.2);
}
#game-container {
position: relative;
margin: 20px 0;
}
#chess-board {
background-color: #DEB887;
border: 2px solid #8B4513;
box-shadow: 0 0 10px rgba(0,0,0,0.3);
}
#status {
margin: 10px 0;
font-size: 18px;
font-weight: bold;
color: #8B4513;
height: 24px;
}
#controls {
margin-top: 10px;
}
button {
background-color: #8B4513;
color: white;
border: none;
padding: 8px 15px;
margin: 0 5px;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s;
}
button:hover {
background-color: #A0522D;
}
.piece {
position: absolute;
border-radius: 50%;
pointer-events: none;
}
.black {
background: radial-gradient(circle at 30% 30%, #666, #000);
box-shadow: 1px 1px 2px rgba(0,0,0,0.7);
}
.white {
background: radial-gradient(circle at 30% 30%, #fff, #ccc);
box-shadow: 1px 1px 2px rgba(0,0,0,0.5);
}
.last-move {
box-shadow: 0 0 5px 3px rgba(255, 215, 0, 0.7);
}
</style>
</head>
<body>
<h1>五子棋游戏</h1>
<div id="status">黑方回合</div>
<div id="game-container">
<canvas id="chess-board" width="450" height="450"></canvas>
</div>
<div id="controls">
<button id="restart">重新开始</button>
<button id="undo">悔棋</button>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const canvas = document.getElementById('chess-board');
const ctx = canvas.getContext('2d');
const statusDisplay = document.getElementById('status');
const restartBtn = document.getElementById('restart');
const undoBtn = document.getElementById('undo');
const BOARD_SIZE = 15;
const CELL_SIZE = canvas.width / (BOARD_SIZE + 1);
const PIECE_RADIUS = CELL_SIZE * 0.4;
let board = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(0));
let currentPlayer = 1; // 1: 黑棋, 2: 白棋
let gameOver = false;
let moveHistory = [];
let lastMove = null;
// 初始化棋盘
function initBoard() {
// 清空棋盘
board = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(0));
currentPlayer = 1;
gameOver = false;
moveHistory = [];
lastMove = null;
statusDisplay.textContent = '黑方回合';
// 清除所有棋子DOM元素
document.querySelectorAll('.piece').forEach(el => el.remove());
// 绘制棋盘
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#DEB887';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制网格线
ctx.strokeStyle = '#000';
ctx.lineWidth = 1;
for (let i = 0; i < BOARD_SIZE; i++) {
// 横线
ctx.beginPath();
ctx.moveTo(CELL_SIZE, CELL_SIZE * (i + 1));
ctx.lineTo(CELL_SIZE * BOARD_SIZE, CELL_SIZE * (i + 1));
ctx.stroke();
// 竖线
ctx.beginPath();
ctx.moveTo(CELL_SIZE * (i + 1), CELL_SIZE);
ctx.lineTo(CELL_SIZE * (i + 1), CELL_SIZE * BOARD_SIZE);
ctx.stroke();
}
// 绘制五个黑点
const dots = [
[3, 3], [3, 11], [7, 7], [11, 3], [11, 11]
];
ctx.fillStyle = '#000';
dots.forEach(([x, y]) => {
ctx.beginPath();
ctx.arc(
CELL_SIZE * (x + 1),
CELL_SIZE * (y + 1),
CELL_SIZE * 0.1,
0,
Math.PI * 2
);
ctx.fill();
});
}
// 放置棋子
function placePiece(x, y) {
if (gameOver || board[x][y] !== 0) return false;
board[x][y] = currentPlayer;
moveHistory.push({x, y, player: currentPlayer});
lastMove = {x, y};
// 创建棋子DOM元素
const piece = document.createElement('div');
piece.className = `piece ${currentPlayer === 1 ? 'black' : 'white'}`;
if (lastMove && lastMove.x === x && lastMove.y === y) {
piece.classList.add('last-move');
}
piece.style.width = `${PIECE_RADIUS * 2}px`;
piece.style.height = `${PIECE_RADIUS * 2}px`;
piece.style.left = `${CELL_SIZE * (x + 1) - PIECE_RADIUS}px`;
piece.style.top = `${CELL_SIZE * (y + 1) - PIECE_RADIUS}px`;
document.getElementById('game-container').appendChild(piece);
// 检查胜利
if (checkWin(x, y)) {
gameOver = true;
statusDisplay.textContent = `${currentPlayer === 1 ? '黑方' : '白方'}获胜!`;
return true;
}
// 切换玩家
currentPlayer = currentPlayer === 1 ? 2 : 1;
statusDisplay.textContent = `${currentPlayer === 1 ? '黑方' : '白方'}回合`;
return true;
}
// 检查是否获胜
function checkWin(x, y) {
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 nx = x + dx * i;
const ny = y + dy * i;
if (nx < 0 || nx >= BOARD_SIZE || ny < 0 || ny >= BOARD_SIZE || board[nx][ny] !== currentPlayer) {
break;
}
count++;
}
// 反向检查
for (let i = 1; i < 5; i++) {
const nx = x - dx * i;
const ny = y - dy * i;
if (nx < 0 || nx >= BOARD_SIZE || ny < 0 || ny >= BOARD_SIZE || board[nx][ny] !== currentPlayer) {
break;
}
count++;
}
if (count >= 5) return true;
}
return false;
}
// 悔棋
function undoMove() {
if (gameOver || moveHistory.length === 0) return;
const lastMove = moveHistory.pop();
board[lastMove.x][lastMove.y] = 0;
currentPlayer = lastMove.player;
// 移除最后一个棋子DOM
const pieces = document.querySelectorAll('.piece');
if (pieces.length > 0) {
pieces[pieces.length - 1].remove();
}
// 如果有上一个棋子,添加高亮
if (moveHistory.length > 0) {
const prevMove = moveHistory[moveHistory.length - 1];
const prevPieces = document.querySelectorAll('.piece');
prevPieces.forEach(p => p.classList.remove('last-move'));
for (let i = 0; i < prevPieces.length; i++) {
const piece = prevPieces[i];
const pieceX = Math.round((parseInt(piece.style.left) + PIECE_RADIUS) / CELL_SIZE) - 1;
const pieceY = Math.round((parseInt(piece.style.top) + PIECE_RADIUS) / CELL_SIZE) - 1;
if (pieceX === prevMove.x && pieceY === prevMove.y) {
piece.classList.add('last-move');
break;
}
}
}
statusDisplay.textContent = `${currentPlayer === 1 ? '黑方' : '白方'}回合`;
}
// 点击事件处理
canvas.addEventListener('click', function(e) {
if (gameOver) return;
const rect = canvas.getBoundingClientRect();
const x = Math.round((e.clientX - rect.left) / CELL_SIZE) - 1;
const y = Math.round((e.clientY - rect.top) / CELL_SIZE) - 1;
if (x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE) {
placePiece(x, y);
}
});
// 按钮事件
restartBtn.addEventListener('click', initBoard);
undoBtn.addEventListener('click', undoMove);
// 初始化游戏
initBoard();
});
</script>
</body>
</html>
猜你喜欢
- 2025-05-11 CSS:前端必会的flex布局,我把布局代码全部展示出来了
- 2025-05-11 Moti:React Native 动画库的新标杆
- 2025-05-11 前端开发避坑指南:每天都能用的 CSS3/Less/Sass 实战技巧
- 2025-05-11 HarmonyOS:ArkTS 多态样式自学指南
- 2025-05-11 5 分钟快速上手图形验证码,防止接口被恶意刷量!
- 2025-05-11 告别长文焦虑!AI帮你“秒划重点”,文章秒变知识卡片
- 2025-05-11 鸿蒙NEXT小游戏开发:数字华容道
- 2025-05-11 Flex 布局 vs 颈椎排列:如何拯救你的 “代码脖”?
- 2025-05-11 一文搞懂flex(弹性盒布局)
- 2024-07-23 Flex 布局教程:实例篇(flex布局教程实例篇 双项目)
- 05-11CSS:前端必会的flex布局,我把布局代码全部展示出来了
- 05-11Moti:React Native 动画库的新标杆
- 05-11前端开发避坑指南:每天都能用的 CSS3/Less/Sass 实战技巧
- 05-11HarmonyOS:ArkTS 多态样式自学指南
- 05-115 分钟快速上手图形验证码,防止接口被恶意刷量!
- 05-11网页五指棋游戏
- 05-11告别长文焦虑!AI帮你“秒划重点”,文章秒变知识卡片
- 05-11鸿蒙NEXT小游戏开发:数字华容道
- 最近发表
- 标签列表
-
- cmd/c (64)
- c++中::是什么意思 (83)
- 标签用于 (65)
- 主键只能有一个吗 (66)
- c#console.writeline不显示 (75)
- pythoncase语句 (81)
- es6includes (73)
- sqlset (64)
- windowsscripthost (67)
- apt-getinstall-y (86)
- node_modules怎么生成 (76)
- chromepost (65)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- & (66)
- java (73)
- org.redisson (64)
- js数组插入 (83)
- gormwherein (64)
- linux删除一个文件夹 (65)
- mac安装java (72)
- outofmemoryerror是什么意思 (64)
- eacces (67)
- 查看mysql是否启动 (70)
- 无效的列索引 (74)