Using JavaScript to Realize Snake Game

  • 2021-08-28 19:07:44
  • OfStack

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

The code for index. html is as follows


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title> Greedy snake </title>
 <link rel="stylesheet" href="css/index.css" >
</head>
<body>
<div id="map">

</div>


<script src="js/tool.js"></script>
<script src="js/food.js"></script>
<script src="js/snake.js"></script>
<script src="js/game.js"></script>
<script src="js/main.js"></script>
</body>
</html>

The code for index. css is as follows


#map {
 width: 600px;
 height: 400px;
 background-color: #ccc;
 position: relative;
}

The code for food. js is as follows


// Self-tuning function   Open 1 New scopes to avoid naming conflicts 
(function () {
 // Local scope 

// On record 1 Create food for deletion 
 var elements=[];
 var position = 'absolute';
// Constructor Food
 function Food(options) {
 options = options || {};
 this.color = options.color || 'green';

 this.width = options.width || 20;
 this.height = options.height || 20;
 // Location of food 
 this.x = options.x || 0;
 this.y = options.y || 0;
 }

// Render the food to map Upper 
// prototype, Each function has a 1 Child object prototype , prototype Represents the prototype of the function 
// prototype Denote 1 A collection of class attributes. Pass new To generate 1 Class object, prototype The properties of the object become the properties of the instantiated object 
 Food.prototype.render = function (map) {
 // Delete previously created food 
 remove();

 // Dynamic creation div Displays the food on the page 
 var div = document.createElement('div');
 map.appendChild(div);

 elements.push(div);
 // Randomly generated food 
 this.x = Tool.getRandom(0,map.offsetWidth/this.width - 1)*this.width;
 this.y = Tool.getRandom(0,map.offsetHeight/this.height - 1)*this.height;

 // Settings div Style 
 div.style.position = position; // Out of document flow 
 div.style.background = this.color;
 div.style.width = this.width + 'px';
 div.style.height = this.height + 'px';
 div.style.left = this.x + 'px';
 div.style.top = this.y + 'px';
 };

 function remove() {
 for (var i = elements.length-1;i >= 0;i-- ){
 // Delete div
 elements[i].parentNode.removeChild(elements[i]);
 // Delete Array Elements 
 elements.splice(i,1); // No. 1 1 Parameters, starting from which element   No. 1 2 Parameters, deleting several elements 
 }
 }
 // Put Food Constructor   Make it externally accessible 
 window.Food = Food;
})()
// Test 
// var map = document.getElementById('map');
// var food = new Food(); // Here's Food Is window.Food
// food.render(map);

The code for snake. js is as follows


(function () {
 var position = 'absolute';
 // Record previously created snakes 
 var elements = [];
 function Snake(options) {
 options = options || {};
 // The size of the snake festival 
 this.width = options.width || 20;
 this.height = options.height || 20;
 // The direction in which the snake moves 
 this.direction = options.direction || 'right';
 // Snake Body (Snake Festival)   No. 1 1 Elements are snake heads 
 this.body = [
 {x: 5, y: 2, color: 'red'},
 {x: 4, y: 2, color: 'blue'},
 {x: 3, y: 2, color: 'blue'},
 {x: 2, y: 2, color: 'blue'},
 {x: 1, y: 2, color: 'blue'}
 ];
 }
 Snake.prototype.render = function (map) {
 // Delete previously created snakes 
 remove();
 // Put every 1 The Snake Festival is rendered on the map 
 for (var i = 0,len = this.body.length; i<len; i++){
 // Snake Festival 
 var object = this.body[i];
 var div = document.createElement('div');
 map.appendChild(div);

 // Record the current snake 
 elements.push(div);
 // Setting Styles 
 div.style.position = position;
 div.style.width = this.width + 'px';
 div.style.height = this.height + 'px';
 div.style.left = object.x * this.width + 'px';
 div.style.top = object.y * this.height + 'px';
 div.style.backgroundColor = object.color;
 }
 }
 // Method of controlling snake movement 
 Snake.prototype.move = function (food,map) {
 // Control the body movement of snakes  ( Current Snake Festival   To   Upper 1 Location of Snake Festival )
 for (var i = this.body.length - 1;i > 0;i--){
 this.body[i].x = this.body[i - 1].x;
 this.body[i].y = this.body[i - 1].y;
 }
 // Control the movement of the snake head 
 // Determine the direction of the snake's movement 
 var head = this.body[0];
 switch (this.direction){
 case 'right':
 head.x += 1;
 break;
 case 'left':
 head.x -=1;
 break;
 case 'top':
 head.y -=1;
 break;
 case 'bottom':
 head.y +=1;
 }


 //2.4 Determine whether the snake head coincides with the food 
 var headX = head.x * this.width;
 var headY = head.y * this.height;
 if (headX === food.x && headY === food.y){
 // Let the snake increase 1 Section 
 // Get the last of the snake 1 Section 
 var last = this.body[this.body.length - 1];
 this.body.push({
 x:last.x,
 y:last.y,
 color:last.color
 })
 // Randomly regenerate food on the map 
 food.render(map);
 }
 }

 function remove() {
 for (var i = elements.length -1;i>= 0;i--){
 // Delete div
 elements[i].parentNode.removeChild(elements[i]);
 // Delete an element from an array 
 elements.splice(i,1);
 }
 }
 // Expose the constructor to the outside 
 window.Snake = Snake;
})()

