JavaScript implementation of classic snake game

JavaScript implementation of classic snake game

This article shares the specific code of JavaScript to implement the classic snake game for your reference. The specific content is as follows

Mainly uses the singleton mode, all elements are created dynamically;

1. Create a map

var Map;
    function map(){
        this.mapp=null;
        this.makemap=function(){
            this.mapp = document.createElement ("div");
            this.mapp.className = "mymap";
            document.body.appendChild(this.mapp);
        }
    }

2. Create a Snake Model

Create a collection to store the first three sections of the snake, traverse the collection, create the size and color of the snake, set the width and height of each section to 30px; initialize the direction of the snake head to the right

var Snack;
    function snack(){
        this.snackk=[["red",3,1,null],["pink",2,1,null],["pink",1,1,null]];
        this.direct="right";
        this.makesnack=function(){
             for(var i=0;i<this.snackk.length;i++){
                 if (this.snackk[i][3]==null){
                     this.snackk[i][3]=document.createElement("div");
                     this.snackk[i][3].className = "eatsnack";
                     this.snackk[i][3].style.backgroundColor =this.snackk[i][0];
                     Map.mapp.appendChild(this.snackk[i][3]);
                 }
                 this.snackk[i][3].style.left=this.snackk[i][1]*30+"px";
                 this.snackk[i][3].style.top=this.snackk[i][2]*30+"px";
             }
        };

3. Dynamic snake, traverse the set snackk that stores each section of the snake from back to front, pass the attributes of each section from back to front, and set the movement direction of the snake head. The left margin and top margin of the snake will change with the change of direction. Then set a timer to move the snake every 100ms;

this.movesnack=function(){
            var long = this.snackk.length - 1;
            for(var i=long; i>0; i--){
                this.snackk[i][1]=this.snackk[i-1][1];
                this.snackk[i][2]=this.snackk[i-1][2];
            }
            switch(this.direct){
                case "right": //right this.snackk[0][1] +=1;
                    break;
                case "left": //left this.snackk[0][1] -=1;
                    break;
                case "down": //down this.snackk[0][2] +=1;
                     break;
                case "up": //up this.snackk[0][2] -=1;
                     break;
            } 

4. Create food.

Food is randomly generated on the map. The size of the food is the same as the size of each section of the snake.

var Guoguo;
    function guozi(){
        this.guoo=null;
        this.x;
        this.y;
        this.makeguozi=function(){
            this.x = Math.floor( Math.random() * 30); //0-29
            this.y=Math.floor( Math.random() * 20); //0-19
            if(this.guoo==null){
                this.guoo=document.createElement("div");
                this.guoo.className = "guozi";
                Map.mapp.appendChild(this.guoo);
            }
            this.guoo.style.left=this.x * 30+"px";
            this.guoo.style.top =this.y * 30+"px";
        }
    }

5. Set keyboard events, and use the up, down, left, and right keys to control the direction of the snake head.

document.body.onkeyup=function(e){
           // console.log(e);
            switch(e.keyCode){
                case 37: //leftif(Snack.direct!="right"){
                            Snack.direct = "left";
                        }
                    break;
                case 39:// rightif(Snack.direct!="left"){
                        Snack.direct = "right";
                    }
                    break;
                case 38: //up if(Snack.direct!="down"){
                        Snack.direct = "up";
                    }
                    break;
                case 40: //Nextif(Snack.direct!="up"){
                       Snack.direct = "down";
                    }
                    break;
                case 87:
                    if (Snack.direct != "down") {
                        Snack.direct = "up";
                    }
                    break;
                case 65:
                    if (Snack.direct != "right") {
                        Snack.direct = "left";
                    }
                    break;
                case 68:
                    if (Snack.direct != "left") {
                        Snack.direct = "right";
                    }
                    break;
                case 83:
                    if (Snack.direct != "up") {
                        Snack.direct = "down";
                    }
                    break;
            }
        };

6. Detect the position of the snake head and the food. When the snake head eats the food, the length of the snake increases, and elements are added to the snackk set. Then, food is randomly created, the position of the food is detected, and the food is eaten again.

if(this.snackk[0][1]==Guoguo.x && this.snackk[0][2]==Guoguo.y ){
                 this.snackk.push([
                         "pink",
                         this.snackk[this.snackk.length-1][1],
                         this.snackk[this.snackk.length-1][2],
                         null
                 ]);
                 Guoguo.makeguozi ();
                 }

7. Set the snake body to pass through the wall. If the upper, lower, left, and right margins of the snake head are equal to 0, change the margins to the maximum value;

if(this.snackk[0][1]>29){
                this.snackk[0][1]=0 ; //Go through the wall from the right}
            if(this.snackk[0][1]<0){
                this.snackk[0][1]=29; //Go through the wall from the right}
            if(this.snackk[0][2]>19){
                this.snackk[0][2]=0 ; //Go through the wall from the right}
            if(this.snackk[0][2]<0){
                this.snackk[0][2]=19; //Go through the wall from the right}
            this.makesnack();
            this.stopsnack();

        };

8. Design the game to end. The snake dies when it hits its own body. The game ends and the timer is turned off. When the top and left margins of the snake's head are equal to the top and left margins of a part of the snake's body, the game ends and a prompt image pops up to indicate the end of the game.

this.stopsnack=function(){
            for(var k=this.snackk.length-1;k>0;k--){
                if (this.snackk[0][1]==this.snackk [k][1] && this.snackk[0][2]==this.snackk [k][2]) {
                    clearInterval(time);
                    var gameover = document.createElement ("div");
                    gameover.className = "over";
                    gameover.style.display = "block";
                    Map.mapp.appendChild (gameover);
                }
            }
} 

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:
  • JavaScript exquisite snake implementation process
  • JS implements the snake game
  • JavaScript to achieve the idea of ​​​​snake game
  • JS practical object-oriented snake game example

<<:  Detailed explanation of the correct way to install opencv on ubuntu

>>:  How to elegantly back up MySQL account information

Recommend

Detailed explanation of the use of Vue's new built-in components

Table of contents 1. Teleport 1.1 Introduction to...

Tutorial on installing and using virtualenv in Deepin

virtualenv is a tool for creating isolated Python...

VMware, nmap, burpsuite installation tutorial

Table of contents VMware BurpSuite 1. Virtual mac...

MySQL Optimization: Cache Optimization (Continued)

There are caches everywhere inside MySQL. When I ...

JS realizes the calculation of the total price of goods in the shopping cart

JS calculates the total price of goods in the sho...

MySQL 8.0.11 installation and configuration method graphic tutorial (win10)

This article records the installation and configu...

Vue scaffolding learning project creation method

1. What is scaffolding? 1. Vue CLI Vue CLI is a c...

Simple CSS text animation effect

Achieve results Implementation Code html <div ...

What is the base tag and what does it do?

The <base> tag specifies the default addres...

Website Design Experience Summary of Common Mistakes in Website Construction

Reminder: Whether it is planning, designing, or de...

Implementation steps for docker deployment of springboot and vue projects

Table of contents A. Docker deployment of springb...