How to use JavaScript to write the Snake

Snake we all played, but you will make thing? It sounds like hard look, in fact very simple man of few words said, directly on the code
we write dom first structure

<div id="content">
<div id="snake">
<div class="box head"></div>
<div class="box"></div>

        </div>

    </div>

Which, content for the entire layout of the big box, snake is a snake inside the box is his body, in order to distinguish the head to the first box we added a name to distinguish head, then let's add css

<style>
.box{
width: 60px;
height: 60px;
background-color: red;
position:absolute;
left: 0;
top: 0;
line-height: 60px;
}
.head{
background-color: yellowgreen;
}
</style>

We each section to the snake's width and height set to 60 pixels, and gave a position, because if we do not locate, then could not get him out of the document flow (floating up in the page), and follow-up can not come through left and top judge his coordinates.

Good so we got a lovely snake (natural goose did not see where lovely - -). what? You ask me which went to his head, very simple, in addition to the element after positioning the elements behind will overwrite the previous element, so just head and body overlap you can not see it.
Then we have to let the snake move right, stock code query www.gendan5.com/topic/lcSearch.html So how do we let him move it? The principle is very simple, we can set a timer every time let him move about, and how to let him move it, only need to set a value, so that the value of every movement on + = 60, then up and down by judge move around or move to the left to the elements and top assignment. We write the code logic, came out the following code

<script>
var boxs = document.querySelectorAll(".box");
var snake_x = 0;
var snake_y = 0;
var turn = "right";
setInterval(function(){
snakeMove();
},100)
function snakeMove(){
switch( turn ){
case "right": snake_x += 60;break;
case "left" : snake_x -= 60;break;
case "top" : snake_y -= 60;break;
case "bottom": snake_y += 60;break;
}

        for(var i = boxs.length - 1; i > 0 ; i --){
            boxs[i].style.left = boxs[i - 1].style.left;
            boxs[i].style.top = boxs[i - 1].style.top;

        }
        boxs[i].style.left = snake_x + "px";
        boxs[i].style.top  = snake_y + "px";

    }

document.onkeydown = function(evt){
var e = evt || event;
var keyCode = e.keyCode || e.which;
switch( keyCode ){
case 37 : turn = "left";break;
case 38 : turn = "top";break;
case 39 : turn = "right";break;
case 40 : turn = "bottom";break;
}
}

</script>

The above code, we give the x and y coordinates of the initial position of the snake are set to 0, and the default initial right away, by inputting direction keys on the keyboard to change his direction. Among them, the difficulty lies

for(var i = boxs.length - 1; i > 0 ; i --){
boxs[i].style.left = boxs[i - 1].style.left;
boxs[i].style.top = boxs[i - 1].style.top;

        }
        boxs[i].style.left = snake_x + "px";
        boxs[i].style.top  = snake_y + "px";

This block of code, the purpose of this code is to follow the elements behind the front walk, it is to let every piece of the body of a snake and went on to a movement, non-farm payrolls and then finally give head to snake_x and snake_y the current values can, thus forming a first (head) is the coordinate value snake_x, snake_y changes in real time, the value of the second block before the first block, the third block to the second block before the value. . . So get a head body to go along with the effect of


But when you lose the code into a running you'll find that this snake was too naughty, but also unlimited go forward after that went to the border, and that it would not do ah, can not let the snake is not run, so you have to plus a snake border

   var snake_x_max = document.documentElement.clientWidth ;
    var snake_y_max = document.documentElement.clientHeight;

if(snake_x > snake_x_max){
snake_x = 0;
}
if(snake_x < 0){
snake_x = snake_x_max;
}
if(snake_y > snake_y_max){
snake_y = 0;
}
if(snake_y < 0){
snake_y = snake_y_max;
}

Here we set the maximum x and y for the current window width and height, and then determines if statement, if the current coordinate is greater than the maximum, the current talk normalized coordinates 0, 0 is less than it (i.e. to the left border went ), stores the current coordinate set to the maximum, so that it can obtain a boundary

Do you think this way to get away it? nonono, no food to eat snakes, how can it be called Snake, it is no soul clatter. Here we begin to make food (can not let the snake hungry right).

<div id="food">

        </div>

Then give him a css

#food{
width: 60px;
height: 60px;
position: absolute;
background: greenyellow;
}

Then what elements and binding his left and top value is set within a range of random numbers, which can be done to generate a random position

var fd=document.getElementById("food");
fd.style.left=Math.random()snake_x_max+"px";
fd.style.top=Math.random()
snake_y_max+"px";

Good food so we get a randomly generated

But our food and the snake seemed to have little interest in it, after passing and will not eat, so we have to give him a right collision detection, collision detection logic is very simple, just to make left and head value of food the absolute value of the subtraction value of the left <= size of the food, and the food top head portion of the top value and the value of subtracting the absolute value of <= size of the food, and the like is provided so as less than equal to judge if the direct use, it must two elements completely overlap the job, what we need is met even if the edge of late, so that phase is reduced to a value equal to two to do. And then determine when the head collides with the food, the snake's body parts out into a cloned body of the snake inside, and let the position of the food to refresh (applicable for the lazy cloning method, this method only applies when the lazy snake start when a body comes, comes not start if the snake's body, we can not clone an existing body, only to create a new body by createElement block out and added className then added to the parent element to the job). Here we put logic into code

var dl=snake_x;
var dt=snake_y;
var fl=fd.style.left;
var ft=fd.style.top;
var dv=document.querySelectorAll("#snake div");
var sk=document.getElementById("snake");
var a2=Number(fl.substring(0,fl.indexOf("px")));
var b2=Number(ft.substring(0,ft.indexOf("px")));
if(Math.abs(dl-a2)<=60&&Math.abs(dt-b2)<=60){
fd.style.left=Math.random()1000+"px";
fd.style.top=Math.random()
800+"px";
sk.appendChild(dv[1].cloneNode());
boxs = document.querySelectorAll(".box");

    }

Wherein a method that long list of substring is because the format of the acquired value is, for example, left and top "200px" Such an array can not be mathematical operations, it should px to cut off, and the remaining characters string "200" into a number types can perform mathematical operations.

Guess you like

Origin blog.51cto.com/14513127/2478905