HTML5实现贪吃蛇源代码

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

!DOCTYPEhtmlhtmlheadmetacharset=UTF-8titleInserttitlehere/titlestyletype=text/css#myCanvas{border:1pxsolid#f00;}/style/headbodyinputtype=buttonvalue=开始游戏onclick=beginGame();/canvasid=myCanvaswidth=450height=450/canvas/bodyscripttype=text/javascriptvarcanvas=document.getElementById(myCanvas);varctx=canvas.getContext(2d);varw=15;//格子宽、高varsnaLen=6;//初始长度varsnake=[];//身体长度for(vari=0;isnaLen;i++){snake[i]=newcell(i,0,39);}varhead=snake[snaLen-1];//头部//初始食物varfoodx=Math.ceil(Math.random()*28+1);varfoody=Math.ceil(Math.random()*28+1);varfood=newFood(foodx,foody);//食物functionFood(x,y){this.x=x;this.y=y;returnthis;}//身体functioncell(x,y,d){this.x=x;this.y=y;this.d=d;returnthis;}//动作functiondraw(){ctx.clearRect(0,0,450,450);//画布局//for(vari=0;i30;i++){//ctx.strokeStyle=#ccc;//线条颜色//ctx.beginPath();//ctx.moveTo(0,i*w);//ctx.lineTo(450,i*w);//ctx.moveTo(i*w,0);//ctx.lineTo(i*w,450);//ctx.closePath();//ctx.stroke();//}//画蛇身for(varj=0;jsnake.length;j++){ctx.fillStyle=black;if(j==snake.length-1){ctx.fillStyle=red;}ctx.beginPath();ctx.rect(snake[j].x*w,snake[j].y*w,w,w);ctx.closePath();ctx.fill();ctx.stroke();}//出现食物drawFood();//吃到食物if(head.x==food.x&&head.y==food.y){initFood();food=newFood(foodx,foody);//重新出现食物drawFood();//增加蛇的长度有些小瑕疵,蛇身增长时应该是身体增长,而不是在蛇头上增长varnewCell=newcell(head.x,head.y,head.d);switch(head.d){case40:newCell.y++;break;//下case39:newCell.x++;break;//右case38:newCell.y--;break;//上case37:newCell.x--;break;//左}snake[snake.length]=newCell;head=newCell;//head=}}//随机初始化食物functioninitFood(){foodx=Math.ceil(Math.random()*28+1);foody=Math.ceil(Math.random()*28+1);for(vari=0;isnake.length;i++){if(snake[i].x==foodx&&snake[i].y==foody){initFood();}}}//画食物functiondrawFood(){//绘制食物ctx.fillStyle=blue;ctx.beginPath();ctx.rect(food.x*w,food.y*w,w,w);ctx.closePath();ctx.fill();}draw();//监听键盘事件document.onkeydown=function(e){//下40,右边39,左边37,上38键盘事件varkeyCode=e.keyCode;if(head.d-keyCode!=2&&head.d-keyCode!=-2&&keyCode=37&&keyCode=40){moveSnake(keyCode);}}//控制蛇移动方向functionmoveSnake(keyCode){varnewSnake=[];varnewCell=newcell(head.x,head.y,head.d);//头//身体for(vari=1;isnake.length;i++){newSnake[i-1]=snake[i];}newSnake[snake.length-1]=newCell;newCell.d=keyCode;switch(keyCode){case40:newCell.y++;break;//下case39:newCell.x++;break;//右case38:newCell.y--;break;//上case37:newCell.x--;break;//左}snake=newSnake;head=snake[snake.length-1];checkDeath();draw();}//游戏规则functioncheckDeath(){//超出边框if(head.x=30||head.y=30||head.x0||head.y0){alert(Gameover!);window.location.reload();}//咬到自己for(vari=0;isnake.length-1;i++){if(head.x==snake[i].x&&head.y==snake[i].y){alert(Gameover!);window.location.reload();}}}//蛇自动走functionmoveClock(){moveSnake(head.d);}functionbeginGame(){setInterval(moveClock,600);}/script/html

1 / 7
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功