温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript怎么实现精美贪吃蛇游戏

发布时间:2021-11-26 14:45:28 来源:亿速云 阅读:160 作者:iii 栏目:开发技术

本篇内容主要讲解“JavaScript怎么实现精美贪吃蛇游戏”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“JavaScript怎么实现精美贪吃蛇游戏”吧!

    话不多说,我们还是先来看看最后的呈现效果吧。

    JavaScript怎么实现精美贪吃蛇游戏

    看完了才知道什么叫做操作,简直传奇!!

    接下来不吹牛来讲讲实际操作 !

    首先我们要知道所谓的贪吃蛇无非就是在表格上面行走的颜色!最初的效果也就是如下图所示

    JavaScript怎么实现精美贪吃蛇游戏

    当然在这个地方是用数组来操作的,也是用构造函数来封装的。

    JavaScript怎么实现精美贪吃蛇游戏

    在这个地方封装了三个 js 文件,分别用来写 食物、蛇、还有我们的中介者 Game.js 文件!

    我刚刚也说了,写贪吃蛇是一个从无到有的过程,所以最开始在我们的 index.html 里面什么都没有,就只有一个 div 盒子,其他的表格、蛇、食物都是后期用函数创建的。

    一、创建html结构

    以下是我们 body 里面最开始的代码:

    <body>
        <div id="app">
        </div>
        <script src="js/Snake.js"></script>
        <script src="js/Food.js"></script>
        <script src="js/Game.js"></script>
        <script>
            var game=new Game();
        </script>
    </body>

    二、创建表格

    从无到有第一步,当然是先把我们的表格追加到页面上,得有一个大体的框架!!这样就能看到刚刚上面图中所示的表格了,看到这仿佛就觉得接下来的每一步都是值得的!

    function Game() {
        this.row = 25;  // 行数
        this.col = 25;  // 列数
        this.init();    //初始化节点
    }
    Game.prototype.init = function () {
        this.dom = document.createElement('table'); // 创建表格
        var tr, td;
        // 遍历行和列
        for (var i = 0; i < this.row; i++) {
            tr = document.createElement('tr');  // 创建行
            for (var j = 0; j < this.col; j++) {
                td = document.createElement('td');  // 创建列
                tr.appendChild(td);     // 把列追加到行
            }
            this.dom.appendChild(tr);   // 把行追加到表格
        }
        document.querySelector('#app').appendChild(this.dom);   //把表格追加到div里
    }

    三、创建蛇头、蛇身

    从无到有第二步,蛇头蛇头蛇头、蛇身蛇身蛇身!看到这觉得学到知道是多么重要的环节。

    function Snake() {
        // 蛇的初始化身体
        this.body = [
            { 'row': 3, 'col': 5 },
            { 'row': 3, 'col': 4 },
            { 'row': 3, 'col': 3 },
            { 'row': 3, 'col': 2 }
        ];
    }
    Snake.prototype.render = function () {
        // 蛇头的渲染
        game.setColorHead(this.body[0].row, this.body[0].col);
        // 蛇身的渲染
        for (var i = 1; i < this.body.length; i++) {
            game.setColor(this.body[i].row, this.body[i].col, '#649c49')
        }
    }

    Snake 里面调用 中介者 Game 原型对象里面的属性!

    Game.prototype.setColor = function (row, col, color) {
        this.dom.getElementsByTagName('tr')[row].getElementsByTagName('td')[col].style.background = color;
    }

    四、创建食物

    从无到有第三步,食物食物食物! 看到这,我们的基本形态就算是全都有了!

    function Food(gameSnake) {
        var self = this;
        // 下面的 do-while 循环语句作用是先创建一个 row 和 col 然后判断这个 row 和 col 是否在蛇的身上
        do {
            // 食物的位置
            this.row = parseInt(Math.random() * gameSnake.row)
            this.col = parseInt(Math.random() * gameSnake.col)
        } while ((function () {
            // 遍历蛇的 row col 然后和 food 新随机出来的 row col 进行判断,是否重合
            for (var i = 0; i < gameSnake.snake.body.length; i++) {
                if (self.row == gameSnake.snake.body[i].row && self.col == gameSnake.snake.body[i].col) {
                    return true;
                }
            }
            return false;
        })());
    }
    Food.prototype.render = function () {
        game.setHTML(this.row, this.col);
    }

    五、让蛇动起来

    从无到有第四步,动起来动起来动起来!这里用数组的头增尾删简直就是天作之合!

    // 蛇的运动
    Snake.prototype.update = function () {
        this.direction = this.willDirection;
        switch (this.direction) {
            case 'R':   //右
                this.body.unshift({ 'row': this.body[0].row, 'col': this.body[0].col + 1 });
                break;
            case 'D':   //下
                this.body.unshift({ 'row': this.body[0].row + 1, 'col': this.body[0].col });
                break;
            case 'L':   //左
                this.body.unshift({ 'row': this.body[0].row, 'col': this.body[0].col - 1 });
                break;
            case 'U':   //上
                this.body.unshift({ 'row': this.body[0].row - 1, 'col': this.body[0].col });
                break;
        }
        // 死亡的判断,超出了表格边缘的部分
        if (this.body[0].col > game.col - 1 || this.body[0].col < 0 || this.body[0].row > game.row - 1 || this.body[0].row < 0) {
            alert('撞到墙了哦,一共吃掉了' + game.score + '颗草莓');
            this.body.shift();
            clearInterval(game.timer);
            location.reload();
        }
        // 自己撞到自己的时候会判定死亡
        for (var i = 1; i < this.body.length; i++) {
            // 如果当前蛇的头部和身体的某一个部位的 row 和 col 完全重合的时候
            if (this.body[0].row == this.body[i].row && this.body[0].col == this.body[i].col) {
                alert('撞到自己了,吃掉了' + game.score + '颗草莓');
                this.body.shift();
                clearInterval(game.timer);
                location.reload();
            }
        }
        // 蛇吃食物
        // 判断如果当前的蛇的头部没有和食物进行重合,就代表此时没有吃到食物,此时就进行尾部删除,如果重合了就代表迟到了,此时我们不进行删除尾部
        if (this.body[0].row == game.food.row && this.body[0].col == game.food.col) {
            // 此时情况是只有头部增加了,尾部没有删除
            game.food = new Food(game);    //创建新的食物
            game.score++;
            game.f = 0;
        } else {
            this.body.pop();    //删除数组最后一个元素
        }
    }

    六、控制蛇的方向

    从无到有第五步,蛇的方向! 做到这里,回望过去的每一步,都是浮云!!

    // 蛇的方向改变,防止的是在一次渲染之前会出现调头的情况
    Snake.prototype.changeDirection = function (d) {
        this.willDirection = d;
    }
    // 设置键盘的事件监听
    Game.prototype.bindEvent = function () {
        var self = this;
        document.addEventListener('keydown', function (e) {
            // 用ASCII码值判断键盘方向
            switch (e.keyCode) {
                case 37:    //左
                    if (self.snake.direction == 'R') return;    // 先进行判断,如果当前的方向是向右移动,此时我们不能按左键
                    self.snake.changeDirection('L');
                    self.d = 'L';
                    break;
                case 38:    //上
                    if (self.snake.direction == 'D') return;    // 先进行判断,如果当前的方向是向下移动,此时我们不能按上键
                    self.snake.changeDirection('U');
                    self.d = 'U';
                    break;
                case 39:    //右
                    if (self.snake.direction == 'L') return;    // 先进行判断,如果当前的方向是向左移动,此时我们不能按右键
                    self.snake.changeDirection('R');
                    self.d = 'R';
                    break;
                case 40:    //下
                    if (self.snake.direction == 'U') return;    // 先进行判断,如果当前的方向是向上移动,此时我们不能按下键
                    self.snake.changeDirection('D');
                    self.d = 'D';
                    break;
            }
        })
    }

    最后按照我们喜欢的样子设置样式就好啦,这里我按我自己喜欢粉色设置相应的颜色以及插入我喜换的食物的样子!!

    七、完整代码

    index.html

    <!DOCTYPE html>
    <html lang="en">
     
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>贪吃蛇</title>
        <style>
            * {
                padding: 0;
                margin: 0;
            }
     
            #app {
                position: relative;
                border: 20px solid #f8bbd0;
                background-color: #fce4ec;
                width: 500px;
                height: 500px;
                margin: 15px auto;
            }
     
            table {
                border-collapse: collapse;
                background-color: #fce4ec;
            }
     
            td {
                position: relative;
                background-size: 100% 100%;
                border-radius: 50%;
                width: 20px;
                height: 20px;
                text-align: center;
                /* background-color: #fce4ec; */
                /* border: 1px solid #aaa; */
            }
     
            td .snake {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
            }
     
            .start,
            .suspend {
                cursor: pointer;
                position: absolute;
                width: 150px;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
     
            .suspend {
                display: none;
                z-index: 2;
            }
        </style>
    </head>
     
    <body>
        <!-- <h4 id="f">帧编号:0</h4>
        <h4 id="score">分数:0</h4> -->
        <div id="app">
            <img src="images/start.gif" alt="" class="start">
            <img src="images/suspended.png" alt="" class="suspend">
        </div>
        <!-- <script src="js/last.js"></script> -->
        <script src="js/Snake.js"></script>
        <script src="js/Food.js"></script>
        <script src="js/Game.js"></script>
        <script>
            var game = null;
            var flag = true;
            var suspend = document.querySelector('.suspend');
            document.querySelector('.start').addEventListener('click', function () {
                // document.querySelector('#app').style.backgroundColor='white';
                this.style.display = 'none';
                game = new Game();
                document.querySelector('table').addEventListener('click', function () {
                    clearInterval(game.timer);
                    suspend.style.display = 'block';
     
                })
                suspend.addEventListener('click', function () {
                    suspend.style.display = 'none';
                    game.timer = setInterval(function () {
                        game.f++;
                        // document.getElementById('f').innerHTML = '帧编号:' + game.f;
                        // document.getElementById('score').innerHTML = '分数:' + game.score;
                        // 清屏
                        game.clear();
                        // 蛇的运动(更新)
                        // 蛇的更新速度,当蛇变长的时候,速度要加快
                        var during = game.snake.body.length < 30 ? 30 - game.snake.body.length : 1;
                        game.f % during == 0 && game.snake.update();
     
                        // game.snake.update();
                        // 渲染蛇
                        game.snake.render();
                        // 渲染食物
                        game.food.render();
                    }, 10)
                })
            })
        </script>
    </body>
     
    </html>

    Game.js

    function Game() {
        this.row = 25;  // 行数
        this.col = 25;  // 列数
        this.score = 0;   //分数
        this.init();    //初始化节点
        this.snake = new Snake();  //实例化蛇类
        this.food = new Food(this);   //初始化食物
        // this.last = new Last();
        this.start();   //执行定时器任务
        this.bindEvent();   //键盘的事件监听
        this.d = 'R';
    }
    Game.prototype.init = function () {
        this.dom = document.createElement('table'); // 创建表格
        var tr, td;
        // 遍历行和列
        for (var i = 0; i < this.row; i++) {
            tr = document.createElement('tr');  // 创建行
            for (var j = 0; j < this.col; j++) {
                td = document.createElement('td');  // 创建列
                tr.appendChild(td);     // 把列追加到行
            }
            this.dom.appendChild(tr);   // 把行追加到表格
        }
        document.querySelector('#app').appendChild(this.dom);   //把表格追加到div里
    }
    // 遍历表格,清除表格上的颜色
    Game.prototype.clear = function () {
        for (var i = 0; i < this.row; i++) {
            for (var j = 0; j < this.col; j++) {
                this.dom.getElementsByTagName('tr')[i].getElementsByTagName('td')[j].style.background = '';
                this.dom.getElementsByTagName('tr')[i].getElementsByTagName('td')[j].innerHTML = '';
            }
        }
    }
    // 设置颜色的方法 让表格的第几行,第几列设置什么颜色
    Game.prototype.setColor = function (row, col, color) {
        this.dom.getElementsByTagName('tr')[row].getElementsByTagName('td')[col].style.background = color;
    }
    // 设置蛇头
    Game.prototype.setColorHead = function (row, col) {
        var img = document.createElement('img');
        img.src = 'images/snake.png';
        img.className = 'snake';
        this.dom.getElementsByTagName('tr')[row].getElementsByTagName('td')[col].appendChild(img);
        // this.dom.getElementsByTagName('tr')[row].getElementsByTagName('td')[col].style.backgroundColor='transparent'
        switch (this.d) {
            case 'R':   //右
                    break;
            case 'D':   //下
                    img.style.transform = 'rotate(90deg)';
                    break;
            case 'L':   //左
                    img.style.transform = 'rotate(180deg)';
                    break;
            case 'U':   //上
                    img.style.transform = 'rotate(-90deg)';
                    break;
        }
    }
    // 渲染食物
    Game.prototype.setHTML = function (row, col) {
        this.dom.getElementsByTagName('tr')[row].getElementsByTagName('td')[col].style.backgroundImage = 'url(./images/food.png)';
    }
    // 设置键盘的事件监听
    Game.prototype.bindEvent = function () {
        var self = this;
        document.addEventListener('keydown', function (e) {
            // 用ASCII码值判断键盘方向
            switch (e.keyCode) {
                case 37:    //左
                    if (self.snake.direction == 'R') return;    // 先进行判断,如果当前的方向是向右移动,此时我们不能按左键
                    self.snake.changeDirection('L');
                    self.d = 'L';
                    break;
                case 38:    //上
                    if (self.snake.direction == 'D') return;    // 先进行判断,如果当前的方向是向下移动,此时我们不能按上键
                    self.snake.changeDirection('U');
                    self.d = 'U';
                    break;
                case 39:    //右
                    if (self.snake.direction == 'L') return;    // 先进行判断,如果当前的方向是向左移动,此时我们不能按右键
                    self.snake.changeDirection('R');
                    self.d = 'R';
                    break;
                case 40:    //下
                    if (self.snake.direction == 'U') return;    // 先进行判断,如果当前的方向是向上移动,此时我们不能按下键
                    self.snake.changeDirection('D');
                    self.d = 'D';
                    break;
            }
        })
    }
    Game.prototype.start = function () {
        // 帧编号
        this.f = 0;
        // 定时器里面的核心就是游戏的渲染本质:清屏-更新-渲染
        this.timer = setInterval(function () {
            game.f++;
            // document.getElementById('f').innerHTML = '帧编号:' + game.f;
            // document.getElementById('score').innerHTML = '分数:' + game.score;
            // 清屏
            game.clear();
            // 蛇的运动(更新)
            // 蛇的更新速度,当蛇变长的时候,速度要加快
            var during = game.snake.body.length < 30 ? 30 - game.snake.body.length : 1;
            game.f % during == 0 && game.snake.update();
            // game.snake.update();
            // 渲染蛇
            game.snake.render();
            // 渲染食物
            game.food.render();
        }, 10)
    }

    Snake.js

    function Snake() {
        // 蛇的初始化身体
        this.body = [
            { 'row': 3, 'col': 5 },
            { 'row': 3, 'col': 4 },
            { 'row': 3, 'col': 3 },
            { 'row': 3, 'col': 2 }
        ];
        this.direction = 'R';   //信号量,设置运动方向
        this.willDirection = 'R';   //即将改变的方向,目的就是为了方向出现原地调头的情况
    }
    Snake.prototype.render = function () {
        // 蛇头的渲染
        game.setColorHead(this.body[0].row, this.body[0].col);
        // 蛇身的渲染
        for (var i = 1; i < this.body.length; i++) {
            game.setColor(this.body[i].row, this.body[i].col, '#649c49')
        }
    }
    // 蛇的运动
    Snake.prototype.update = function () {
        this.direction = this.willDirection;
        switch (this.direction) {
            case 'R':   //右
                this.body.unshift({ 'row': this.body[0].row, 'col': this.body[0].col + 1 });
                break;
            case 'D':   //下
                this.body.unshift({ 'row': this.body[0].row + 1, 'col': this.body[0].col });
                break;
            case 'L':   //左
                this.body.unshift({ 'row': this.body[0].row, 'col': this.body[0].col - 1 });
                break;
            case 'U':   //上
                this.body.unshift({ 'row': this.body[0].row - 1, 'col': this.body[0].col });
                break;
        }
        // 死亡的判断,超出了表格边缘的部分
        if (this.body[0].col > game.col - 1 || this.body[0].col < 0 || this.body[0].row > game.row - 1 || this.body[0].row < 0) {
            alert('撞到墙了哦,一共吃掉了' + game.score + '颗草莓');
            this.body.shift();
            clearInterval(game.timer);
            location.reload();
        }
        // 自己撞到自己的时候会判定死亡
        for (var i = 1; i < this.body.length; i++) {
            // 如果当前蛇的头部和身体的某一个部位的 row 和 col 完全重合的时候
            if (this.body[0].row == this.body[i].row && this.body[0].col == this.body[i].col) {
                alert('撞到自己了,吃掉了' + game.score + '颗草莓');
                this.body.shift();
                clearInterval(game.timer);
                location.reload();
            }
        }
        // 蛇吃食物
        // 判断如果当前的蛇的头部没有和食物进行重合,就代表此时没有吃到食物,此时就进行尾部删除,如果重合了就代表迟到了,此时我们不进行删除尾部
        if (this.body[0].row == game.food.row && this.body[0].col == game.food.col) {
            // 此时情况是只有头部增加了,尾部没有删除
            game.food = new Food(game);    //创建新的食物
            game.score++;
            game.f = 0;
        } else {
            this.body.pop();    //删除数组最后一个元素
        }
    }
    // 蛇的方向改变,防止的是在一次渲染之前会出现调头的情况
    Snake.prototype.changeDirection = function (d) {
        this.willDirection = d;
    }

    Food.js

    function Food(gameSnake) {
        var self = this;
        // 下面的 do-while 循环语句作用是先创建一个 row 和 col 然后判断这个 row 和 col 是否在蛇的身上
        do {
            // 食物的位置
            this.row = parseInt(Math.random() * gameSnake.row)
            this.col = parseInt(Math.random() * gameSnake.col)
        } while ((function () {
            // 遍历蛇的 row col 然后和 food 新随机出来的 row col 进行判断,是否重合
            for (var i = 0; i < gameSnake.snake.body.length; i++) {
                if (self.row == gameSnake.snake.body[i].row && self.col == gameSnake.snake.body[i].col) {
                    return true;
                }
            }
            return false;
        })());
    }
    Food.prototype.render = function () {
        game.setHTML(this.row, this.col);
    }

    八、图片

    接下里我把我用的图片放到这个地方,喜欢的宝宝们也可以直接拿去用!

    JavaScript怎么实现精美贪吃蛇游戏

    JavaScript怎么实现精美贪吃蛇游戏

    JavaScript怎么实现精美贪吃蛇游戏

    JavaScript怎么实现精美贪吃蛇游戏

    到此,相信大家对“JavaScript怎么实现精美贪吃蛇游戏”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI