经典小游戏js点灯游戏

首先先来看看点灯游戏的实现逻辑

首先是十六个灯笼默认全部熄灭,点击之后灯笼上下左右同时点亮,点击旁边的灯笼同样会影响周围的灯笼

 点击效果

 使用二维数组来遍历出灯笼的行和列 

  var m = 4;
	var n = 4;
	var boxs = []
	for (var i = 0; i < m; i++) {
		boxs[i] = []
		for (var j = 0; j < n; j++) {
			boxs[i][j] = creatBox(i,j);
            boxs[i][j].style.top = i*40+"px"
            boxs[i][j].style.left = j*40+"px"
            boxdiv.appendChild(boxs[i][j])
		}
        
	}

在声明一个方法接收,使用工厂模式制造出灯笼,通过二维数组的矩阵模式,点击改变元素状态取反,来改变灯笼的上下左右

function creatBox(i,j) {
        let box = document.createElement("img")
        box.i = i
        box.j = j
        box.state = true
        box.src = "./img/an.png"
        box.className = "deng"
        box.onclick = function() {
            // 自己的状态取反
            this.state = !this.state
            if (this.state) {
                this.src = "./img/an.png"
            } else {
                this.src = "./img/liang.png"
            }
            // 控制四周的灯
            if(i>0){
				boxs[this.i-1][this.j].state = !boxs[this.i-1][this.j].state;
				if(boxs[this.i-1][this.j].state){
					boxs[this.i-1][this.j].src = "./img/an.png"
				}else{
					boxs[this.i-1][this.j].src = "./img/liang.png"
				}
			}
            if (i < 3) {
                boxs[this.i+1][this.j].state = !boxs[this.i+1][this.j].state;
                if (boxs[this.i+1][this.j].state) {
                    boxs[this.i+1][this.j].src = "./img/an.png"
                } else {
                    boxs[this.i+1][this.j].src = "./img/liang.png"
                }
            } 
            if (j>0) {
				boxs[this.i][this.j-1].state = !boxs[this.i][this.j-1].state;
				if(boxs[this.i][this.j-1].state){
					boxs[this.i][this.j-1].src = "./img/an.png"
				}else{
					boxs[this.i][this.j-1].src =  "./img/liang.png"
				}
			}
			//控制右灯笼
			if (j<3) {
				boxs[this.i][this.j+1].state = !boxs[this.i][this.j+1].state;
				if(boxs[this.i][this.j+1].state){
					boxs[this.i][this.j+1].src = "./img/an.png"
				}else{
					boxs[this.i][this.j+1].src =  "./img/liang.png"
				}
			}	
        }
        return box
    }

这是HTML和css部分

 .box {
            width: 460px;
            height: 420px;
	        display: flex;
	        flex-wrap: wrap;
	        display: -webkit-flex;
        }
        .deng{
	        width: 100px;
	        height: 100px;
	        top: 0;
	        left:0;
        }
<div id="boxdiv" class="box">

        </div>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值