网站首页 > 基础教程 正文
完整代码如下,大家可以保存到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-27 是时候使用iframe延迟加载来提升LCP!
- 2025-05-27 页面卡顿到崩溃?5 个实战技巧让前端性能飙升 80%!
- 2025-05-27 前端人必看!10 个实战优化技巧,让项目性能直接起飞!
- 2025-05-27 快速了解JavaScript的表单操作
- 2025-05-27 来了!JavaScript 最强大的 8 个 DOM API
- 2025-05-27 如何使用 ChatGPT 进行抓取
- 2025-05-27 Pyppeteer爬虫神器详解
- 2025-05-27 《高性能JavaScript》学习笔记——日更中
- 2025-05-27 性能狂飙!5 各前端优化奇招,让页面加载速度提升 300%?
- 2025-05-27 前端页面中,如何让用户回到上次阅读的位置?
- 最近发表
-
- 在使用Bootstrap吗?快来看看如何使用 Bootswatch 主题吧
- 50个HTML5免费的Bootstrap模板 :下
- 定制你的bootstrap之--修改less文件1
- BootstrapBlazor :使用 .NET 生成交互式客户端 Web UI 的框架
- React与使用Bootstrap5模态框的注意事项
- 如何引用bootstrap没有的字体图标
- 10个超酷炫Bootstrap HTML & CSS UI工具包
- Bootstrap自举电路工作原理讲解(自举电路的原理)
- 为何 BootstrapVue 能成为 Vue 前端框架顶流?
- 新增 创意布局企业网络服务CSS模板 bootstrap 模板
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- deletesql (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)