八皇后 - vue实现

本文通过Vue.js展示了八皇后问题的实现,提供了演示地址供读者参考。
摘要由CSDN通过智能技术生成

演示地址

<!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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值