原生js做打地鼠游戏

时间:2024-03-25 16:11:54

原生js做打地鼠游戏
学原生js的语法其实是容易的,最主要的练习逻辑思维。对于刚刚学完js的语法的我来说,写这个打地鼠游戏真的花费了我一整天的时间。整体感觉写出来的js代码,其实就是平时练习的一些小案例的代码拼起来的,js代码量比较少,最难的还是逻辑思维。练习逻辑思维是每个初学js都必备的。
建议:
在写一些逻辑思维较强的程序时,建议画思维脑图。可帮助写代码是思路清晰,避免混乱。
原生js做打地鼠游戏

原生js做打地鼠游戏
白线框是每个老鼠出现的位置

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }
        .game {
            width: 750px;
            height: 600px;
            margin: 0 auto;
        }
        .ground {
            position: relative;
            width: 100%;
            height: 600px;
            background: url("images/bg_canvas.png") no-repeat;
            cursor: url("images/hammer.png") ,auto;
        }
        .ground .score {
            width: 300px;
            height: 30px;
            position: absolute;
            top: 180px;
            right: 40px;
        }
        .score img {
            width: 80px;
            height: 30px;
            display: inline-block;
        }
        .score span {
            display: inline-block;
            height: 30px;
            line-height: 30px;
            color: #fff;
            font-size: 24px;
            margin-left: 10px;
            vertical-align: top;
        }
        .ground .mask {
            width: 140px;
            height: 125px;
            position: absolute;
            overflow: hidden;
            border: 1px solid #ccc;
            background-position: 50% 50%;
        }
        .mouse {
            width: 110px;
            height: 125px;
            position: absolute;
            top: 10px;
            animation: mousecreate 0.5s linear ;
        }
        @keyframes mousecreate {
            0%{
                top: 70px;
            }
            100% {
                top: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="game">
        <div class="ground" id="_ground">
            <div class="score">
                <img src="images/score.png" alt="">
                <span></span>
            </div>          
        </div>
    </div>
</body>
</html>
<script>
    // 获取元素 ,设置全局变量
    var _ground = document.getElementById("_ground");
    var Mask = [];// 存储mask遮罩
    var Mouse = [];// 存储老鼠
    var score = 0;
    var life = 10;
    var gemeTimer = null;
    var maxMouseCount = 2;//初始时,老鼠出现的个数不超过2个
    var coordinate = [{x: 130, y:173}, {x: 320, y:171}, {x: 515, y:175}, {x: 105, y: 265}, {x: 320, y: 256}, {x: 522, y: 256}, {x: 96, y: 350}, {x: 320, y: 355}, {x: 540, y: 358}];//洞口坐标
    /*
        1:鼠标按下ground,鼠标锤子改变,鼠标弹起锤子恢复
        2:创建洞穴和遮罩
        3:创建老鼠 
        4:老鼠出现
        5:老鼠消失 -> 1: 不敲打自己消失 2: 敲打盒子消失
    */

    // 1:鼠标点击ground,鼠标锤子改变
    _ground.onmousedown = function() {
        _ground.style.cursor = "url('images/hammer2.png'),auto";
    }
    _ground.onmouseup = function() {
        _ground.style.cursor = "url('images/hammer.png'),auto";    
    }
    init();// 初始化函数
    // 2:创建洞穴和遮罩
    function createMask() {
        for(var i = 0; i < coordinate.length; i++)
        {
        var mask = document.createElement("div");
        mask.className = "mask";
        mask.style.left = coordinate[i].x + "px";
        mask.style.top = coordinate[i].y + "px";
        mask.index = i;
        var maskimg = document.createElement("div");
        maskimg.className = "mask";
        maskimg.style.zIndex = i * 2  + 1; // 遮罩的层级大于老鼠的层级,并且保证上一层的遮罩层级不能大于下一层老鼠的层级,否则会遮住老鼠的头部 
        maskimg.style.backgroundImage = "url('images/mask"+i+".png')";
        mask.appendChild(maskimg);// 添加遮罩层
        Mask[i] = mask;
        _ground.appendChild(mask);// 添加洞穴
        mask.onclick = function() {
            disappear(this.index,true); // (被敲打的mask的index,被敲打)
        }
        }
    }

    // 3: 创建老鼠
    function createMouse(i) {
        // 随机选择老鼠
        var picnum = Math.floor(Math.random()*4);// 从0-4产生一个随机数
        var mouse = document.createElement("div");
        mouse.className = "mouse";
        mouse.num = picnum;
        mouse.style.zIndex = i * 2;
        mouse.style.backgroundImage = "url('images/mouse"+picnum+".png')";
        Mouse[i] = mouse;// 向老鼠数组里面添加老鼠
        Mask[i].appendChild(mouse); // 向洞穴里面添加老鼠

        // 每个老鼠都有一个消失的定时器
        var timer = setTimeout(function(){
            disappear(i,false);
        },2000);
        mouse.timer = timer;

    }

    // 4: 老鼠出现
    function genarateMouse() {
        var num = Math.floor(Math.random()*coordinate.length);// 随机产生一个洞穴位置
        if (Mouse.filter(function (item){
        return item;
    }).length < maxMouseCount && Mouse[num] == null) {
        createMouse(num);
    }
    }

    // 5: 老鼠消失  --> 1: 老鼠自动消失 2: 老鼠在被敲打之后消失
    function disappear(index,isHit) { // isHit是否被敲打,布尔值
        if(Mouse[index] != null)
        {
            Mouse[index].style.top = "70px";
            Mouse[index].style.transition  = "top 0.5s";
            if(isHit)// 如果被敲打
            {
                clearInterval(Mouse[index].timer);// 清除老鼠本身的定时器
                score += 10;
            }
            else
            {
                life -= 1;
            }
             setTimeout(function(){
                if(Mouse[index])
                {
                Mask[index].removeChild(Mouse[index]);
                }
                Mouse[index] = null;
            },500);
        }
    }

    function init() {
        createMask();
        gameTimer = setInterval(function(){
            genarateMouse();
            if(life <= 0)
            {
                clearInterval(gameTimer);
                alert("游戏结束,您的得分是" + score);
            }
            document.getElementsByClassName("score")[0].getElementsByTagName("span")[0].innerHTML =  score + ",生命:"+ life;
            maxMouseCount = score / 100 + 1;// 分数每增加到100, 允许老鼠出现的数目加1
        },50);
       
    }
</script>