vue数字华容道九宫格
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/vue/3.2.31/vue.global.min.js"></script>
<title>Document</title>
</head>
<style>
.box {
border: 5px solid rgb(218, 195, 147);
display: flex;
flex-wrap: wrap;
background-color: black;
}
.item {
width: 100px;
height: 100px;
background-color: rgb(247, 170, 3);
border: 1px solid rgb(189, 133, 12);
color: white;
text-align: center;
line-height: 100px;
font-size: 20px;
cursor: pointer;
user-select: none;
position: relative;
left: 0;
}
.empty {
background-color: black;
}
</style>
<body>
<div id="app">
<div class="box" :style="{width,height}">
<div class="item" :class="{'empty':item == -1}" v-for="(item, index) in list" @click="onSwitch(item,index)"
ref="item">
{{item != -1?item:''}}</div>
</div>
<input type="text" :value="col" ref="input">阶华容道
<button @click="setCol">设置</button>
</div>
<script>
const { createApp } = Vue
createApp({
data() {
return {
list: [],
answerList: [],
col: 3,
width: "",
height: "",
}
},
mounted() {
this.reset();
},
methods: {
setCol() {
this.col = this.$refs.input.value;
this.reset();
},
reset() {
this.list = [];
const maxCount = this.col * this.col;
this.width = (102 * this.col) + 'px';
this.height = (102 * this.col) + 'px';
for (let i = 0; i < maxCount; i++) {
this.list.push(i == maxCount - 1 ? -1 : i + 1)
}
this.answerList = JSON.parse(JSON.stringify(this.list)); //备份一份答案
this.list = this.list.sort(() => 0.5 - Math.random());
},
onSwitch(item, index) {
if (item != -1) {
const lastItem = (index) % this.col + 1; //是否右边最后一个
const eIdx = this.list.findIndex(d => d == -1);//空闲的位置
if (lastItem != this.col || (lastItem == this.col && this.list != -1)) {//判断当前格如果不是右边最后一格或者当前当前格是最后一格并且下一格不是空格
if (this.list == -1 || this.list == -1) { //如果左边或者右边有空位
, this.list] = , this.list];
}
}
if (this.list == -1) {//当前格子上面有格子
, this.list] = , this.list];
}
if (this.list == -1) {//当前格子下面有格子
, this.list] = , this.list];
}
if (this.list.toString() == this.answerList.toString()) {
setTimeout(() => {
alert("恭喜,通关了");
this.reset();
}, 1000);
}
}
}
},
}).mount('#app')
</script>
</body>
</html>
页:
[1]