JavaScript Snake Implementation Code

JavaScript Snake Implementation Code

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 implementation

1.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 functions

1. 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:
  • JS implements the snake game
  • JavaScript to achieve the idea of ​​​​snake game
  • JavaScript implementation of classic snake game
  • Use js to write a simple snake game
  • JavaScript to implement the web version of the snake game
  • Implementing the Snake Game in JavaScript
  • Native js to realize a simple snake game
  • Writing Snake Game with Native JS
  • js to implement the snake game with comments
  • JavaScript exquisite snake implementation process

<<:  Centos7 implements sample code for restoring data based on MySQL logs

>>:  Detailed graphic tutorial on how to enable remote secure access with Docker

Recommend

mysql IS NULL using index case explanation

Introduction The use of is null, is not null, and...

JS implements sliding up and down on the mobile terminal one screen at a time

This article shares with you the specific code of...

Detailed explanation of Vue-Jest automated testing basic configuration

Table of contents Install Configuration Common Mi...

How to install Composer in Linux

1. Download the installation script - composer-se...

Teach you how to achieve vertical centering elegantly (recommended)

Preface There are many ways to center horizontall...

What are the advantages of using B+Tree as an index in MySQL?

Table of contents Why do databases need indexes? ...

Detailed explanation of jQuery chain calls

Table of contents Chain calls A small case Chain ...

Sample code for deploying ELK using Docker-compose

environment Host IP 192.168.0.9 Docker version 19...

Implementing a random roll caller based on JavaScript

This article shares the specific code of JavaScri...

MySQL 5.7.10 Installation Documentation Tutorial

1. Install dependency packages yum -y install gcc...

Detailed steps to delete environment variables in Linux

How to delete environment variables in Linux? Use...

Should I use distinct or group by to remove duplicates in MySQL?

Preface About the performance comparison between ...

JavaScript to implement the web version of Gobang game

This article shares the specific code for JavaScr...