<template>
<div id="app">
<h1>扫雷游戏</h1>123</s>
<div id="minefield">
<button
v-for="(tile, index) in tiles"
:key="index"
:data-mine="tile.isMine"
:disabled="tile.isRevealed"
@click="revealTile(index)"
>
{{ tile.adjacentMines }}
</button>
</div>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
tiles: [],
};
},
methods: {
// 初始化游戏
initGame() {
const numberOfTiles = 100;
const numberOfMines = 10;
this.tiles = Array.from({ length: numberOfTiles }, (_, i) => ({
id: i,
isRevealed: false,
isMine: false,
adjacentMines: 0,
}));
this.placeMines(numberOfMines);
this.calculateAdjacentMines();
},
// 布置雷
placeMines(count) {
for (let i = 0; i < count; ) {
const index = Math.floor(Math.random() * this.tiles.length);
if (!this.tiles[index].isMine) {
this.tiles[index].isMine = true;
i++;
}
}
},
// 计算每个格子周围雷的数量
calculateAdjacentMines() {
this.tiles.forEach((tile) => {
if (!tile.isMine) {
const adjacentTiles = this.getAdjacentTiles(tile.id);
tile.adjacentMines = adjacentTiles.filter((t) => t.isMine).length;
}
});
},
// 获取一个格子周围的其他格子
getAdjacentTiles(tileId) {
const tileIndex = tileId;
const tileRow = Math.floor(tileIndex / 10);
const tileColumn = tileIndex % 10;
return [
this.tiles[tileIndex - 11], // Top-left
this.tiles[tileIndex - 10], // Top-middle
this.tiles[tileIndex - 9], // Top-right
this.tiles[tileIndex - 1], // Left
this.tiles[tileIndex + 1], // Right
this.tiles[tileIndex + 9], // Bottom-left
this.tiles[tileIndex + 10], // Bottom-middle
this.tiles[tileIndex + 11], // Bottom-right
].filter((t) => t); // Ensure tiles are within the bounds of the array
},
// 显示格子
revealTile(tileId) {
const tile = this.tiles[tileId];
if (!tile.isRevealed && !tile.isMine) {
评论已关闭