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

jquery+springboot realizes file upload function

This article example shares the specific code of ...

A Preliminary Study on JSBridge in Javascript

Table of contents The origin of JSBridge The bidi...

Detailed explanation of MySQL table name case-insensitive configuration method

By default, MySQL in Linux distinguishes between ...

Introducing the code checking tool stylelint to share practical experience

Table of contents Preface text 1. Install styleli...

Implementation of deploying Apollo configuration center using docker in CentOS7

Apollo open source address: https://github.com/ct...

js tag syntax usage details

Table of contents 1. Introduction to label statem...

Introduction to the process of building your own FTP and SFTP servers

FTP and SFTP are widely used as file transfer pro...

How to load third-party component libraries on demand in Vue3

Preface Take Element Plus as an example to config...

How to restore a database and a table from a MySQL full database backup

In the official MySQL dump tool, how can I restor...

Detailed explanation of JavaScript upload file limit parameter case

Project scenario: 1. Upload file restrictions Fun...

MySQL index failure principle

Table of contents 1. Reasons for index failure 2....

Solution to Nginx session loss problem

In the path of using nginx as a reverse proxy tom...