// Test 
// var map =document.getElementById('map');
// var sanke = new Snake();
// sanke.render(map);

The code for game. js is as follows


// Using self-tuning functions, create 1 New local scope to prevent naming conflicts 
(function () {
 function Game(map) {
 this.food = new Food();
 this.snake = new Snake();
 this.map = map;
 that=this;
 }
 Game.prototype.start = function () {
 //1. Render snakes and food objects on the map 
 this.food.render(this.map);
 this.snake.render(this.map);
 //2. Start game logic 
 //2.1  Let the snake move 
 //2.2 When the snake meets the boundary, the game ends 
 runSnake();
 //2.3 Control the direction of snake movement through keyboard 
 bindKey();
 //2.4 When snakes meet food   Do the corresponding treatment 
 }

 function bindKey() {
 document.onkeydown = function (e) {
 switch (e.keyCode){
 case 37:
 if (that.snake.direction === 'right') return;
 that.snake.direction = 'left';
 break;
 case 38:
 if (that.snake.direction === 'bottom') return;
 that.snake.direction = 'top';
 break;
 case 39:
 if (that.snake.direction === 'left') return;
 that.snake.direction = 'right';
 break;
 case 40:
 if (that.snake.direction === 'top') return;
 that.snake.direction = 'bottom';
 break;
 }
 }
 }

 //
 function runSnake() {
 var timerId = setInterval(function () {
 // Let the snake go 1 Lattice 
 // In the timer function Medium this Is to point to window Object's 
 that.snake.move(that.food,that.map);
 that.snake.render(that.map);

 //2.2 When the snake meets the boundary, the game ends 

 var maxX = that.map.offsetWidth / that.snake.width;
 var maxY = that.map.offsetHeight / that.snake.height;
 // Get the coordinates of the snake head 
 var headX = that.snake.body[0].x;
 var headY = that.snake.body[0].y;

 if (headX <0 || headX>=maxX){
 alert('Game Over');
 clearInterval(timerId);
 }
 if (headY <0 || headY >= maxY){
 alert('Game Over');
 clearInterval(timerId);
 }
 for (var i = that.snake.body.length - 1;i > 0;i--){
 if (headX == that.snake.body[i].x && headY == that.snake.body[i].y){
 alert('Game Over');
 clearInterval(timerId);
 break;
 }
 }
 },300)
 }


 // Expose the constructor to the outside 
 window.Game = Game;
})()

// // Test 
// var map =document.getElementById('map');
// var game = new Game(map);
// game.start();

The code for main. js is as follows


(function () {
 var map =document.getElementById('map');
 var game = new Game(map);
 game.start();
})()

The code for Tool. js is as follows


//  Tool object 

(function () {
 var Tool = {
 getRandom: function (min, max) {
 min = Math.ceil(min);
 max = Math.floor(max);
 return Math.floor(Math.random() * (max - min + 1)) + min;
 }
 }
 window.Tool = Tool;
})()

Related articles: