JS进阶:贪吃蛇游戏

  1. 对于贪吃蛇由食物,蛇,地图,游戏对象这个部分组成
  2. 地图是最简单的,看个人如何设计它的样式与属性
  3. 食物对象,设计样式以及位置,对于位置要做到位置随机,且在蛇头吃掉食物后食物会消失,出现在另一随机位置,代码如下:
 (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';
            }
            //渲染
            Food.prototype.render = function (map) {
                //吃掉食物之后,删除食物
                removeFood();

                this.x = Tools.getRandom(0, map.offsetWidth / this.width - 1) * this.width;
                this.y = Tools.getRandom(0, map.offsetHeight / this.height - 1) * this.height
                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;
            }

            //删除食物
            function removeFood() {
                for (var i = elements.length - 1; i >= 0; i--) {
                    //删除div
                    elements[i].parentNode.removeChild(elements[i]);
                    //删除数组中的元素
                    //删除数组元素
                    //第一个参数
                    elements.splice(i, 1);
                }
            }
            window.Food = Food;
        })()

        //随机生成食物
        var Tools = {
            getRandom: function (min, max) {
                return Math.floor(Math.random() * (max - min + 1)) + min;
            }
        }
  1. 蛇对象的样式属性可自由设计,蛇移动起来的方法是:蛇身体移动后一个的蛇节的下一位置是前一个蛇节,蛇头的移动要看具体的移动方向代码如下:
       //控制蛇的身体移动(当前蛇结到上一个蛇结的位置)
            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;
            }

5.当蛇头吃到食物的时候,食物就会消失,且蛇的身子会长一节

            //2.4判断蛇头是否和食物重合
            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);
            }

6.游戏对象用来调用食物对象和蛇对象,以及根据键盘来控制蛇的方向,用键盘控制,游戏结束的标志就是当蛇出了边界

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

总代码如下:

       <script>
        var map = document.querySelector('#map');

        //游戏对象
        (function () {
            var that;//记录游戏对象
            function Game(map) {
                this.food = new Food();
                this.snake = new Snake();
                this.map = map;
                that = this;
            }

            //开始游戏
            Game.prototype.start = function () {
                //1.把蛇和食物对象渲染到map上
                this.food.render(this.map);
                //开始游戏的逻辑
                //1让蛇移动起来
                //2当蛇遇到边界时游戏就结束
                runSnake();
                //3通过键盘控制蛇移动方向
                bindKey();
                //4当蛇遇到食物时

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

            //私有函数
            function runSnake() {
                var timerId = setInterval(function () {
                    //让蛇走一格
                    //在定时器中function中this指向window对象的
                    //要获取游戏对象中的蛇属性
                    that.snake.move(that.food, that.map);
                    that.snake.render(that.map);
                    //当蛇遇到边界时游戏结束
                    //获取蛇头的坐标
                    var maxX = that.map.offsetWidth / that.snake.width;
                    var maxY = that.map.offsetHeight / that.snake.height;
                    var headX = that.snake.body[0].x;
                    var headY = that.snake.body[0].y;
                    if (headX < 0 || headX >= maxX) {
                        alert('Game Over');
                        clearInterval(timerId);
                    }
                    if (headY < 0 || headY >= maxY) {
                        alert('Game Over');
                        clearInterval(timerId);
                    }
                }, 150);
            }
            window.Game = Game;
        })();

        (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';
            }
            //渲染
            Food.prototype.render = function (map) {
                //吃掉食物之后,删除食物
                removeFood();

                this.x = Tools.getRandom(0, map.offsetWidth / this.width - 1) * this.width;
                this.y = Tools.getRandom(0, map.offsetHeight / this.height - 1) * this.height
                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;
            }

            //删除食物
            function removeFood() {
                for (var i = elements.length - 1; i >= 0; i--) {
                    //删除div
                    elements[i].parentNode.removeChild(elements[i]);
                    //删除数组中的元素
                    //删除数组元素
                    //第一个参数
                    elements.splice(i, 1);
                }
            }
            window.Food = Food;
        })()

        //随机生成食物
        var Tools = {
            getRandom: function (min, max) {
                return Math.floor(Math.random() * (max - min + 1)) + min;
            }
        }

        //蛇对象
        //自调用函数,防止命名冲突
        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();
            //把每一个蛇结渲染到map上面
            for (var i = 0, len = this.body.length; i < len; i++) {
                var object = this.body[i];
                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;
            }
            //2.4判断蛇头是否和食物重合
            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);
            }
        }
        //调用
        var game = new Game(map);
        game.start();
    </script>
代码还有一些没有完善的地方,后期慢慢改善。。。。
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值