SoFunction
Updated on 2025-04-05

Implementing Snake Games with JavaScript

This article shares the specific code of JavaScript to implement the Snake Game for your reference. The specific content is as follows

The code 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/" >
</head>
<body>
<div >

</div>


<script src="js/"></script>
<script src="js/"></script>
<script src="js/"></script>
<script src="js/"></script>
<script src="js/"></script>
</body>
</html>

The code is as follows

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

The code is as follows

//The self-keying function opens a new scope to avoid naming conflicts(function () {
 //Local scope
//Record the food you created last time and prepare for deletion var elements=[];
 var position = 'absolute';
//Constructor Food function Food(options) {
 options = options || {};
  =  || 'green';

  =  || 20;
  =  || 20;
 //The location of the food  =  || 0;
  =  || 0;
 }

// Render the food on the map// prototype, each function has a child object prototype, which represents the prototype of the function// prototype represents a collection of class attributes.  When a class object is generated through new, the properties of the prototype object will become properties of the instantiated object  = function (map) {
 //Delete the food created before remove();

 //Dynamicly create divs to display food on the page var div = ('div');
 (div);

 (div);
 //Randomly generated food  = (0,/ - 1)*;
  = (0,/ - 1)*;

 //Set div style  = position; //False from document flow  = ;
  =  + 'px';
  =  + 'px';
  =  + 'px';
  =  + 'px';
 };

 function remove() {
 for (var i = -1;i >= 0;i-- ){
 //Delete div elements[i].(elements[i]);
 //Delete array elements (i,1); //The first parameter, which element starts with? The second parameter, delete several elements }
 }
 //Put the Food constructor to allow external access  = Food;
})()
//test// var map = ('map');
// var food = new Food(); //The Food here is// (map);

The code is as follows

(function () {
 var position = 'absolute';
 //Record the snake created before var elements = [];
 function Snake(options) {
 options = options || {};
 //Size of Snake Festival  =  || 20;
  =  || 20;
 //The direction of the snake moving  =  || 'right';
 //Snake Body (Snake Festival) The first element is the snake head  = [
 {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'}
 ];
 }
  = function (map) {
 //Delete the snake created before remove();
 // Render each snake festival onto the map for (var i = 0,len = ; i<len; i++){
 //Snake Festival var object = [i];
 var div = ('div');
 (div);

 //Record the current snake (div);
 //Set style  = position;
  =  + 'px';
  =  + 'px';
  =  *  + 'px';
  =  *  + 'px';
  = ;
 }
 }
 // Methods to control snake movement  = function (food,map) {
 //Control the movement of the snake's body (current snake festival to the position of the previous snake festival) for (var i =  - 1;i > 0;i--){
 [i].x = [i - 1].x;
 [i].y = [i - 1].y;
 }
 //Control the movement of the snake's head //Judge the direction of the snake's movement var head = [0];
 switch (){
 case 'right':
  += 1;
 break;
 case 'left':
  -=1;
 break;
 case 'top':
  -=1;
 break;
 case 'bottom':
  +=1;
 }


 //2.4 Determine whether the snake head overlaps with the food var headX =  * ;
 var headY =  * ;
 if (headX ===  && headY === ){
 //Let the snake add one section //Get the last section of the snake var last = [ - 1];
 ({
 x:,
 y:,
 color:
 })
 //Regenerate food randomly on the map (map);
 }
 }

 function remove() {
 for (var i =  -1;i>= 0;i--){
 //Delete div elements[i].(elements[i]);
 //Delete elements in the array (i,1);
 }
 }
 //Expose the constructor to the outside  = Snake;
})()

//test// var map =('map');
// var sanke = new Snake();
// (map);

The code is as follows

//Use self-keying function to create a new local scope to prevent naming conflicts(function () {
 function Game(map) {
  = new Food();
  = new Snake();
  = map;
 that=this;
 }
  = function () {
 //1. Render snake and food objects onto the map ();
 ();
 //2. Start the game logic //2.1 Let the snake move //2.2 When the snake encounters the boundary game ends runSnake();
 //2.3 Control the direction of the snake's movement through the keyboard bindKey();
 //2.4 When a snake encounters food, do the corresponding treatment }

 function bindKey() {
  = function (e) {
 switch (){
 case 37:
 if ( === 'right') return;
  = 'left';
 break;
 case 38:
 if ( === 'bottom') return;
  = 'top';
 break;
 case 39:
 if ( === 'left') return;
  = 'right';
 break;
 case 40:
 if ( === 'top') return;
  = 'bottom';
 break;
 }
 }
 }

 //
 function runSnake() {
 var timerId = setInterval(function () {
 //Let the snake go one by one //In the function in the timer, this points to the window object (,);
 ();

 //2.2 When the snake encounters the boundary game ends
 var maxX =  / ;
 var maxY =  / ;
 //Get the coordinates of the snake head var headX = [0].x;
 var headY = [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 =  - 1;i > 0;i--){
 if (headX == [i].x && headY == [i].y){
 alert('Game Over');
 clearInterval(timerId);
 break;
 }
 }
 },300)
 }


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

// //test// var map =('map');
// var game = new Game(map);
// ();

The code is as follows

(function () {
 var map =('map');
 var game = new Game(map);
 ();
})()

The code is as follows

// Tool Object
(function () {
 var Tool = {
 getRandom: function (min, max) {
 min = (min);
 max = (max);
 return (() * (max - min + 1)) + min;
 }
 }
  = Tool;
})()

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.