This article shares the specific code of JS to implement the Snake mini game for your reference. The specific content is as follows
Idea: Add a map to the page to provide boundaries, randomly appear in the map, set an initial length for the snake body, use the keyboard direction keys to control the snake's direction, when the snake touches the food (when the coordinates are repeated), increase the length of the snake body, and when it hits the wall or itself, the program stops and the game ends.
HTML structure:
<body> <div ></div> </body>
CSS style:
<style> #map{ width: 600px; height: 300px; background: #ccc; border: 5px solid blacks; margin: 0 auto; position: relative;} </style>
js implementation functions:
<script> class Map{ //map constructor(){ = ("map"); = ; = ; } } class Food{ //food constructor(){ = 20; = 20; = 0; = 0; = "orange"; (); } createEle(){ = ("div"); = `width:${}px;height:${}px;background:${};position:absolute;left:${ * }px;top:${ * }px;border-radius: 40%;`; (); } randomPos(){ = random(0,() / ); = random(0,() / ); = * + "px"; = * + "px"; } } class Snake{ //Body constructor(){ = 20; = 20; = [{ ele:null,x:4,y:3,c:randomColor() },{ ele:null,x:3,y:3,c:randomColor() },{ ele:null,x:2,y:3,c:randomColor() }]; = "right"; //Set the default walking direction (); } createEle(){ for(var i=0;i<;i++){ if(![i].ele){ [i].ele = ("div"); ([i].ele); } [i]. = `width:${}px;height:${}px;background:${[i].c};position:absolute;left:${[i].x * }px;top:${[i].y * }px;color:#fff;border-radius: 40%;`; } [0]. = "00" setTimeout(()=>{()},300); } move(){ for(var i=-1;i>0;i--){ [i].x = [i-1].x; [i].y = [i-1].y; } switch(){ case "left":[0].x -= 1;break; case "right":[0].x += 1;break; case "top":[0].y -= 1;break; case "bottom":[0].y += 1;break; } if([0].x < 0 || [0].y < 0 || [0].x > (() / ) || [0].y > (() / )){ alert("It hit the wall"); return; } if([0].x === && [0].y === ){ ({ele:null,x:[-1].x,y:[-1].y,c:randomColor()}); (); } for(var i=1;i<;i++){ if([0].x == [i].x && [0].y == [i].y){ alert("Crashed myself"); return; } } (); } direct(type){ switch(type){ case 37: if( === "right") break; = "left";break; case 38: if( === "bottom") break; = "top";break; case 39: if( === "left") break; = "right";break; case 40: if( === "top") break; = "bottom";break; } } } function random(a,b){ return (()*(a-b)+b); } function randomColor(){ return `rgb(${random(0,255)},${random(0,255)},${random(0,255)})`; } var m = new Map(); var f = new Food(); (); var s = new Snake(); = function(eve){ var e = eve || ; var code = || ; (code); } </script>
The editor has also prepared a wonderful topic for everyone: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.