This article example shares the specific code of JavaScript to implement the greedy snake for your reference. The specific content is as follows First we need to determine the functions that the snake should have 1. Use the up, down, left, and right keys on the keyboard to control the snake's movement direction 2. Boundary determination, that is, the game ends when the snake head exceeds the boundary 3. Collision detection, that is, the snake head and the food block touch each other 4. Eat food and your points will increase by 1 Specific implementation1.html code<div class="container"> <!--Snake moving playground--> <div id="playground"> <!--Little Snake--> <div id="snake"></div> <!--Food--> <div id="food"></div> </div> <!--Record score--> <div id="menu"> <div>Score<span id="score"></span></div> </div> </div> 2.css code<style> * { padding: 0; margin: 0; } .container { width: 800px; height: 600px; margin: 0 auto; } #playground { width: 650px; height: 100%; background-color: cadetblue; float: left; position: relative; } #menu { width: 150px; height: 100%; background-color: darkcyan; float: left; } #snake { width: 20px; height: 20px; background-color: #d3e0d7; position: absolute; left: 0; top: 0; } #food { width: 20px; height: 20px; background-color: #027766; position: absolute; } .body { width: 20px; height: 20px; background-color: #178b9a; position: absolute; ; top: 0; left: 0; } #score { font-size: 30px; font-weight: bold; color: black; } #menu div { font-size: 20px; font-weight: bold; margin-left: 20px; } #hqx { width: 100px; height: 50px; margin: 0 auto; } #inp { border: 0; width: 100px; height: 50px; background-color: coral; } </style> 3. Start implementing specific functions1. Get the node first and set the global variable //Get the node var snake = document.getElementById("snake"); var food = document.getElementById("food"); var playground = document.getElementById("playground"); var score = document.getElementById('score'); // var inp = document.getElementById('inp') /*Set global variables*/ var timer; var arr = []; //Array to store the position of the snake var num = 0; //Length of the array var snakeBody; //Each time you eat a food, you will increase the body 2. Set up key events and determine boundary collisions. The game ends when a collision occurs. I encountered a problem with this piece of code. When I used if(){return} to jump out of the event, it would end all the code and the following code would not be executed. Then I changed it to switch(){case: break;} and it worked. //Set key event document.onkeydown = function (e) { var evt = window.evnet || e; switch (evt.keyCode) { case 37: //left clearInterval(timer); timer = window.setInterval(runLeft, 10); //Timer to move to the left function runLeft() { if (snake.offsetLeft > 0) { snake.style.left = snake.offsetLeft - 1 + 'px'; //Achieve self-movement snake.style.top = snake.offsetTop + 'px'; //No change in height arr.push([snake.offsetLeft, snake.offsetTop]); //Every time you move 1px, store the position in the array num++; //Add 1 to the corresponding array length } else { clearInterval(timer); //Clear timer alert('you die') //Pop up failure message document.onkeydown = null //End button } } break; //End current keystroke case 38: //clearInterval(timer); timer = window.setInterval(runTop, 10); function runTop() { if (snake.offsetTop > 0) { snake.style.top = snake.offsetTop - 1 + 'px'; snake.style.left = snake.offsetLeft + 'px'; arr.push([snake.offsetLeft, snake.offsetTop]); num++; } else { clearInterval(timer); alert('you die') document.onkeydown = null } } break; case 39: //right clearInterval(timer); timer = window.setInterval(runRight, 10); function runRight() { if (snake.offsetLeft < 630) { snake.style.left = snake.offsetLeft + 1 + 'px'; snake.style.top = snake.offsetTop + 'px'; arr.push([snake.offsetLeft, snake.offsetTop]); num++; } else { clearInterval(timer); alert('you die') document.onkeydown = null } } break; case 40: //clearInterval(timer); timer = window.setInterval(runBottom, 10); function runBottom() { if (snake.offsetTop < 580) { snake.style.top = snake.offsetTop + 1 + 'px'; snake.style.left = snake.offsetLeft + 'px'; arr.push([snake.offsetLeft, snake.offsetTop]); num++; } else { clearInterval(timer); alert('you die') document.onkeydown = null } } break; } 3. Encapsulate a function to randomly generate food positions. The first time I was careless and forgot to add the unit, I looked at the web page and it didn’t work, then I realized I forgot to add the unit function pos() { food.style.left = parseInt(Math.random() * 630) + 'px'; food.style.top = parseInt(Math.random() * 580) + 'px'; } 4. Encapsulate a collision judgment function so that when a collision occurs, the food disappears and a piece of the snake's body is added. There was a timer problem here. When I wrote it for the first time, my timer clear flag was the same as the previous timer flag, which caused the snake to shake up and down and left and right. After continuous modifications, I finally found the error. var timer1 = setInterval(eat, 10); //Set a collision timer function eat() { snakeCrashFood(snake, food); //Input parameters function snakeCrashFood(obj1, obj2) { var obj1Left = obj1.offsetLeft; var obj1Width = obj1.offsetWidth + obj1.offsetLeft; var obj1Top = obj1.offsetTop; var obj1Height = obj1.offsetHeight + obj1.offsetTop; var obj2Left = obj2.offsetLeft; var obj2Width = obj2.offsetWidth + obj2.offsetLeft; var obj2Top = obj2.offsetTop; var obj2Height = obj2.offsetHeight + obj2.offsetTop; if (!((obj1Width < obj2Left) || (obj2Width < obj1Left) || (obj1Height < obj2Top) || ( obj2Height < obj1Top))) { snakeBody = document.createElement("div"); //Generate a new div snakeBody.setAttribute("class", "body"); //Add a class name to the new div playground.appendChild(snakeBody); //Add a new body pos(); //Make the food reappear randomly setInterval(follow, 10); //Dynamically change the position of the new body } } } 5. Set the snake's body to follow, get the array of the snake's body, and the position of the new body relative to the 20th array of the previous body. Here I encountered an array out of bounds problem. At the beginning, the initial num value is 0, and place=20, so the index before the first increase of arr[num-place][0] starts from a negative number. With the guidance of the teacher, a judgment is added to solve this problem. function follow() { /*Get the array of added bodies*/ var bodyNum = document.getElementsByClassName("body"); score.innerHTML = bodyNum.length; var place = 0; /*Every time the array moves 1px, the position of the new body is the position of the 20th array relative to the previous body, and so on*/ // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1") // console.log("arr : ==" + arr) // console.log("num : ==" + num) //2 for (var i = 0; i < bodyNum.length; i++) { // console.log("bodyNum.length : ==" + bodyNum.length) place += 20; // console.log("place : ==" + place)//20 // console.log("num - place : ==" + (num - place)) //-18 // bodyNum[i].style.left = arr[num - place][0] + 'px'; // bodyNum[i].style.top = arr[num - place][1] + 'px'; if (num - places > 0) { bodyNum[i].style.left = arr[num - place][0] + 'px'; bodyNum[i].style.top = arr[num - place][1] + 'px'; } } // console.log("num555 : ==" + num) // console.log("============================================") } The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM. You may also be interested in:
|
<<: Centos7 implements sample code for restoring data based on MySQL logs
>>: Detailed graphic tutorial on how to enable remote secure access with Docker
This article example shares the specific code of ...
Table of contents environment: 1. Docker enables ...
Preface NAT forwarding: Simply put, NAT is the us...
Preface As you all know, we have encountered many...
introduction: Slider drag verification is now use...
This article example shares the specific code of ...
This article example shares the specific code of ...
Table of contents 1. Create HTML structure 2. Cre...
Table of contents 1. MySQL data backup 1.1, mysql...
1. Review The Buffer Pool will be initialized aft...
The so-called three-column adaptive layout means ...
symptom I set a crontab task on a centos7 host, b...
Enable the service when you need it, and disable ...
Table of contents Preface Basic Usage grammar Err...
The project requirements are: select date and tim...