The examples in this article share the relevant code of the JS Snake Game for your reference. The specific content is as follows
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Snake Game</title> <style>*{margin:0; padding:0;}header { display: block; margin: 0 auto; width: 500px; text-align: center;}header h1 { font-family: Arial; font-weight: bold;}header #newGameButton { display: block; margin: 20px auto; width: 100px; padding: 10px 10px; background-color: #8f7a66; font-family: Arial; color: white; border-radius: 10px; text-decoration: none;}header #newGameButton:hover { background-color: #9f8b77;}header p { font-family: Arial; font-size: 25px; margin: 20px auto;} canvas{ display:block; border:medium double black; margin:4px auto;} </style></head><body> <header> <h1>Snake Game</h1> <a href="javascript:newgame();" id="newGameButton">New Game</a> <p>score:<span id="score">0</span></p> </header> <canvas id="canvas"> Your browser doesn't support the <code>canvas</code> element. </canvas> <script> var CANVAS = document.getElementById("canvas");var CTX = CANVAS.getContext("2d");var SNAKE = new Array(); //Simulate the snake body var with a queue DIR = "right"; //Use to control the direction of the snake head var SIZE = 20; //Width of the snake body var FOODX = 0; //The x coordinate of the food var FOODY = 0; //The y coordinate of the food var HEADX = 0; //The x coordinate of the snake head var HEADY = 0; //The y coordinate of the snake head var MAXWIDTH = 200; //The height of the canvas var MAXHEIGHT = 200; //The width of the canvas var TIME = 400; //The speed of the snake var SCORE = 0; //Calculate the player score var interval = null; CANVAS.width = MAXWIDTH;CANVAS.height = MAXHEIGHT;window.onload = function(){ newgame();};document.getElementById("newGameButton").click(function(){ newgame();});function newgame(){ SNAKE = []; //Use queue to simulate the snake body DIR = "right"; //Use to control the direction of the snake head HEADX = 0; //The x coordinate of the snake head HEADY = 0; //The y coordinate of the snake head SCORE = 0; window.clearInterval(interval); interval = null; //Initialize the canvas CTX.clearRect(0, 0, MAXWIDTH, MAXHEIGHT); //Draw a snake drawSnake(); //Port food setFood(); //Move snake interval = window.setInterval(move, TIME);}function move(){ switch(DIR){ case "up":HEADY = HEADY-SIZE;break; case "right":HEADX = HEADX+SIZE;break; case "down":HEADY = HEADY+SIZE;break; case "left":HEADX = HEADX-SIZE;break; } if(HEADX>MAXWIDTH-SIZE || HEADY>MAXHEIGHT-SIZE || HEADX<0 || HEADY<0){ alert("Your score is: "+SCORE+" points, keep working hard! Reason for failure: I ran into a wall......"); window.location.reload(); } for(var i=1;i<SNAKE.length;i++){ if(SNAKE[i][0] == SNAKE[0][0] && SNAKE[i][1] == SNAKE[0][1]){ alert("Your score is: "+SCORE+" points, keep working hard! Reason for failure: I bumped into myself...."); window.location.reload(); } } if(SNAKE.length == MAXWIDTH *MAXHEIGHT){ alert("So awesome! ~"); window.location.reload(); } moveIn(HEADX, HEADY);//Move one grid}document.onkeydown = function(e) { //Change the snake direction var code = e.keyCode - 37; switch(code){ case 1 : DIR = "up";break;//On case 2 : DIR = "right";break;//Right case 3 : DIR = "down";break;//Down case 0 : DIR = "left";break;//Left}}//====================================================================================================================================================================================================================================================================================================================================================================================================================================================================== SNAKE.push([HEADX, HEADY]); //Drawing snake body switch(DIR){ case "up": drawBody(HEADX, HEADY + SIZE, HEADX, HEADY + 2 * SIZE); break; case "right": drawBody(HEADX - SIZE, HEADY, HEADX - 2 * SIZE, HEADY); break; case "down": drawBody(HEADX, HEADY - SIZE, HEADX, HEADY - 2 * SIZE); break; case "left": drawBody(HEADX + SIZE, HEADY, HEADX + 2 * SIZE, HEADY); break; }}function drawBody(x1, y1, x2, y2){ CTX.fillRect (x1, y1, SIZE, SIZE); CTX.fillRect (x2, y2, SIZE, SIZE); SNAKE.push([x1, y1]); SNAKE.push([x2, y2]);}//======================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================= FOODY, SIZE, SIZE);}function foodInSnake(){ for (var i = 0; i < SNAKE.length; i++) { if(FOODX == SNAKE[i][0] && FOODY == SNAKE[i][1]){ return true; } } return false;}//============================================================================================================================================================================================================================================================================================================================================================================================================================ CTX.fillRect(x, y, SIZE, SIZE);//Re-draw the snake head//Add the new snake head to the SNAKE array var newSnake = [[x, y]]; SNAKE = newSnake.concat(SNAKE); if(false == eatFood()){//If you don't eat food, reduce one snake tail var snakeTail = SNAKE.pop();//Get the snake tail position CTX.clearRect(snakeTail[0], snakeTail[1], SIZE, SIZE);//Remove the snake tail}}function eatFood(){ if(HEADX == FOODX && HEADY == FOODY){ CTX.fillStyle = "block"; CTX.fillRect (FOODX, FOODY, SIZE, SIZE); setFood(); SCORE++; //$("#score").text(SCORE); document.getElementById("score").innerHTML = SCORE; return true; } return false;} </script></html>Reproduction image:
Ideas:
function newgame(){ reset the data of snake and fractions; clear interval; initialize the canvas; draw a snake; place food; use a timer (setInterval) to move the snake (move function); } function move(){ change the position of the next latitude of the snake head according to the direction; determine whether the game is over and the reason for the end (including win or lose); Snake moves one latitude (moveIn function); } monitor the keyboard's direction keys, and modify the value of the global variable DIR (used to store the direction); function moveIn(){ add a latitude to the previous latitude of the snake head as a new snake head, and add the coordinates of the snake head as the first element to the array representing the snake; if (no food was eaten){ delete a latitude to the snake tail and make corresponding changes in the canvas; }}It should be noted that if you need to set the width and height in canvas in JS, it is slightly different from setting other CSS properties.
CANVAS.width = MAXWIDTH;CANVAS.height = MAXHEIGHT;
The editor has also prepared a wonderful topic for everyone: a summary of classic javascript games
The above is all about this article, I hope it will be helpful for everyone to learn JavaScript programming.