<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>八皇后</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>
<style>
.grid {
width: 400px;
margin: 0 auto;
}
.cell {
width: 50px;
height: 50px;
line-height: 50px;
background: #999;
float: left;
cursor: pointer;
text-align: center;
font-weight: bold;
}
.cell:nth-child(2n) {
background: #efefef;
}
.row {
height: 50px;
width: 400px;
display: flow-root;
}
.row:nth-child(2n) .cell:nth-child(2n){
background: #999;
}
.row:nth-child(2n) .cell:nth-child(2n-1){
background: #efefef;
}
</style>
</head>
<body>
<div id="app">
<!-- 表格 -->
<div class="grid">
<!-- 行 -->
<div class="row" v-for='(row,rindex) in grids' :key="rindex">
<!-- 格子 -->
<div class="cell"
v-for='(cell,cindex) in row'
:key='cindex'
@click.stop='choose(rindex,cindex)'
>
<div v-if='cell.ok'>Q</div>
</div>
</div>
</div>
</div>
<script>
new Vue({
el:"#app",
data:{
//表格
grids:new Array(8).fill(1).map(()=>new Array(8).fill(1).map(()=>({ok:false})))
},
methods:{
//点击格子
choose(rindex,cindex){
if (this.grids[rindex][cindex].ok) {
this.grids[rindex][cindex].ok=false
} else if (this.validate(rindex,cindex)) {
this.grids[rindex][cindex].ok=true
} else {
alert("当前位置不能放置皇后");
}
},
//判断位置能否放置
validate(rindex, cindex) {
// 横
for (let i=0;i<this.grids[rindex].length;i++) {
if (this.grids[rindex][i].ok) return false
}
// 竖
for (let i=0;i<this.grids.length; i++) {
if (this.grids[i][cindex].ok) return false
}
// 撇
for (let i=0;i<this.grids[0].length;i++) {
let y=rindex+cindex-i
if (y>=0&&y<this.grids.length&&this.grids[y][i].ok) return false
}
// 捺
for (let i=0;i<this.grids[0].length;i++) {
let y=rindex-cindex+i
if (y>=0&&y<this.grids.length&&this.grids[y][i].ok) return false
}
return true
}
}
})
</script>
</body>
</html>
八皇后 - vue实现
最新推荐文章于 2024-09-13 14:34:15 发布
本文通过Vue.js展示了八皇后问题的实现,提供了演示地址供读者参考。
摘要由CSDN通过智能技术生成