代码如下:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Snake</title> 5 </head> 6 <body style="text-align:center;margih:100px;background-color:#aaaaaa"> 7 <canvas id="canv" width="400" height="400" style="background-color:gray"> 8 </canvas> 9 <script> 10 //声明变量 11 var box=document.getElementById('canv').getContext('2d'); 12 var snake; 13 var direction;//1向右,-1向左,20向下,-20向上 14 var n;//下次移动相关 15 var food; 16 var istrue; 17 //绘制地图 18 function draw(point,color){ 19 box.fillStyle=color; 20 box.fillRect(point%20*20+1,~~(point/20)*20+1,18,18); 21 } 22 23 (function() {ready() ; } () ); 24 25 function ready(){ 26 for(var i=0;i<400;i++){ 27 draw(i,"#313131");} 28 snake=[66,65,64]; 29 direction=1; 30 food=344; 31 istrue=true; 32 draw(food,"yellow"); 33 draw(66,"#00b7ee"); 34 draw(65,"#00b7ee"); 35 draw(64,"#00b7ee"); 36 } 37 38 //核心算法 39 function run(){ 40 istrue=true; 41 document.getElementById("butn").setAttribute("disabled",true); 42 snake.unshift(n=snake[0]+direction); 43 if(snake.indexOf(n,1)>0||n<0||n>399||(direction==-1&&n%20==19)||(direction==1&&n%20==0)){ 44 ready(); 45 document.getElementById("butn").removeAttribute("disabled"); 46 return alert("游戏结束");} 47 draw(n,"#00b7ee"); 48 if(n==food) 49 { 50 while(snake.indexOf(food=~~(Math.random()*400))>0){continue;}; 51 draw(food,"yellow"); 52 } 53 else{ 54 draw(snake.pop(),"#313131"); 55 } 56 setTimeout(arguments.callee,200);//每过200ms执行一次事件 57 } 58 59 //添加键盘事件 60 document.onkeydown=function(e){ 61 if(istrue){ 62 if(direction==1||direction==-1){ 63 if(e.keyCode==38) 64 {direction=-20;istrue=false;} 65 if(e.keyCode==40) 66 {direction=20;istrue=false;}} 67 if(direction==20||direction==-20){ 68 if(e.keyCode==39) 69 {direction=1;istrue=false;} 70 if(e.keyCode==37) 71 {direction=-1;istrue=false;} 72 }}} 73 74 </script> 75 <div> 76 <button id="butn" type="button" onclick="run()">开始游戏</button> 77 </div> 78 </body> 79 </html>
使用方法:
1.将代码复制入记事本;
2.打开方式选择浏览器打开就可以了;