Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the exquisite Snake Game with JavaScript

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to realize the exquisite gluttonous snake game in JavaScript". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to realize the exquisite gluttonous snake game with JavaScript.

Without saying much, let's first take a look at the final presentation.

It is legendary to know what operation is only after reading it.

Next, don't brag to talk about the actual operation!

First of all, we need to know that the so-called gluttonous snake is nothing more than the color of walking on the table! The initial effect is shown in the following figure

Of course, it is operated with an array in this place, and it is also encapsulated with a constructor.

Three js files are encapsulated in this place, which are used to write food, snake, and our intermediary Game.js files!

As I just said, writing gluttonous snakes is a process from scratch, so at the beginning there is nothing in our index.html, only a div box, and other tables, snakes and foods are created later with functions.

First, create html structure

Here is the initial code in our body:

Var game=new Game (); II. Create a table

The first step from scratch is, of course, to append our form to the page and have a general framework! In this way, you can see the table shown in the picture above, and it seems that every next step is worth it!

Function Game () {this.row = 25; / / number of rows this.col = 25; / / number of columns this.init (); / / initialize node} Game.prototype.init = function () {this.dom = document.createElement ('table'); / / create table var tr, td; / / traverse rows and columns 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 贪吃蛇 * { 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; }

Var game = null; var flag = true; var suspend = document.querySelector ('.start'); 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') [xss_clean] = 'frame number:' + game.f; / / document.getElementById ('score') [xss_clean] =' score:'+ game.score / / clear the screen game.clear (); / / the movement of the snake (update) / / the update speed of the snake, when the snake grows longer, speed up 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) }) }) Game.jsfunction 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][xss_clean] = ''; } }}// 设置颜色的方法 让表格的第几行,第几列设置什么颜色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')[xss_clean] = '帧编号:' + game.f; // document.getElementById('score')[xss_clean] = '分数:' + 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.jsfunction 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.jsfunction 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);}八、图片 接下里我把我用的图片放到这个地方,喜欢的宝宝们也可以直接拿去用!

At this point, I believe you have a deeper understanding of "how to achieve the exquisite gluttonous Snake game in JavaScript". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report