用VUE.js写一个扫雷游戏
时间: 2023-12-18 08:06:01 浏览: 66
好的,下面是一个基于 Vue.js 的简单扫雷游戏实现:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue.js 扫雷游戏</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="./minesweeper.js"></script>
</head>
<body>
<div id="app">
<h1>Vue.js 扫雷游戏</h1>
<table>
<tbody>
<tr v-for="(row, rowIndex) in board" :key="rowIndex">
<td v-for="(cell, colIndex) in row" :key="colIndex"
@click="clickCell(rowIndex, colIndex)"
:class="{ 'cell': true, 'revealed': cell.revealed, 'mine': cell.mine }">
{{ cell.content }}
</td>
</tr>
</tbody>
</table>
<div v-if="gameOver">
<p>游戏结束!</p>
<button @click="restart">重新开始</button>
</div>
<div v-else>
<p>剩余雷数:{{ minesLeft }}</p>
<button @click="restart">重新开始</button>
</div>
</div>
</body>
</html>
```
JavaScript 代码(minesweeper.js):
```javascript
// 初始化游戏棋盘
function initBoard(row, col, numMines) {
const board = [];
for (let i = 0; i < row; i++) {
board.push([]);
for (let j = 0; j < col; j++) {
board[i].push({
content: '',
revealed: false,
mine: false
});
}
}
// 添加地雷
let count = 0;
while (count < numMines) {
const i = Math.floor(Math.random() * row);
const j = Math.floor(Math.random() * col);
if (!board[i][j].mine) {
board[i][j].mine = true;
count++;
// 更新其它方格的数字
for (let r = Math.max(0, i - 1); r <= Math.min(row - 1, i + 1); r++) {
for (let c = Math.max(0, j - 1); c <= Math.min(col - 1, j + 1); c++) {
if (r !== i || c !== j) {
board[r][c].content += 1;
}
}
}
}
}
return board;
}
// Vue.js 实例
const app = new Vue({
el: '#app',
data: {
row: 10,
col: 10,
numMines: 10,
board: [],
minesLeft: 0,
gameOver: false
},
methods: {
clickCell(row, col) {
const cell = this.board[row][col];
if (!cell.revealed) {
cell.revealed = true;
if (cell.mine) {
this.gameOver = true;
} else if (cell.content === '') {
// 递归展开周围的空白方格
for (let r = Math.max(0, row - 1); r <= Math.min(this.row - 1, row + 1); r++) {
for (let c = Math.max(0, col - 1); c <= Math.min(this.col - 1, col + 1); c++) {
if (r !== row || c !== col) {
this.clickCell(r, c);
}
}
}
}
}
// 检查游戏是否结束
this.gameOver = this.board.some(row => row.some(cell => cell.mine && cell.revealed));
},
restart() {
this.board = initBoard(this.row, this.col, this.numMines);
this.minesLeft = this.numMines;
this.gameOver = false;
this.board.forEach(row => row.forEach(cell => cell.revealed = false));
}
},
created() {
this.board = initBoard(this.row, this.col, this.numMines);
this.minesLeft = this.numMines;
},
computed: {
minesLeft() {
return this.numMines - this.board.reduce((count, row) => {
return count + row.filter(cell => cell.revealed && cell.mine).length;
}, 0);
}
}
});
```
在浏览器中打开 HTML 文件,即可开始游戏。
阅读全文