Vue的扫雷实现
Vue 扫雷实现步骤
准备工作
确保已安装 Vue CLI 或通过 CDN 引入 Vue。创建一个 Vue 项目或单文件组件,初始化游戏所需的数据结构(如雷区矩阵、雷数量、游戏状态等)。
数据结构设计
使用二维数组表示雷区,每个格子包含属性:isMine(是否为雷)、revealed(是否揭开)、flagged(是否标记)、adjacentMines(周围雷数)。例如:
data() {
return {
grid: Array(10).fill().map(() =>
Array(10).fill().map(() => ({
isMine: false,
revealed: false,
flagged: false,
adjacentMines: 0
}))
),
mineCount: 15,
gameOver: false
};
}
初始化雷区
随机布置雷并计算周围雷数。通过双重循环和随机数生成雷的位置,避免重复。初始化后遍历非雷格子,统计周围8个方向的雷数:

methods: {
initGrid() {
// 布置雷
let minesPlaced = 0;
while (minesPlaced < this.mineCount) {
const x = Math.floor(Math.random() * 10);
const y = Math.floor(Math.random() * 10);
if (!this.grid[x][y].isMine) {
this.grid[x][y].isMine = true;
minesPlaced++;
}
}
// 计算周围雷数
for (let x = 0; x < 10; x++) {
for (let y = 0; y < 10; y++) {
if (!this.grid[x][y].isMine) {
this.grid[x][y].adjacentMines = this.countAdjacentMines(x, y);
}
}
}
},
countAdjacentMines(x, y) {
let count = 0;
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
const nx = x + dx, ny = y + dy;
if (nx >= 0 && nx < 10 && ny >= 0 && ny < 10 && this.grid[nx][ny].isMine) {
count++;
}
}
}
return count;
}
}
游戏交互逻辑
实现左键揭开格子和右键标记功能。揭开时递归处理空白区域(类似 Flood Fill 算法),遇到雷则结束游戏:
methods: {
revealCell(x, y) {
if (this.gameOver || this.grid[x][y].revealed || this.grid[x][y].flagged) return;
this.grid[x][y].revealed = true;
if (this.grid[x][y].isMine) {
this.gameOver = true;
alert('游戏结束');
return;
}
if (this.grid[x][y].adjacentMines === 0) {
this.revealAdjacentCells(x, y); // 递归揭开周围空白格子
}
},
toggleFlag(x, y) {
if (!this.grid[x][y].revealed) {
this.grid[x][y].flagged = !this.grid[x][y].flagged;
}
}
}
界面渲染
使用 v-for 渲染雷区,绑定点击事件和右键事件。根据格子状态显示不同内容(数字、雷、旗帜):

<template>
<div class="grid">
<div v-for="(row, x) in grid" :key="x" class="row">
<div
v-for="(cell, y) in row"
:key="y"
class="cell"
:class="{ revealed: cell.revealed, mine: cell.isMine && cell.revealed }"
@click="revealCell(x, y)"
@contextmenu.prevent="toggleFlag(x, y)"
>
<span v-if="cell.revealed">
{{ cell.isMine ? '💣' : cell.adjacentMines || '' }}
</span>
<span v-else-if="cell.flagged">🚩</span>
</div>
</div>
</div>
</template>
样式设计
添加基础样式控制格子外观和游戏状态反馈。例如:
.grid {
display: inline-block;
border: 2px solid #333;
}
.row {
display: flex;
}
.cell {
width: 30px;
height: 30px;
border: 1px solid #ccc;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
background-color: #eee;
}
.cell.revealed {
background-color: #fff;
}
.cell.mine {
background-color: #f00;
}
游戏状态检查
添加胜利条件判断(所有非雷格子被揭开):
methods: {
checkWin() {
return this.grid.every(row =>
row.every(cell =>
cell.revealed || cell.isMine
)
);
}
}
在 revealCell 方法中调用此方法,若返回 true 则触发胜利逻辑。






