The examples in this article share with you the specific code of JS to implement the Snake game for your reference. The specific content is as follows
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gbk"> <title>Snake game</title> <style type="text/css"> * { margin: 0; padding: 0; } .wrap { width: 600px; margin: 0 auto; position: relative; } p { position: absolute; left: 65%; top: 10%; } h1 { text-align: center; margin-bottom: 20px; } #score { text-align: center; font-size: 20px; } #snake_map { margin: 0 auto; border: 1px solid skyblue; } /*Line Style*/ .row { height: 20px; } /*Column Style*/ .col { height: 20px; width: 20px; box-sizing: border-box; border: 1px solid lightgray; background: rgb(250, 250, 250); float: left; } .activeSnake { background: black; } .egg { background: red; } #Pause { margin-left: 18%; border: 1px solid skyblue; color: white; background: skyblue; width: 50px; height: 30px; margin-bottom: 10px; border-radius: 5px; } #Start,#Refresh,#Speed { border: 1px solid skyblue; background: skyblue; color: white; width: 50px; height: 30px; border-radius: 5px; margin-left: 15px; } </style> </head> <body> <div class="wrap"> <h1>Snake game</h1> <!-- Record how many eggs I ate --> <p style="font-size:20px;color:red"> score:<span style="color:black">0</span> </p> <!-- Pause button --> <input type="button" name="name" value="Pause"> <!-- Start button --> <input type="button" name="name" value="Start"> <!-- refresh(Start the game again) --> <input type="button" name="name" value="Refresh"> <!-- Acceleration button --> <input type="button" name="name" value="Speed"> <!-- Snake walking path map --> <div > </div> </div> </body> <script type="text/javascript"> //Get score tagvar score = ('score'); // Get the path map tagvar map = ('snake_map'); // In order to flexibly set the map size, the following two variables are set// Used to store the number of rows and columns (i.e. the number of squares)var rowNumber = 25;// Number of rowsvar columnNumber = 20;// Number of columns;var mapWidth = columnNumber * 20 + 'px';// The width of the mapvar mapHeight = rowNumber * 20 + 'px';// The height of the map = mapWidth; = mapHeight;// Set the map width and height// Create a two-dimensional array to record the locations of all divs on the mapvar snakeDIVPosition = []; // Create map elements through a double-layer for loopfor ( var i = 0; i < rowNumber; i++) { // Create line div var rowDIV = ('div'); // Set div style = 'row'; // Add row div to path map map (rowDIV); // Create a row-level array to store each square div in the current row var rowArray = []; for ( var j = 0; j < columnNumber; j++) { // Create a div in each row var columnDIV = ('div'); // Set css style = 'col'; // Add block DIV to the current row (columnDIV); // Add squares to row array at the same time (columnDIV); } // The current inner loop ends, add the row array to the two-dimensional array (rowArray); } // Create a snake model// Create a one-dimensional array to store the divs occupied by the snake bodyvar snake = []; // The starting length of the fixed snake body is 3 divsfor ( var i = 0; i < 3; i++) { // Set different color divs for the snake body snakeDIVPosition[0][i].className = 'col activeSnake'; // Stored in snake body array snake[i] = snakeDIVPosition[0][i]; } // Define variables to control snakesvar x = 2; var y = 0;// The starting position offset of the snake headvar scoreCount = 0;// Fraction counter, that is, how many eggs have you eatenvar eggX = 0;// Record the row position of the eggvar eggY = 0;// Record the column position of the egg; var direction = 'right';// Record the direction of the snake movement, initially to the rightvar changeDir = true;// Determine whether the snake's movement direction needs to be changedvar delayTimer = null;// Delay timer // Add keyboard event listening direction keys to change the direction of the snake = function(event) { // First determine whether the direction needs to be changed. True means that it is necessary, false means that it is not needed. if (!changeDir) { return;// Return empty means that the function is directly terminated, and subsequent code will not be executed } event = event || ; // In order to reasonably handle the movement of the snake, it is necessary to judge the snake's head and body // Suppose the snake moves to the right, click the arrow keys left or right buttons without responding if (direction == 'right' && == 37) { return;// Terminate event execution } if (direction == 'left' && == 39) { return; } if (direction == 'up' && == 40) { return; } if (direction == 'down' && == 38) { return; } // We use keyCode to determine the direction the snake is going to move switch () { case 37: direction = 'left';// To the left break; case 38: direction = 'up';// Upward; break; case 39: direction = 'right';// To the right break; case 40: direction = 'down';// Down break; } changeDir = false; delayTimer = setTimeout(function() { // Set whether you need to change the direction changeDir = true; }, 300); }; // Start setting the snake movement logic// Snake movement functionfunction snakeMove() { // Set the position of the snake head according to the direction set above switch (direction) { case 'left': x--; break; case 'right': x++; break; case 'up': y--; break; case 'down': y++; break; }; // Determine whether the game is over if (x < 0 || y < 0 || x >= columnNumber || y >= rowNumber) { alert('Game Over!!!'); // Timer to end the snake movement clearInterval(moveTimer); return;// Terminate keyboard event; } // If the snake eats it, it will end the game. for ( var i = 0; i < ; i++) { // Compare the position of the snake's head after moving at this time with the position of the div that forms the snake on the left and right before. If the same means that you have eaten yourself and the game ends if (snake[i] == snakeDIVPosition[y][x]) { alert('Game over!!!'); clearInterval(moveTimer); return; }; } // Determine whether there is an egg on the snake's head moving if (eggX == x && eggY == y) { snakeDIVPosition[eggY][eggX].className = 'col activeSnake'; (snakeDIVPosition[eggY][eggX]);// Join the snake body scoreCount++;// Record scores // Update the current score = scoreCount; // Randomly generate a new egg createNewEgg(); } else { // Set the logic that the snake cannot touch the egg // Let the snake move // The snake's tail removes the snake's own color and turns it into the color of the grid snake[0].className = 'col'; // Remove the snake tail div from the array (); // Add the new snake head to the snake array snakeDIVPosition[y][x].className = 'col activeSnake'; (snakeDIVPosition[y][x]); }; }; var moveTimer = setInterval('snakeMove()', 300); // Define a random number function that generates min and maxfunction random(min, max) { return (() * (max - min + 1) + min); }; function createNewEgg() { // Randomly output the x and y values of the subscript of new egg eggX = random(0, columnNumber - 1); eggY = random(0, rowNumber - 1); //Judge if the randomly generated egg coincides with the snake body, then randomly generate an egg again if (snakeDIVPosition[eggY][eggX].className == 'col activeSnake') { createNewEgg();// Re-random new egg } else { snakeDIVPosition[eggY][eggX].className = 'col egg'; } }; createNewEgg();// Generate new egg at the beginning of the game var pause = ('Pause'); var start = ('Start'); var refresh = ('Refresh'); var speed = ('Speed'); // Add a pause button = function() { clearInterval(moveTimer); }; // Add Start Button = function() { clearInterval(moveTimer); moveTimer = setInterval('snakeMove()', speed1); }; // Add refresh button = function() { (); }; // Add acceleration buttonvar speed1 = 300; = function() { speed1 -= 20; clearInterval(moveTimer); moveTimer = setInterval('snakeMove()', speed1); }; </script> </html>
More interesting classic game implementation topics, share with you:
Summary of C++ classic games
Summary of classic python games
python Tetris game collection
JavaScript classic game
Summary of classic java games
Summary of classic javascript games
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.