js贪吃蛇

贪吃蛇网页:

js贪吃蛇

*{
        padding: 0;
        margin: 0;
    }
    .dv{
        width: 300px;
        height: 200px;
        border: 1px solid red;
        border-radius: 5px;
        position: absolute;
        right: 110px;
        top: 20px;
    }
    .dv div{
        width: 300px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        font-size: 18px;
        color: orange;
        margin: 6px 6px;
    }
    #s2,#s1{
        color: red;
        font-size: 18px;
    }
    h3{
        text-align: center;
        padding:8px 0px;
        margin-top: 20px;
    }


<div id="map"></div>
<div class="dv">
    <h3>欢迎进入贪吃蛇世界!</h3>
    <div>时间:<span id="s1">00</span>秒</div>
    <div>积分:<span id="s2">0</span>分</div>
    <div id="div1" style="display: none;font-size: 14px;color: hotpink">积分加50</div>
</div>

js代码

var quickTime = 0;
    var num = parseInt(prompt("请输入难度等级:(1/2/3)"));
    if (num == 1) {
        my$("map").style.width = "1100px";
        my$("map").style.height = "700px";
        my$("map").style.backgroundColor = "#ccc";
        my$("map").style.position = "relative";
        quickTime = 90;
    }else if (num == 2){
        my$("map").style.width = "900px";
        my$("map").style.height = "600px";
        my$("map").style.backgroundColor = "#ccc";
        my$("map").style.position = "relative";
        quickTime = 60;
    }else if (num == 3) {
        my$("map").style.width = "800px";
        my$("map").style.height = "500px";
        my$("map").style.backgroundColor = "#ccc";
        my$("map").style.position = "relative";
        quickTime = 40;
    }

    //显示积分和时间
    var time = 0;
    var timeOut;
    var score = parseInt(my$("s2").innerText);
    var timer = setInterval(function () {
        time ++;
        time = time < 10 ? "0"+ time : time;
        my$("s1").innerHTML = time;
        if(time % 30 == 0 && time != 0){
            my$("div1").style.display = "block";
            score += 50;
            my$("s2").innerText = score;
            timeOut = setTimeout(function () {
                my$("div1").style.display = "none";
            },5000);
        }
    },1000);

    // //创建食物对象
    // ((function () {
    //     //保存每一个小方块,方便删除小方块
    //     var elements = [];
    //
    //     //构造函数
    //     function Food(width,height,color,x,y) {
    //         this.width = width || 20;
    //         this.height = height || 20;
    //         this.color = color || "green";
    //         //随机的横纵坐标
    //         this.x = x || 0;
    //         this.y = y || 0;
    //     }
    //
    //     //在原型对象上添加方法---> 把食物显示在地图上
    //     Food.prototype.init = function (map) {
    //         //先删除再创建
    //         remove();
    //
    //         //1.创建一个小盒子
    //         var div = document.createElement("div");
    //         //2.把div添加到map中
    //         map.appendChild(div);
    //         //3.设置样式
    //         div.style.width = this.width + "px";
    //         div.style.height = this.height + "px";
    //         div.style.backgroundColor = this.color;
    //         div.style.position = "absolute";
    //         //随机数的横纵坐标
    //         this.x = parseInt(Math.random() * (map.offsetWidth / this.width)) * this.width;
    //         this.y = parseInt(Math.random() * (map.offsetHeight / this.height)) * this.height;
    //         div.style.left = this.x + "px";
    //         div.style.top = this.y + "px";
    //
    //         //把div添加到数组中去
    //         elements.push(div);
    //     }
    //
    //     //封装一个删除食物的函数
    //     function remove(){
    //         for ( var i = 0; i < elements.length; i++){
    //             //获取每一个小方块
    //             var ele = elements[i];
    //             //删除map中的小方块
    //             ele.parentElement.removeChild(ele);
    //             //删除数组中的小方块
    //             elements.splice(i,1);
    //         }
    //     }
    //
    //     //把Food暴露给window
    //     window.Food = Food;
    //
    // })());
    //
    // //创建小蛇对象
    // ((function () {
    //     //存放小蛇
    //     var elements = [];
    //
    //     function Snake(width,height,direction) {
    //         //小蛇每个部位的宽度
    //         this.width = width || 20;
    //         this.height = height || 20;
    //         //小蛇的方向
    //         this.direction = direction || "right";
    //         //小蛇的身体 -- 》 小蛇吃食物会变长
    //         this.body = [
    //             {x:3,y:1,color:"red"},//小蛇的头部
    //             {x:2,y:1,color:"orange"},//小蛇的身体
    //             {x:1,y:1,color:"orange"}
    //         ]
    //     }
    //     //2.在原型中添加方法--》小蛇初始化--》需要地图参数
    //     Snake.prototype.init = function (map) {
    //         //先删除小蛇,再创建
    //         remove();
    //         //遍历的创建div---》小蛇的每个部位
    //         for ( var i = 0 ; i < this.body.length;i++ ){
    //             //创建
    //             var div = document.createElement("div");
    //             //添加到地图中
    //             map.appendChild(div);
    //             var obj = this.body[i];//存放的数组的每一个元素,也是对象
    //             //3.设置div的样式
    //             div.style.width = this.width + "px";
    //             div.style.height = this.height + "px";
    //             div.style.backgroundColor = obj.color;
    //             div.style.position = "absolute";
    //             //横纵坐标
    //             div.style.left = obj.x * this.width + "px";
    //             div.style.top = obj.y * this.height + "px";
    //             //把蛇添加到数组
    //             elements.push(div);
    //         }
    //     }
    //
    //
    //     //3.添加一个让小蛇移动的方法
    //     Snake.prototype.move = function (map,food){
    //         //改变小蛇的身体坐标--》要循环小蛇的身体部分,头部要判断方向
    //         for ( var i = this.body.length - 1;i > 0 ; i--){
    //             //当i等于2时,此时是第三块的坐标,让第二块的坐标给第三块的坐标
    //             this.body[i].x = this.body[i - 1].x;
    //             this.body[i].y = this.body[i - 1].y;
    //         }
    //         //判断小蛇头部的坐标位置
    //         switch (this.direction){
    //             case "right":
    //                 this.body[0].x += 1;
    //                 break;
    //             case "left":
    //                 this.body[0].x -= 1;
    //                 break;
    //             case "top":
    //                 this.body[0].y -= 1;
    //                 break;
    //             case "bottom":
    //                 this.body[0].y += 1;
    //                 break;
    //         }
    //
    //         //最后要判断小蛇是否吃到食物---》判断蛇头的坐标
    //         //获取蛇头的坐标
    //         var headX = this.body[0].x * this.width;
    //         var headY = this.body[0].y * this.height;
    //         //食物的坐标
    //         var foodX = food.x;
    //         var foodY = food.y;
    //
    //         if (headX == foodX && foodY == headY){
    //             //吃到食物加积分
    //             //1.重新初始化食物
    //             food.init(map);
    //             //2.获取小蛇的尾巴
    //             var last = this.body[this.body.length - 1];
    //             //3.添加到数组中
    //             this.body.push({
    //                 x:last.x,
    //                 y:last.y,
    //                 color:last.color
    //             })
    //             //计算积分
    //             score += 10;
    //             my$("s2").innerHTML = score;
    //         }
    //     }
    //
    //     function remove(){
    //         for ( var i = elements.length - 1; i >= 0; i--){
    //             //存放每一个小蛇的
    //             var ele = elements[i];
    //             //删除地图上面的小蛇
    //             ele.parentElement.removeChild(ele);
    //             //删除数组中的小蛇
    //             elements.splice(i,1);
    //         }
    //     }
    //
    //     //暴露给window
    //     window.Snake = Snake;
    // })());
    //
    // //创建游戏对象
    // ((function () {
    //     //游戏的构造函数
    //     function Game() {
    //         this.food = new Food();//食物的对象
    //         this.snake = new Snake();//小蛇的对象
    //         this.map = document.getElementById("map");//地图对象
    //     }
    //     //2.初始化游戏对象
    //     Game.prototype.init = function () {
    //         //显示食物和小蛇
    //         this.food.init(this.map);
    //         this.snake.init(this.map);
    //         //调用自动移动的小蛇
    //         this.runSnake(this.map,this.food);
    //         this.keyDown();
    //
    //     }
    //     //3.添加原型方法--》使小蛇自动跑起来
    //     Game.prototype.runSnake = function(map,food){
    //         var that = this;
    //         //自动的移动
    //         var timeID = setInterval(function () {
    //             this.snake.move(map,food);//移动
    //             this.snake.init(map);//显示
    //
    //             //判断横纵坐标的最大值
    //             var maxX = map.offsetWidth / this.snake.width;
    //             var maxY = map.offsetHeight / this.snake.height;
    //
    //             //获取蛇头的坐标
    //             var headX = this.snake.body[0].x;
    //             var headY = this.snake.body[0].y;
    //
    //             //判断横纵坐标是否撞墙
    //             if (headX < 0 || headX >= maxX){
    //                 clearInterval(timeID);
    //                 clearInterval(timer);
    //                 clearTimeout(timeOut);
    //                 alert("游戏结束,你的积分为"+score);
    //             }
    //             if (headY < 0 || headY >= maxY){
    //                 clearInterval(timeID);
    //                 clearInterval(timer);
    //                 clearTimeout(timeOut);
    //                 alert("游戏结束,你的积分为"+score);
    //             }
    //         }.bind(that),quickTime);
    //         //.bind(that)把这个函数的指向绑定在了that的指向上
    //     }
    //
    //     //4.添加原型方法---》设置用户的按键,改变小蛇的方向
    //     Game.prototype.keyDown = function (){
    //         document.addEventListener("keydown",function (e) {
    //             // console.log(e.keyCode);//按键的值
    //             switch (e.keyCode) {
    //                 case 65:
    //                 case 37:
    //                     this.snake.direction = "left";
    //                     break;
    //                 case 87:
    //                 case 38:
    //                     this.snake.direction = "top";
    //                     break;
    //                 case 68:
    //                 case 39:
    //                     this.snake.direction = "right";
    //                     break;
    //                 case 83:
    //                 case 40:
    //                     this.snake.direction = "bottom";
    //                     break;
    //             }
    //         }.bind(this))
    //     }
    //
    //
    //     //暴露给window
    //     window.Game = Game;
    // })());
    //
    // var game = new Game();
    // game.init();


    //创建食物对象
    ((function () {
        //保存每一个小方块,方便删除小方块
        var elements = [];

        function Food(width,height,x,y) {
            this.width = width || 20;
            this.height = height || 20;
            //随机的横纵坐标
            this.x = x || 0;
            this.y = y || 0;
        }

        //在原型对象上添加方法
        Food.prototype.init = function (map) {
            //先删除再创建
            remove();
            //1.创建一个小盒子
            var div = document.createElement("div");
            //2.把div添加到map中
            map.appendChild(div);
            //3.设置样式
            div.style.width = this.width + "px";
            div.style.height = this.height + "px";
            div.style.backgroundImage = "url('bangbang.jpg')";
            div.style.width = "20px";
            div.style.height = "20px";
            div.style.backgroundSize = "20px 20px";
            div.style.position = "absolute";
            //随机数的横纵坐标
            this.x = parseInt(Math.random() * (map.offsetWidth / this.width)) * this.width;
            this.y = parseInt(Math.random() * (map.offsetHeight / this.height)) * this.height;
            div.style.left = this.x + "px";
            div.style.top = this.y + "px";
            //把div添加到数组中去
            elements.push(div);
        }

        //封装一个删除食物的函数
        function remove(){
            for ( var i = 0; i < elements.length; i++){
                //获取每一个小方块
                var ele = elements[i];
                //删除map中的小方块
                ele.parentElement.removeChild(ele);
                //删除数组中的小方块
                elements.splice(i,1);
            }
        }

        //把Food暴露给window
        window.Food = Food;

    })());

    //创建小蛇对象
    ((function () {
        //存放小蛇
        var elements = [];

        function Snake(width,height,direction) {
            //小蛇每个部位的宽度
            this.width = width || 20;
            this.height = height || 20;
            //小蛇的方向
            this.direction = direction || "right";
            //小蛇的身体
            this.body = [
                {x:3,y:1,color:"red"},//小蛇的头部
                {x:2,y:1,color:"yellow"},//小蛇的身体
                {x:1,y:1,color:"yellow"}//小蛇的身体
            ]
        }
        //2.在原型中添加方法
        Snake.prototype.init = function (map) {
            //先删除小蛇,再创建
            remove();
            //遍历的创建div
            for ( var i = 0 ; i < this.body.length;i++ ){
                //创建
                var div = document.createElement("div");
                //添加到地图中
                map.appendChild(div);
                var obj = this.body[i];
                //3.设置div的样式
                div.style.width = this.width + "px";
                div.style.height = this.height + "px";
                div.style.backgroundColor = obj.color;
                div.style.position = "absolute";
                div.style.borderRadius = "40%";
                //横纵坐标
                div.style.left = obj.x * this.width + "px";
                div.style.top = obj.y * this.height + "px";
                //把蛇添加到数组
                elements.push(div);
            }
        }


        //3.添加一个让小蛇移动的方法
        Snake.prototype.move = function (map,food){
            //改变小蛇的身体坐标
            for ( var i = this.body.length - 1;i > 0 ; i--){
                this.body[i].x = this.body[i - 1].x;
                this.body[i].y = this.body[i - 1].y;
            }
            //判断小蛇头部的坐标位置
            switch (this.direction){
                case "right":
                    this.body[0].x += 1;
                    break;
                case "left":
                    this.body[0].x -= 1;
                    break;
                case "top":
                    this.body[0].y -= 1;
                    break;
                case "bottom":
                    this.body[0].y += 1;
                    break;
            }

            //获取蛇头的坐标
            var headX = this.body[0].x * this.width;
            var headY = this.body[0].y * this.height;
            //食物的坐标
            var foodX = food.x;
            var foodY = food.y;

            if (headX == foodX && foodY == headY){
                //1.重新初始化食物
                food.init(map);
                //2.获取小蛇的尾巴
                var last = this.body[this.body.length - 1];
                //3.添加到数组中
                this.body.push({
                    x:last.x,
                    y:last.y,
                    color:last.color
                })
                //吃到食物计算积分
                score += 10;
                my$("s2").innerHTML = score;
            }
        }

        function remove(){
            for ( var i = elements.length - 1; i >= 0; i--){
                //存放每一个小蛇的
                var ele = elements[i];
                //删除地图上面的小蛇
                ele.parentElement.removeChild(ele);
                //删除数组中的小蛇
                elements.splice(i,1);
            }
        }
        //暴露给window
        window.Snake = Snake;
    })());

    //创建游戏对象
    ((function () {
        //游戏的构造函数
        function Game() {
            this.food = new Food();//食物的对象
            this.snake = new Snake();//小蛇的对象
            this.map = document.getElementById("map");//地图对象
        }
        //2.初始化游戏对象
        Game.prototype.init = function () {
            //显示食物和小蛇
            this.food.init(this.map);
            this.snake.init(this.map);
            //调用自动移动的小蛇
            this.runSnake(this.map,this.food);
            this.keyDown();

        }
        //3.添加原型方法
        Game.prototype.runSnake = function(map,food){
            var that = this;
            //自动的移动
            var timeID = setInterval(function () {
                this.snake.move(map,food);
                this.snake.init(map);

                //判断横纵坐标的最大值
                var maxX = map.offsetWidth / this.snake.width;
                var maxY = map.offsetHeight / this.snake.height;

                //获取蛇头的坐标
                var headX = this.snake.body[0].x;
                var headY = this.snake.body[0].y;

                //判断横纵坐标是否撞墙
                //获取小蛇的各个部位
                var divs = my$("map").getElementsByTagName("div");
                if (headX < 0 || headX >= maxX){
                    //小蛇撞墙后的位置
                    if (headX < 0){
                        for ( var i = 1; i < divs.length;i++){
                            divs[i].style.left = divs[i].offsetWidth * (i - 1) + "px";
                        }
                    } else {
                        for ( var i = 1; i < divs.length;i++){
                            divs[i].style.left = (my$("map").offsetWidth - divs[i].offsetWidth * i) + "px";
                        }
                    }
                    clearInterval(timeID);
                    clearInterval(timer);
                    clearTimeout(timeOut);
                    alert("游戏结束,你的积分为"+score);
                }
                if (headY < 0 || headY >= maxY){
                    //小蛇撞墙后的位置
                    if (headY < 0){
                        for ( var i = 1; i < divs.length;i++){
                            divs[i].style.top = divs[i].offsetHeight * (i - 1) + "px";
                        }
                    } else {
                        for ( var i = 1; i < divs.length;i++){
                            divs[i].style.top = (my$("map").offsetHeight - divs[i].offsetHeight * i) + "px";
                        }
                    }
                    clearInterval(timeID);
                    clearInterval(timer);
                    clearTimeout(timeOut);
                    alert("游戏结束,你的积分为"+score);
                }
            }.bind(that),quickTime);
        }

        //4.添加原型方法
        Game.prototype.keyDown = function (){
            document.addEventListener("keydown",function (e) {
                switch (e.keyCode) {
                    case 65:
                    case 37:
                        this.snake.direction = "left";
                        break;
                    case 87:
                    case 38:
                        this.snake.direction = "top";
                        break;
                    case 68:
                    case 39:
                        this.snake.direction = "right";
                        break;
                    case 83:
                    case 40:
                        this.snake.direction = "bottom";
                        break;
                }
            }.bind(this))
        }
        //暴露给window
        window.Game = Game;
    })());

    var game = new Game();
    game.init();


function my$(id){
    return document.getElementById(id);
}

目前还有些bug,不完善,敬请见谅!