【HTML 趣味五子棋】
五子棋游戏开发详解:一步步实现一个简单的HTML五子棋游戏

在这篇博客中,我们将详细讲解如何使用HTML、CSS和JavaScript实现一个简单的五子棋游戏。我们将逐步分析游戏的代码,并解释每一部分的功能。
1. 项目概述
我们的目标是开发一个简单的五子棋游戏,使用HTML来绘制棋盘,CSS来样式化游戏界面,使用JavaScript来实现游戏的逻辑。游戏包括以下主要功能:
- 玩家交替落子
- 胜利判断(五子连珠)
- 悔棋功能
- 游戏历史和排名系统
- 重新开始游戏按钮

我们将利用浏览器的 localStorage 存储玩家的历史成绩,展示在一个排行榜中。
2. HTML结构解析
var code = "a72db481-3d1e-4834-ae8c-6884856dfaf9"
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>五子棋游戏</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<div id="board"></div> <!-- 棋盘 -->
<div>
<img id="logo" src="wuziqi_Game_logo.png" alt="游戏 logo">
<div>
<button id="newGame">新游戏</button>
<button id="undo">悔棋</button>
</div>
<p id="currentPlayer">当前玩家: 黑棋</p>
<div id="rankings">
<h2>成绩排名</h2>
<table>
<thead>
<tr>
<th>排名</th>
<th>获胜者</th>
<th>总步数</th>
<th>获胜时间</th>
</tr>
</thead>
<tbody id="rankings-body">
</tbody>
</table>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
说明:
#board是棋盘区域,接下来我们会用JavaScript来动态填充这个区域。- 右侧是包含按钮、当前玩家显示、排名表格等内容的区域。
newGame按钮用于开始新的一局游戏,undo按钮用于悔棋。rankings显示排名,包括每个游戏的获胜者、步数、获胜时间等信息。
3. CSS样式解析
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
.container {
display: flex;
gap: 20px;
}
#board {
display: grid;
grid-template-columns: repeat(19, 30px);
grid-template-rows: repeat(19, 30px);
gap: 0;
border: 2px solid #333;
background-color: #d8b595;
}
.cell {
width: 30px;
height: 30px;
border: 1px solid #ccc;
box-sizing: border-box;
}
.black {
background-color: #000;
border-radius: 50%;
}
.white {
background-color: #fff;
border-radius: 50%;
border: 1px solid #ccc;
}
.highlight {
box-shadow: 0 0 10px 5px yellow;
z-index: 1;
}
button {
margin: 10px;
padding: 10px 20px;
}
#logo {
margin-bottom: 10px;
max-width: 300px;
}
#rankings {
margin-top: 20px;
}
#rankings table {
border-collapse: collapse;
}
#rankings th, #rankings td {
border: 1px solid #ccc;
padding: 5px 10px;
}
说明:
#board使用了 CSS Grid 来创建一个 19x19 的棋盘,每个格子是 30px。cell类为每个棋盘格子设置大小、边框等样式。black和white类分别表示黑棋和白棋,通过background-color和border-radius来实现圆形的棋子。highlight类用于高亮显示获胜的棋子格子。
4. JavaScript逻辑解析
4.1 初始化游戏状态
const board = document.getElementById('board');
const newGameButton = document.getElementById('newGame');
const undoButton = document.getElementById('undo');
const currentPlayerText = document.getElementById('currentPlayer');
const rankingsBody = document.getElementById('rankings-body');
const BOARD_SIZE = 19;
let gameBoard = Array.from({ length: BOARD_SIZE }, () => Array(BOARD_SIZE).fill(0)); // 0 表示空
let currentPlayer = 1; // 1 表示黑棋,2 表示白棋
let moveHistory = [];
let gameStartTime = null;
// 从 localStorage 获取排名数据
let rankings = JSON.parse(localStorage.getItem('rankings')) || [];
gameBoard是一个二维数组,用来表示棋盘状态。每个位置的值为 0 表示空位,1 表示黑棋,2 表示白棋。currentPlayer记录当前是哪个玩家的回合,1 为黑棋,2 为白棋。moveHistory用来存储每步棋的信息,以便实现悔棋功能。gameStartTime记录游戏开始的时间。
4.2 绘制棋盘
function drawBoard() {
board.innerHTML = '';
for (let i = 0; i < BOARD_SIZE; i++) {
for (let j = 0; j < BOARD_SIZE; j++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.dataset.row = i;
cell.dataset.col = j;
cell.addEventListener('click', handleCellClick);
board.appendChild(cell);
}
}
}
drawBoard函数通过document.createElement动态创建棋盘的每个格子,并将其添加到#board元素中。- 每个格子添加了一个
click事件监听器,用于处理玩家点击的事件。
4.3 处理玩家落子
function handleCellClick() {
if (gameStartTime === null) {
gameStartTime = new Date();
}
const row = parseInt(this.dataset.row);
const col = parseInt(this.dataset.col);
if (gameBoard[row][col] === 0) {
gameBoard[row][col] = currentPlayer;
moveHistory.push({ row, col, player: currentPlayer });
this.classList.add(currentPlayer === 1 ? 'black' : 'white');
if (checkWin(row, col, currentPlayer)) {
// 为最后落子的格子添加高亮样式
this.classList.add('highlight');
const gameEndTime = new Date();
const totalMoves = moveHistory.length;
const winner = currentPlayer === 1 ? '黑棋' : '白棋';
const winTime = gameEndTime - gameStartTime;
// 添加到排名系统
const newRank = { winner, totalMoves, winTime };
rankings.push(newRank);
localStorage.setItem('rankings', JSON.stringify(rankings));
rankings.sort((a, b) => a.totalMoves - b.totalMoves);
rankingsBody.innerHTML = '';
const top8Rankings = rankings.slice(0, 8);
top8Rankings.forEach((rank, index) => {
const newRow = document.createElement('tr');
const rankCell = document.createElement('td');
const winnerCell = document.createElement('td');
const movesCell = document.createElement('td');
const timeCell = document.createElement('td');
rankCell.textContent = index + 1;
winnerCell.textContent = rank.winner;
movesCell.textContent = rank.totalMoves;
timeCell.textContent = `${(rank.winTime / 1000).toFixed(2)} 秒`;
newRow.appendChild(rankCell);
newRow.appendChild(winnerCell);
newRow.appendChild(movesCell);
newRow.appendChild(timeCell);
rankingsBody.appendChild(newRow);
});
setTimeout(() => {
alert(`${winner} 获胜!总步数: ${totalMoves},获胜时间: ${(winTime / 1000).toFixed(2)} 秒`);
resetGame();
}, 100); // 延迟显示获胜弹窗
} else if (isBoardFull()) {
alert('平局!');
resetGame();
} else {
currentPlayer = currentPlayer === 1 ? 2 : 1;
currentPlayerText.textContent = `当前玩家: ${currentPlayer === 1 ? '黑棋' : '白棋'}`;
}
}
}
- 玩家点击棋盘的一个格子时,会检查该位置是否为空。如果为空,则当前玩家在该位置落子。
- 如果落子后形成五子连珠,判断玩家胜利,并更新排名。
- 每当游戏结束时,记录当前的游戏信息,并存储到
localStorage中。
4.4 悔棋功能
function undoMove() {
if (moveHistory.length > 0) {
const lastMove = moveHistory.pop();
gameBoard[lastMove.row][lastMove.col] = 0;
const cell = document.querySelector(`[data-row="${lastMove.row}"][data-col="${lastMove.col}"]`);
cell.classList.remove('black', 'white', 'highlight');
currentPlayer = lastMove.player !== 1 ? 2 : 1;
currentPlayerText.textContent = `当前玩家: ${currentPlayer === 1 ? '黑棋' : '白棋'}`;
if (moveHistory.length === 0) {
gameStartTime = null;
}
}
}
undoMove函数实现了悔棋功能,每当玩家点击悔棋按钮时,撤销最后一步落子,并恢复之前的游戏状态。
5. 总结
通过这篇博客的讲解,我们实现了一个简单但功能完善的五子棋游戏。使用HTML、CSS和JavaScript,我们完成了棋盘的绘制、玩家交替落子、胜利判定、悔棋、成绩排名等功能。通过 localStorage 保存了玩家的历史成绩并显示在排行榜中。

浙公网安备 33010602011771号