贪吃蛇js实现总结

这是一篇关于js贪吃蛇的总结
对象: 蛇 食物 游戏

1.创建食物对象

/*<!--创建食物对象
       属性:  X , Y ,width,height,color
       方法: render   随机创建一个食物对象,并输出到map上
-->*/

//自调用函数 ------>开启新的作用域------防止命名冲突
(function () {
    //局部作用域

    var position = 'absolute';
    /*记录上一次创建的食物,为删除做准备*/
    var elements = [];

    function Food(options) {
        options = options || {};
        this.x = options.x ||0;
        this.y = options.y ||0;

        this.width = options.width ||20;
        this.height = options.height || 20;

        this.color = options.color || 'green';
    };

//var f = new Food();


    /*渲染*/
    Food.prototype.render  = function (map) {
        /*删除之前创建的食物*/
        remove();

        /*随机设置x,y 的值*/
        this.x = Tools.getRandom(0,map.offsetWidth/this.width-1)*this.width;
        //这个食物前边有几个食物的宽度
        this.y = Tools.getRandom(0,map.offsetHeight/this.height-1)*this.height;
        //动态创建div------->食物
        var div = document.createElement('div');
        map.appendChild(div);
        elements.push(div);
        //设置div的样式
        div.style.position = position;  //子绝父相
        div.style.left = this.x + 'px';
        div.style.top = this.y + 'px';
        div.style.width = this.width + 'px';
        div.style.height = this.height +'px';
        div.style.backgroundColor = this.color;
    };
               //remove是不让外部访问的
    function remove() {
        for(var i=elements.length-1;i>=0;i--){//从后往前删
            //删除div
            elements[i].parentNode.removeChild((elements[i]));//elements[i]就是div,  父节点 ,  移除子元素
            /*删除数组中的元素
            * 删除数组
            * 第一个参数,从哪个元素开始删除
            * 第二个参数,删除几个元素
            * */
            elements.splice(i,1);
        }
    }
    //把Food构造函数,让外部可以访问
    window.Food = Food;
})();

//测试
/*
var map = document.getElementById('map');
var food = new Food();
food.render(map);*/

2.创建游戏对象

/*Game对象
* 属性:food snake  map
* 方法:start   开始游戏(绘制所有的对象)
* 构造函数
* */








(function () {
    var that;    //记录游戏对象

    function Game() {
       this.food = new Food();
       this.snake = new Snake();
       this.map = map;
       that = this;
    };
    Game.prototype.start = function () {
        //把蛇和食物对象,渲染到地图上
        this.food.render(this.map);
        //this.snake.move()
        this.snake.render(this.map);
        /*this.snake.move()
        this.snake.render(this.map);   //测试
        this.snake.move()
        this.snake.render(this.map);
        this.snake.move()
        this.snake.render(this.map);*/
        //开始游戏的逻辑
        /*
        * 1. 让蛇移动起来
        * 2.通过键盘控制蛇移动的方向
        * 3.当蛇遇到食物,做相应的处理
        * 4.遇到边界游戏结束
        * */

        //1
        runsnake();
        //2
        bindKey();

        //3

        //4
    }
        //私有的
    function runsnake(){
        var timerId = setInterval(function () {
            //让蛇走一个
            //在定时器的function中this是指向window对象的
            this.snake.move(this.food,this.map);//判断蛇是否吃到了食物
            this.snake.render(this.map);//把蛇渲染到map

            //4
            var maxX = this.map.offsetWidth/this.snake.width;
            var maxY = this.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(timerId);
                alert("Game Over!!!!");

            }
            /*纵向判断是否越界*/
            if(headY<0 || headY>=maxY){
                clearInterval(timerId);
                alert("Game Over!!!!");

            }



        }.bind(that),150);
    }

    //2通过键盘控制蛇移动的方向
    function bindKey(){
        document.addEventListener('keydown',function (e) {
            //console.log(e.keyCode);
            /*37-------->left
            * 
            * 38------->top
            * 
            * 39------->right
            * 
            * 40------->bottom
            */
            switch (e.keyCode) {
                case 37:
                    this.snake.direction = 'left';
                    break;
                case 38:
                    this.snake.direction = 'top';
                    break;
                case 39:
                    this.snake.direction = 'right';
                    break;
                case 40:
                    this.snake.direction = 'bottom';
                    break;

            }

        }.bind(that),false);
    };




    //暴露构造函数给外部
    window.Game = Game;
})();













4创建蛇对象
/*
创建蛇对象-------->
属性:width,heigth,body(数组),direclion(蛇的运动方向)
方法:render
蛇的构造函数
*/
(function () {
//局部函数
var position = ‘absolute’;
var elements = []; //记录之前创建的蛇
function Snake(options) {

    options = options ||{};
    //蛇节的大小
    this.width = options.width ||20;
    this.height = options.height||20;
    //蛇移动的方向
    this.direction = options.direction ||'right';
    //蛇的身体(蛇节)//第一个蛇节是蛇头
    this.body = [
        {x: 3,y: 2, color:'red'},
        {x: 2,y: 2, color:'blue'},
        {x: 1,y: 2, color:'blue'}
    ];
}
Snake.prototype.render = function(map){
    //删除之前创建的蛇(私有的)
    remove();


    //把每一个蛇节渲染到地图上
    for(var i=0,len=this.body.length;i<len;i++){
        //蛇节
        var object = this.body[i];
        //创建一个div,并把它放到map中.
        var div = document.createElement('div');
        map.appendChild(div);
        elements.push(div);   //记录当前蛇
        div.style.position = position;
        div.style.width = this.width+'px';
        div.style.height = this.height+'px';
        div.style.left = object.x  * this.width+'px';
        div.style.top = object.y * this.height+'px';   //注意
        div.style.backgroundColor = object.color;

    }
}

//私有
function remove(){
        for(var i=elements.length-1;i>=0;i--){
            //删除div
            elements[i].parentNode.removeChild(elements[i]);

            //删除数组中的元素
            elements.splice(i,1);
        }
}

        //控制蛇移动的方法
    Snake.prototype.move = function(food,map){
          //控制蛇的身体移动(当前蛇节 到 上一个蛇节的位置)
         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;
         }

        //控制蛇头的移动
        var head = this.body[0];
        /*判断蛇移动的方向*/
        switch (this.direction){
            case  'right':
                head.x +=1;
                break;
            case  'left':
                head.x-=1;
                break;
            case  'top':
                head.y-=1;
                break;
            case  'bottom':
                head.y+=1;
                break;

        }
        /*Game3判断蛇头是否和食物的坐标重合*/
        var headX = head.x *this.width;
        var headY = head.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.render(map);
        }



    }

window.Snake = Snake;

})();

//测试
// var map = document.getElementById(‘map’);
// var snake = new Snake();
// snake.render(map);

创建一个工具类

(function () {
var Tools = {
getRandom:function (min,max) {
return Math.floor(Math.random()*(max - min + 1))+min;
}
}

window.Tools = Tools;

})();

5.运行代码
/运行代码/
(function(){
var map = document.getElementById(‘map’);
var game = new Game();
game.start();
})();

这是html的代码

Title
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值