关灯游戏js

 

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.wrap {
width: 500px;
height: 500px;
box-shadow: 0 0 3px #333;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
align-content: space-around;
}
.wrap div {
width: 80px;
height: 80px;
margin: 5px;
background-image: url(./img/close.png);
background-size: 100% 100%;
}
.wrap .open {
background-image: url(./img/open.png);
}
</style>
</head>
<body>
<div class="wrap">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</body>
<script>
// 需要进行改变的灯放入数组
var ds = $$('.wrap div');
//关卡
var level = 1;
// opend的个数
var count = 0;
// 点击事件
for (var i = 0; i < ds.length; i++) {
ds[i].index = i;
ds[i].onclick = function () {
getIndexs(this.index);
}
}
function getIndexs(index) {
var arr = []; //存放需要改变状态灯的下标
if (index == 0) {
arr = [0, 1, 5];
} else if (index == 4) {
arr = [4, 3, 9]
}
else if (index == 20) {
arr = [20, 21, 15]
}
else if (index == 24) {
arr = [24, 23, 19]
}
else if (index < 4) {
arr = [index, index + 1, index - 1, index + 5]
}
else if (index > 20) {
arr = [index, index + 1, index - 1, index - 5]
}
else if (index % 5 == 0) {
arr = [index, index + 5, index - 5, index + 1]
}
else if (index % 5 == 4) {
arr = [index, index + 5, index - 5, index - 1]
} else {
arr = [index, index + 1, index - 1, index + 5, index - 5]
}
changeLight(arr);
}
function changeLight(arr) {
for (var i = 0; i < arr.length; i++) {
var n = arr[i];
if (ds[n].className === "") {
ds[n].className = 'open';
count++;
} else {
ds[n].className = '';
count--;
}
}
//判断是否进入下一关卡
if (count === 0){
level++;
setTimeout( function() {
alert('恭喜你进入关卡' + level);
start();
}, 0);
}
}
// 简化一下query和queryall
function $(str) {
return document.querySelector(str);
}
function $$(str) {
return document.querySelectorAll(str);
}
//游戏开始
function start() {
//根据关卡点亮灯
for (var i = 0; i < level; i++) {
var n = rand(0, ds.length);
getIndexs(n);
}
}
start();
function rand(min, max) {
return Math.floor(Math.random() * (max - min) + min)
}
</script>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值