首先先来看看点灯游戏的实现逻辑
首先是十六个灯笼默认全部熄灭,点击之后灯笼上下左右同时点亮,点击旁边的灯笼同样会影响周围的灯笼
点击效果
使用二维数组来遍历出灯笼的行和列
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>