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 gluttonous Snake Mini Game by JS+Canvas

2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you how to achieve gluttonous Snake Mini Game, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!

First of all, there are general things to consider:

1. If there is no snake, it is not a gluttonous snake.

two。 Then there should be a map (snakes can't go up to heaven).

3. You cannot turn around horizontally / vertically (if you want to turn around, you need to change direction and move at least one frame).

4. Food (otherwise how to be gluttonous).

5. Get longer after eating the food (that's the essence).

PS:~ now when I think about it, that's all I really thought of (⊙ thinking ⊙).

After the idea, let's get to work!

How do I do that? From big to small, first draw a rectangle to make a map, but I think it is too ugly, so I draw a picture:

Context.beginPath (); var bgImg = new Image (); bgImg.src = "img/background.png"; context.drawImage (bgImg, 0,0,600,600); context.closePath ()

Now we have a map.

There seems to be something missing on the map. Yes, it is a gift, so now that we generate gifts, the question arises: how many gifts are there at most, where to generate them, and when to generate them.

I temporarily define it as: up to 2, random location generation, up to 2 when the number of gifts is less than 2.

Then it's very simple. In the picture above, the range that allows snakes to move is 14 trees (two surrounding trees are walls), and then 16 trees = 600px. It's easy for us to get how wide each grid is.

So, we just need to define a method that randomly generates 1-14 integers to easily find where it should be generated:

/ / Random number function selectfrom () {return Math.floor (Math.random () * 14 + 1);}

Then multiply the calculated number by the width of each grid to find out the specific X coordinates generated. Because it is a square, so is Y:

Var x = selectfrom () * (600x16); var y = selectfrom () * (600Univer 16)

And every time you get a set of gift coordinates, you need to store them in an array (which will be of great use later). As for drawing rectangles is too basic, I won't talk about it.

And Now, we have a gift, we have a map, we need a snake, so the question comes again: how long the snake was born, where it was born, how it died, how it moved, how it turned, how to judge how long it grew when it was eaten, where it grew when it was eaten.

Birth snake length: in the actual writing process, I found that the default length 1 and 2 can not well reflect the "snake turn", so it is defined as 3, and all the coordinates of the snake body need to be recorded in the array.

Place of birth: set a location in the center of the map or set your own location (divided by the grid). The method of obtaining XY coordinates has been mentioned above and will not be repeated.

Mode of death: encounter obstacles, or (eat yourself) the head of the snake touches the body of the snake.

How to move: record the current direction (0, 1, 2, 3, default 1) by defining a global variable, and use a timer to drive the snake movement.

Turn mode: add keyboard keys to detect events and modify-record all variables of the direction when the key is pressed.

How to tell if a gift is eaten: every time the snakehead moves, go through the gift collection (as mentioned above), and if the next coordinate to which the snakehead is about to move coincides with it, it is considered to have eaten the gift.

Where does the gift grow after eating it: adding it directly to the head may lead to accidental death, so I decided that the next move after eating the gift would not eliminate the snake tail (the last element).

With the above idea, we can begin to define some common variables that may be used:

Var canvas = document.getElementById ("mycanvas"); / / canvas body var context = canvas.getContext ("2d"); var timer;// timer const WIDTH = canvas.width;// canvas width const HEIGHT = canvas.height;// canvas height const XSUM = 16; / / canvas width divided into several squares const YSUM = 15; / / canvas height divided into several grids const MAXFFOD = 2; / / maximum number of food var score = 0 position / define record game score var xsplit = WIDTH / XSUM / / x width of each grid var ysplit = HEIGHT / YSUM; / / y height of each grid var foodcount = 0; / / current amount of food var sinak = []; / / gluttonous snake coordinate set var get = []; / / gift coordinate set var MoveTo = 1; / / moving direction defaults to 1 (right)

With these variables, do you find that a lot of things make sense?

Let's start by drawing snakes:

/ / draw Snake function drawsinak (sl) {/ / sl default length context.beginPath (); context.fillStyle = "# 000"; var ling = 0; / / Snake printed length for (var r = 0; r

< sinak.length; r++) { context.fillRect(sinak[r].split(',')[0], sinak[r].split(',')[1], xsplit, ysplit); ling++; } if (ling == 0) { for (var i = 0; i < sl; i++) { context.fillRect(xsplit * (7 - i), ysplit * 6, xsplit, ysplit); //默认出生点:7,6默认中心点 sinak.push(xsplit * (7 - i) + ',' + ysplit * 6); } } context.fill(); context.closePath();} 可以看到我将生成的蛇的坐标都计入了数组内,生成的礼物自然也要计入: context.beginPath(); var x = selectfrom(XSUM - 2) * xsplit; var y = selectfrom(YSUM - 2) * ysplit; context.fillStyle = "red"; for (var i = 0; i < get.length; i++) { context.fillRect(get[i].split(',')[0], get[i].split(',')[1], xsplit, ysplit); context.fill(); foodcount++; } if (MAXFFOD >

Foodcount) {context.fillRect (x, y, xsplit, ysplit); context.fill (); foodcount++; get.push (x +','+ y);} context.closePath ()

What's more important next is the movement of the snake, as well as eating gifts and triggering death judgments:

/ / move method / / [c] move up, right, down, left 0123function sinakMove (c) {context.beginPath (); / / head var tou = sinak [0] by default; / / head var weiba = sinak [sinak.length-1]; / / tail var oldX = tou.split (',') [0]; / / Old X coordinate of head var oldY = tou.split (',') [1] / / the old Y coordinates of the head var newX = 0; / the latest X coordinates of the head var newY = 0; / the latest Y coordinates of the head / / calculate the latest XY coordinates of the head switch (c) {case 0: newX = oldX; newY = oldY-ysplit; break; case 1: newX = (oldX-0) + xsplit NewY = oldY; break; case 2: newX = oldX; newY = (oldY-0) + ysplit; break; case 3: newX = oldX-xsplit; newY = oldY; break;} var flag = 0 / / have you eaten the gift? no one has / / if you have eaten the gift, the last element for (var I = 0; I < get.length; iTunes +) {if (newX = = GET [I] .split (',') [0] & & newY = = GET [I] .split (',') [1]) {sinak.unshift (newX +','+ newY); foodcount-- / / reduce the gift count by 1 get.splice (I, 1); / / clear the gift flag = 1;}} / / if you don't eat the gift, judge whether you encounter obstacles or eat your own if (flag = = 0) {for (var I = 0; I < sinak.length) ) {if (newX = = Sinak [I] .split (',') [0] & & newY = = Sinak [I] .split (',') [1]) {if (confirm ('ate yourself), the game failed! Do you want to start over?') {location.reload (true);} else {context.clearRect (0,0, WIDTH, HEIGHT);} if (xsplit * (XSUM-2) < newX | | ysplit * (YSUM-2) < newY | | newX = = 0 | newY = = 0) {if (confirm ('hit the wall, the game failed! Do you want to start over?') {location.reload (true);} / / if you don't get a gift, do normal mobile if (flag = = 0) {sinak.unshift (newX +','+ newY); sinak.splice (sinak.length-1,1);} / draw snake for (var r = 0; r < sinak.length) Ysplit +) {context.fillRect (Sinak [r] .split (',') [0], Sinak [r] .split (',') [1], xsplit, ysplit);} context.closePath ();}

Control the direction of the snake:

/ / keyboard event _ document.onkeydown = function (event) {var e = event | | window.event | | arguments.callee.caller.arguments [0]; var move = 0; / / moving direction if (e & & e.keyCode = = 37) {/ / left move = (MoveTo = = 1? 1: 3);} else if (e & & e.keyCode = = 38) {/ / move = (MoveTo = 2? 2: 0) } else if (e & & e.keyCode = = 39) {/ / right move = (MoveTo = = 3: 1);} else if (e & & e.keyCode = = 40) {/ / Lower move = (MoveTo = = 0: 2);} else if (e & & e.keyCode = = 32) {/ / pause game clearInterval (timer);} MoveTo = move; / / modify current movement direction}

Error prevention is done here, and when the snake is moving in a certain direction, it is invalid to enter the opposite direction directly. For example, the snake is walking to the right, it is invalid to press the ← key directly at this time, it is still going right.

Along the way to do this, I believe that everyone's gluttonous snake can play a normal game, but I do this is very rough, you can add some of your own ideas, such as:

Score customs clearance, after customs clearance by speeding up the speed of the snake to increase the difficulty.

Randomly generate a variety of fruits, such as accelerated fruit, double growth fruit and so on.

Join WebSocket to realize the online version of Snake.

These are all the contents of the article "how to achieve gluttonous Snake Mini Game by JS+Canvas". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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