Implementation code of JavaScript snake

  • 2021-11-14 04:47:40
  • OfStack

This article example for everyone to share the JavaScript implementation of the snake specific code, for your reference, the specific content is as follows

First of all, we should determine the function of gluttonous snakes

1. Control the moving direction of the snake through the keyboard up, down, left and right

2. Boundary judgment, that is, the snake head exceeds the boundary and the game ends

3. Collision judgment, that is, the snake head touches the food block

4. Eat food points plus 1

Concrete realization

1. html code


<div class="container">
        <!-- Playground where small snakes move -->
        <div id="playground">
            <!-- Small 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 functions

1. Get the node first 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')
        /* Setting global variables */
        var timer;
        var arr = []; // An array of locations where snakes are stored 
        var num = 0; // Length of Array 
        var snakeBody; // Every time you eat the tune 1 A food, an increase in the body 

2. Set the key event and judge the boundary collision, and the game ends when the collision occurs. I had a problem with this one piece of code. When I used if () {return} to jump out of the event, it ended all the code, and the following code would not be executed. Then I switched to switch () {case: break;} The effect will be achieved


 // Set key events 
        document.onkeydown = function (e) {
            var evt = window.evnet || e;
            switch (evt.keyCode) {
                case 37: // Left 
                    clearInterval(timer);
                    timer = window.setInterval(runLeft, 10); // Timer moving to the left 
                    function runLeft() {
                        if (snake.offsetLeft > 0) {
                            snake.style.left = snake.offsetLeft - 1 + 'px'; // Realize one's own movement 
                            snake.style.top = snake.offsetTop + 'px'; // Constant height 
                            arr.push([snake.offsetLeft, snake.offsetTop]); // Every move 1px The location is stored in an array 
                            num++; // The length of the corresponding array is added 1
                        } else {
                            clearInterval(timer); // Clear timer 
                            alert('you die') // Pop up failure message 
                            document.onkeydown = null // End button 
                        }
                    }
                    break; // End the current key 
                case 38: // Upper 
                    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: // Under 
                    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, randomly generated food location, the first careless forget to add units, look at the web page has no effect, just know forget to add units


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 it collides, the food disappears and the snake's body increases by 1 piece. I encountered a timer problem here. When I wrote it for the first time, my timer clearing mark and the previous timer mark 1 caused the snake to shake up and down, left and right. After constant modification, I finally found the error.


var timer1 = setInterval(eat, 10); // Settings 1 A collision timer 
            function eat() {
                snakeCrashFood(snake, food); // Pass in 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"); // To the new div Add a class name 
                        playground.appendChild(snakeBody); // Add 1 Knock a new body 
                        pos(); // Let food reappear randomly 
                        setInterval(follow, 10); // Dynamically change the position of the new body 
                    }
                }
            }

5. Set the snake's body to follow, get the snake's body array, 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 in front of arr [num-place] [0] for the first body increase starts from a negative number. Under the guidance of the teacher, one judgment is added to solve this problem.


function follow() {
                /* Get an array of increased bodies */
                var bodyNum = document.getElementsByClassName("body");
                score.innerHTML = bodyNum.length;
                var place = 0;
                /* Every move of the array 1px, The position of the new body is relative to the front 1 The first of a body 20 The position of the array, followed by, etc. */
                // 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("===========================================")
            }

Related articles: