使用vue写扫雷游戏

2023-07-11,,

上班闲来没事做,,心血来潮。想用刚学的vue,写一个扫雷游戏。。好了,直入正题.


第一步,先制作一个10x10的格子图。。这个divcss就不说了。。大家都会。

第二步,制造一个数组,用来生成随机雷区。

let arr = []
for (var i = 0; i < 10; i++) {
arr.push(Math.floor(Math.random() * 100))
}

第三步,制造一个json数组,让他循环生成页面上的格子。

  let arrs = []
for (var j = 0; j < 100; j++) {
let obj = {}
if (arr.indexOf(j) > -1) {
obj.isLei = true // 是否是地雷
} else {
obj.isLei = false // 是否是地雷
}
obj.id = j
obj.isTrue = false // 安全区样式
obj.isFalse = false // 雷区样式
arrs.push(obj)
}

大概是这样子的数据

第四步,点击格子,触发事件。判断是否这个是雷区。如果安全就显示绿色,否则显示红色。

toclick (e) {
console.log(e.isTrue)
if (e.isLei === true) {
e.isFalse = true
} else {
e.isTrue = true
this.surPlus = this.surPlus - 1
}
}

以下是所有代码:

<script>
export default{
data () {
return {
lattice: null, // 100个格子
surPlus: 90 // 安全区。。因为是10个雷。所以就是100-10 = 90
}
},
methods: {
toclick (e) {
console.log(e.isTrue)
if (e.isLei === true) {
e.isFalse = true
} else {
e.isTrue = true
this.surPlus = this.surPlus - 1
}
},
random () {
let arr = []
for (var i = 0; i < 10; i++) {
arr.push(Math.floor(Math.random() * 100))
}
let arrs = []
for (var j = 0; j < 100; j++) {
let obj = {}
if (arr.indexOf(j) > -1) {
obj.isLei = true // 是否是地雷
} else {
obj.isLei = false // 是否是地雷
}
obj.id = j
obj.isTrue = false // 安全区样式
obj.isFalse = false // 雷区样式
arrs.push(obj)
}
this.lattice = arrs
console.log(arrs)
}
},
mounted () {
this.random()
}
}
</script>
<template>
<div class="page">
<div class="bg">
<div v-for="item in lattice" class="lattice" :class="{ 'security' : item.isTrue , 'danger': item.isFalse }" :key="item.id" @click="toclick(item)"></div>
</div>
<div class="surplus">剩余{{surPlus}}个安全格子</div>
</div>
</template>
<style scoped>
.page{
overflow: hidden;
}
.bg{
border:1px solid #000;
width:600px;
height:600px;
margin:20px auto;
}
.lattice{
border: 1px solid #ccc;
box-sizing: border-box;
float:left;
width:60px;
height:60px;
}
.surplus{
line-height: 38px;
height:38px;
width:150px;
margin:0 auto;
}
.security{
background-color: green;
}
.danger{
background-color: red;
}
</style>

最后样子大概就是这样:

使用vue写扫雷游戏的相关教程结束。

《使用vue写扫雷游戏.doc》

下载本文的Word格式文档,以方便收藏与打印。