请叫我小一 2019-04-01 15:14 采纳率: 100%
浏览 337
已采纳

用JS写的贪吃蛇,为什么定时器结束后会自动平移一格?

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>random</title>
    <style>
    .map{
      width: 800px;
      height: 600px;
      background-color: #CCC;
      position: relative;
    }
    </style>
</head>
<body>
    <div class="map"></div>
    <script>
        //自调用函数----食物的
        (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;
    }

    //为原型添加初始化的方法(作用:在页面上显示这个食物)
    //因为食物要在地图上显示,所以,需要地图的这个参数(map---就是页面上的.class=map的这个div)
    Food.prototype.init=function(map){
        //先删除这个小食物
        //外部无法访问的函数
        remove();
        //设置div的样式
        var div = document.createElement("div");
        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加到map中
        map.appendChild(div);
        //把div加入到数组elements中
        elements.push(div);
    }

    function remove(){
        for(var i=0;i<elements.length;i++)
        {
            //找到这个子元素的父级元素,然后删除这个子元素
            elements[i].parentNode.removeChild(elements[i]);
            //再次把elements中的这个子元素也要删除
            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:2,color:"red"},
            {x:2,y:2,color:"orange"},
            {x:1,y:2,color:"orange"}
        ];
    }

    //为原型添加方法--小蛇初始化的方法
    Snake.prototype.init=function(map){
        remove();
        //循环遍历创建div
        for(var i=0;i<this.body.length;i++)
        {
            //数组中的每个数组元素都是一个对象
            var obj=this.body[i];
            var div=document.createElement('div');
            //设置div的样式
            div.style.position = "absolute";
            div.style.width = this.width + "px";
            div.style.height = this.height + "px";
            //横纵坐标
            div.style.left = obj.x * this.width + "px";
            div.style.top = obj.y * this.height + "px";
            //背景颜色
            div.style.backgroundColor = obj.color;
            //方向暂时不定
            map.appendChild(div);
            //把div加入到elements数组中----目的是为了删除
            elements.push(div);
        }
    }

    //为原型添加方法---小蛇动起来
    Snake.prototype.move=function(food,map){
        //改变小蛇的身体的坐标位置
        var i=this.body.length-1;//2
        for(;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;
        //判断小蛇的头的坐标和食物的坐标是否相同
        if(headX==food.x&&headY==food.y)
        {
            var last=this.body[this.body.length-1];
            this.body.push({
                x:last.x,
                y:last.y,
                color:last.color
            });
            //把食物删除,重新初始化食物
            food.init(map);
        }
    }

    function remove(){
        //删除map中的小蛇的每个div,同时删除elements数组中的每个元素,从蛇尾向蛇头方向删除div
        var i = elements.length - 1;
        for(;i>=0;i--)
        {
            //先从当前的子元素中找到该子元素的父级元素,然后再弄死这个子元素
            var div=elements[i];
            //从map地图上删除这个子元素div
            div.parentNode.removeChild(div);
            elements.splice(i, 1);
        }
    }

    window.Snake=Snake;
})();
        //自调用函数---游戏对象================================================
        (function(){
    function Game(map) {
        this.food = new Food();//食物对象
        this.snake = new Snake();//小蛇对象
        this.map = map;//地图
        that = this;//保存当前的实例对象到that变量中-----------------此时that就是this
    }

    //初始化游戏-----可以设置小蛇和食物显示出来
    Game.prototype.init = function () {
    //初始化游戏
    //食物初始化
    this.food.init(this.map);
    //小蛇初始化
    this.snake.init(this.map);
    //调用自动移动小蛇的方法========================||调用了小蛇自动移动的方法
    this.runSnake(this.food, this.map);
    //调用按键的方法
    this.bindKey();//========================================
    };

    //添加原型方法---设置小蛇可以自动的跑起来
    Game.prototype.runSnake=function(food,map){
        //自动的去移动
        var timeId = setInterval(function () {
            //此时的this是window
            //移动小蛇
            this.snake.move(food, map);
            //初始化小蛇
            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);
            alert("游戏结束");
            }
            //纵坐标
            if (headY < 0 || headY >= maxY) {
            //撞墙了,停止定时器
            clearInterval(timeId);
            alert("游戏结束");
            }
        }.bind(that), 150);
    }

    //添加原型方法---设置用户按键,改变小蛇移动的方向
    Game.prototype.bindKey=function(){
        document.addEventListener("keydown",function(e){
            //获取用户的按键,改变小蛇的方向
            //这里的this应该是触发keydown的事件的对象---document,
            //所以,这里的this就是document
            //获取按键的值
            switch (e.keyCode){
                case 37:
                    this.snake.direction="left";
                    if(snake_direction=="right")
                    {
                        this.snake.direction="right";
                    }
                    else{
                        snake_direction="left";
                    }
                    break;
                case 38:
                    this.snake.direction="top";
                    if(snake_direction=="bottom")
                    {
                        this.snake.direction="bottom";
                    }
                    else{
                        snake_direction="top";
                    }
                    break;
                case 39:
                    this.snake.direction="right";
                    if(snake_direction=="left")
                    {
                        this.snake.direction="left";
                    }
                    else{
                        snake_direction="right";
                    }
                    break;
                case 40:
                    this.snake.direction="bottom";
                    if(snake_direction=="top")
                    {
                        this.snake.direction="top";
                    }
                    else{
                        snake_direction="bottom";
                    }
                    break;
            }
        }.bind(that));
    }

    window.Game=Game;
})();
        //初始化游戏对象
        var gm = new Game(document.querySelector(".map"));

        //初始化游戏---开始游戏
        gm.init();

    </script>
</body>
</html>
  • 写回答

1条回答

  • LuoBinary 2019-04-01 15:54
    关注

    runSnake()方法里面逻辑有问题,在蛇撞墙之后还是执行了snake的move和init方法。改成我写的这样就行了:

        //添加原型方法---设置小蛇可以自动的跑起来
        Game.prototype.runSnake=function(food,map){
            //自动的去移动
            var timeId = setInterval(function () {
                //此时的this是window
                //移动小蛇
                this.snake.move(food, 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 || headY < 0 || headY >= maxY) {
                //撞墙了,停止定时器
                clearInterval(timeId);
                alert("游戏结束");
                }else{
                //初始化小蛇
                this.snake.init(map);
                }
            }.bind(that), 150);
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案