您当前的位置:首页 > 网站建设 > javascript
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 | ajax | jQuery | 小程序 |

JavaScript 精美贪吃蛇实现流程

51自学网 2022-02-21 13:36:39
  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>    <!-- <h3 id="f">帧编号:0</h3>    <h3 id="score">分数:0</h3> -->    <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 贪吃蛇内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net!


下载地址:
JavaScript
javascript&nbsp;Three.js创建文字初体验
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。