In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the knowledge of "how to write a gluttonous Snake game with JavaScript". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
First of all, we need to determine the function of the gluttonous snake.
1. Control the movement direction of the snake through the top and bottom of the keyboard.
two。 Boundary determination, that is, if the snakehead exceeds the boundary, the game is over.
3. Collision determination, that is, the snake head touches the piece of food.
4. Add 1 to the food points.
Specific implementation 1. Html code score 2. CSS code * {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;} three. Begin to implement specific functions
1. First get the node and set the global variable
/ / get 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 variable * / var timer; var arr = [] / / the array where the snake is stored is var num = 0; / / the length of the array is var snakeBody; / / one food at a time, increasing the body.
two。 Set the keystroke event and judge the boundary collision. The game ends when the collision occurs. I have a problem with this piece of code, that is, when I use if () {return} to jump out of the event, it ends all the code, and the rest of the code will not be executed, and then I replace it with switch () {case: break;} to achieve the effect.
/ / set button event _ document.onkeydown = function (e) {var evt = window.evnet | | e; switch (evt.keyCode) {case 37: / / left clearInterval (timer); timer = window.setInterval (runLeft, 10) / / left-moving timer function runLeft () {if (snake.offsetLeft > 0) {snake.style.left = snake.offsetLeft-1 + 'px'; / / implement self-moving snake.style.top = snake.offsetTop +' px' / / height invariant arr.push ([snake.offsetLeft, snake.offsetTop]); / / each time you move 1px, store the position in the array num++; / / the corresponding array length plus 1} else {clearInterval (timer) / / clear timer alert ('you die') / / pop-up failure message _ document.onkeydown = null / / end key}} break / / end the current key 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.封装一个函数,随机生成食物位置,第一次粗心忘记加单位,看网页没效果,才知道忘记加单位了 function pos() { food.style.left = parseInt(Math.random() * 630) + 'px'; food.style.top = parseInt(Math.random() * 580) + 'px'; } 4.封装一个碰撞判定函数,使其碰撞时,食物消失,蛇的身体增加一块。这里遇到一个定时器问题,第一次写的时候,我的定时器清除标识和之前的定时器标识一致,导致蛇会上下左右抖动,经过后面不停的修改,最终找到错误。 var timer1 = setInterval(eat, 10); //设置一个碰撞的时间器 function eat() { snakeCrashFood(snake, food); //传入参数 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"); //生成新的div snakeBody.setAttribute("class", "body"); //给新的div添加类名 playground.appendChild(snakeBody); //添加一节新的身体 pos(); //让食物重新随机出现 setInterval(follow, 10); //动态地改变新的身体的位置 } } } 5.设置蛇的身体跟随,获得蛇身体的数组,新的身体相对于上一个身体的第20个数组的位置。这里我遇到了一个数组越界问题。最开始初始num值为0,place=20,所以第一次身体的增加arr[num-place][0]前面的索引是从负数开始,在通过老师的指导,增加一个判定,解决了这个问题。 function follow() { /*获得增加的身体的数组*/ var bodyNum = document.getElementsByClassName("body"); score[xss_clean] = bodyNum.length; var place = 0; /*数组每移动1px,新的身体的位置就是相对于前一个身体的第20个数组的位置,后面依次加等*/ // 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 - place >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 ("= =")} "how to write a Snake Game with JavaScript" ends here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.