用js、html、css制作简单的关灯游戏

CloseHight.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
*{
    margin: 0px;
    padding: 0px;
}
.content{
    margin:auto;
    background:red;
    font-size:0px;
}
.box{
    width:50px;
    height: 50px;
    border:.5px white solid;
    display:inline-block;
}
</style>
</head>
<body>
    <div class="content" style="min-width:714px;max-width:714px;">  
    </div>
    <div style="font-size:16px; text-align:center;">您已用<span id="bushu" style="width:20px;height:20px; color:red;"></span></div>
</body>
<script type="text/javascript" src="../js/CloseLight.js"></script>
</html>

CloseLight.js

var boxs = document.getElementsByClassName("box");//获取所有指定类名"box"的元素
var divs = document.getElementsByClassName("content");
var count = 0;//声明点击的步数

function initialize(){//初始化游戏界面
    var temp = divs[0];
    var content ="";
    //初始化一个140个方格的背景为黑色的、具有点击事件的游戏背景
    for(var i=0; i<140; i++){
        content = content + '<div class="box" style="background-color:black;" onclick="myClick('+i+');"></div>';
    }
    temp.innerHTML = content;
    //模拟游戏操作过程,随机点击10个div块
    for(var j=0; j<10; j++){
        operation(Math.floor(Math.random()*140));
    }
}

//点击事件的方法
function myClick(foo){
    count++;
    var bushu = document.getElementById("bushu");
    bushu.innerText = count;
    console.log(foo);//在控制台输出块的序号
    operation(foo);
    isClose();
}

//改变颜色
function changeColor(index){
    if(boxs[index].getAttribute("style").includes("black")){//如果div的style中的属性包含black
        boxs[index].setAttribute("style","background-color:red;");//将该div的style属性中背景颜色改为red
    }else if(boxs[index].getAttribute("style").includes("red")){
        boxs[index].setAttribute("style","background-color:black;");
    }
}

//点击后对上下左右的影响
function operation(index){
    //Up
    if(index>13){//当点击的div不是第一行
        changeColor(index-14);
    }
    //Down
    if(index<126){//当点击的div不是最后一行
        changeColor(index+14);
    }
    //Left
    var left = index % 14;
    if(left!=0){//当点击的div不是第一列
        changeColor(index-1);
    }
    //Light
    var light = (index+1) % 14;
    if(light != 0){/当点击的div不是最后一列
        changeColor(index+1);
    }
}

//判断是否全部关闭
function isClose(){
    for(var j=0;j<boxs.length; j++){//遍历整个div,如果有style属性包含red,则跳出;如果没有style属性包含red,则通关
        if(boxs[j].getAttribute("style").includes("red")){
            return;
        }
    }
    alert("恭喜您,游戏通过~");
    initialize();
}

initialize();
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值