JS practical object-oriented snake game example

JS practical object-oriented snake game example

think

The first step is to think about how many parts a snake is divided into and how the snake's head and body are formed.

The second step is to think about how the snake moves; how to control the direction of the snake through the keyboard.

The third step is to think about under what circumstances the game will end.

The fourth step is to think about how the food is produced, and what points need to be paid attention to between its production location and the position of the snake.

The fifth step is to think about how the snake eats the food; after eating, the snake's body will become longer and new food will be produced.

After completing step 6, play it a few more times to enjoy the fruits of your labor. ! ! !

1. Greedy Snake Effect Picture

2. Analysis of Snake

2.1 Start Game Function

When the user enters the main interface of the game, he can find the "start" button in a prominent position at the lower center of the interface. After clicking it, the user can start a new game. Get the button variable and add an addEventListener('click', function() {}) click event to it.

btnstart.addEventListener('click', function() {
     btnstart.style.display = 'none';
     //Call the intermediary class game = new Game();
     var table = document.querySelector('table');
     table.addEventListener('click', function() {
        //Clear timer clearInterval(game.timer);
        btnstop.style.display = 'block';
     })
});

2.2 Motor function

2.2.1 Snake Movement in Different Directions

When the user clicks the "Start Game" button, the snake moves from left to right by default.

//The current direction accepts willDirection! ! !
this.direction = this.willDirection;
 
//Snake movement in different directions switch (this.direction) {
     case "R":
            //Move right this.body.unshift({ "row": this.body[0].row, "col": this.body[0].col + 1 });
            break;
     case "D":
            //Move down this.body.unshift({ "row": this.body[0].row + 1, "col": this.body[0].col });
            break;
     case "L":
            //Move left this.body.unshift({ "row": this.body[0].row, "col": this.body[0].col - 1 });
            break;
     case "T":
            //Move up this.body.unshift({ "row": this.body[0].row - 1, "col": this.body[0].col });
            break;
}

2.2.2 Keyboard control direction movement function

The user can control the direction of the snake's movement by using the up, down, left, and right directional keys on the keyboard, and the snake will move in a straight line in the controlled direction.

Game.prototype.bindEvent = function() {
    var self = this;
    //Keyboard event document.onkeydown = function(e) {
        switch (e.keyCode) {
            //Press the left button case 37:
                //Judge first (if the current direction is moving to the right, we cannot press the left button at this time)
                if (self.snake.direction == 'R') return;
                // self.snake.direction = 'L';
                self.snake.changeDirection('L');
                self.d = "L";
                break;
                //Press the up key case 38:
                if (self.snake.direction == 'D') return;
                self.snake.changeDirection('T');
                self.d = "T";
                break;
                //Press right key case 39:
                if (self.snake.direction == 'L') return;
                self.snake.changeDirection('R');
                self.d = "R";
                break;
                //Press the key case 40:
                if (self.snake.direction == 'T') return;
                self.snake.changeDirection('D');
                self.d = "D";
 
                break;
        }
 
    }
 
};

2.3 Eating food function

2.3.1 Food production

Food location: traverse the row and col of the snake, and then determine whether they overlap with the randomly generated row and col.

var self = this; //refers to window
    //The following do-while loop statement is used to create a row and col first, and then determine whether it is on the snake.
        //Food location this.row = parseInt(Math.random() * gameSnake.row);
        this.col = parseInt(Math.random() * gameSnake.col);
    } while ((function() {
        //Traverse the row and col of the snake, and then judge whether they overlap with the randomly generated row and col for (var i = 0; i < gameSnake.snake.body.length; i++) {
        if (gameSnake.snake.body[i].row == self.row && gameSnake.snake.body[i].col == self.col) {
             return true;
          }
       }
       return false;
})());

2.3.2 The process of eating food

When food appears anywhere on the interface, the user uses the direction keys to control the snake to move around the food. When the snake's head touches the food, it means that the greedy snake has eaten the food. The next food will appear at any location on the interface, and the user will control the snake to eat this food again.

//If the current snake's head does not overlap with the food, it means that the food has not been eaten, and the tail is deleted at this time;
if (this.body[0].row == game.food.row && this.body[0].col == game.food.col) {
      //If they overlap, it means they have been eaten. The tail will not be deleted, only the head will be added. //Create a new food game.food = new Food(game);
      //Reset the frame number to 0, because the snake will jump //eat the food and add points game.score++;
      game.f = 0;
} else {
      this.body.pop();
}

2.4 Death determination function

When the snake head hits a wall in the forward direction or the snake head eats the snake body, a death judgment is given and a pop-up box is given to the user's game score.

2.4.1 Edge Death Judgment (Hit the Wall)

if (this.body[0].col > game.col - 1 || this.body[0].row > game.row - 1 || this.body[0].col < 0 || this.body[0].row < 0) {
        //lower right upper left alert('Game is over, your current total score is:' + game.score + 'points');
        this.body.unshift();
        clearInterval(game.timer);
}

2.4.2 Hitting Yourself

for (var i = 1; i < this.body.length; i++) {
    if (this.body[0].col == this.body[i].col && this.body[0].row == this.body[i].row) {
        alert('The game is over, your current total score is:' + game.score + 'points');
        clearInterval(game.timer);
    }
}

2.5 Pause/resume game function

btnstop.addEventListener('click', function() {
    btnstop.style.display = 'none';
    game.timer = setInterval(function() {
    // The core of the timer is the essence of game rendering, clear screen - update - render game.f++;
    // Clear the screen game.clear();
    //Snake movement/update //Snake update speed When the snake side is longer, the speed increases var during = game.snake.body.length < 30 ? 30 - game.snake.body.length : 1;
    // Snake update game.f % during == 0 && game.snake.update();
    // Render the snake game.snake.render();
    // Render food game.food.render();
    }, 20);
})

Summarize

For the Snake game project, you need to sort out your ideas.

This is the end of this article about the practical object-oriented snake game example in JS. For more relevant JS snake game content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript exquisite snake implementation process
  • JS implements the snake game
  • JavaScript to achieve the idea of ​​​​snake game
  • JavaScript implementation of classic snake game

<<:  HTML unordered list bullet points using images CSS writing

>>:  Pure CSS to implement iOS style open and close selection box function

Recommend

5 ways to make your JavaScript codebase cleaner

Table of contents 1. Use default parameters inste...

CentOS7 upgrade kernel kernel5.0 version

Upgrade process: Original system: CentOS7.3 [root...

SMS verification code login function based on antd pro (process analysis)

Table of contents summary Overall process front e...

mysql 5.7.18 winx64 password change

After MySQL 5.7.18 is successfully installed, sin...

Detailed explanation of the use of MySQL select cache mechanism

MySQL Query Cache is on by default. To some exten...

Use of Linux chkconfig command

1. Command Introduction The chkconfig command is ...

JavaScript Function Currying

Table of contents 1 What is function currying? 2 ...

Detailed tutorial on installing Mysql5.7.19 on Centos7 under Linux

1. Download MySQL URL: https://dev.mysql.com/down...

Let you understand the working principle of JavaScript

Table of contents Browser kernel JavaScript Engin...

Practice of dynamically creating dialog according to file name in vue+el-element

Table of contents background accomplish 1. Encaps...

What does href=# mean in a link?

Links to the current page. ------------------- Com...

14 Ways to Create Website Content That Engages Your Visitors

When I surf the Net, I often see web sites filled...

Detailed explanation of ECharts mouse event processing method

An event is an action performed by the user or th...

CnBlogs custom blog style sharing

After spending half the night on it, I finally ma...