话不多说,请看代码:
& lt; !doctype html> & lt; html lang=癳n”比; & lt; head> & lt;元charset=皍tf - 8”比; & lt; title>贪吃蛇& lt;/title> & lt;链接rel="样式表" href=" https://www.yisu.com/zixun/style.css "比; & lt;脚本src=" https://www.yisu.com/zixun/style.js "祝辞& lt;/script> & lt;/head> & lt; body> & lt; div id="容器"祝辞& lt;/div> & lt;/body> & lt;/html>
<强>第一步:初始化地图,创建蛇圈。
第二步:创建蛇,随机生产食物。
第三步:让蛇移动起来。
第四步:通过js绑定键盘事件,控制蛇移动方向。强>
var盒={宽度:50岁,身高:50},//每一个方块的高度 蛇var=[];//保存蛇每一节身体对应的跨度 var DIR={ DIR_RIGHT: 1、 DIR_LEFT: 2 DIR_TOP: 3, DIR_BOTTOM: 4 }; var dir=DIR.DIR_BOTTOM; var食品=零;//始终记录当前的食物 window=function () {//1 .初始化地图 initMap ();//2 .创建蛇//2.5随机显示食物 showFood (); createSnake ();//3 .让蛇动起来 setInterval (snakeMove, 100);//4 .控制蛇移动 document.onkeyup=function (e) { 开关(e.keyCode) { 例37:dir=DIR.DIR_LEFT;断裂; 例38:dir=DIR.DIR_TOP;断裂; 例39:dir=DIR.DIR_RIGHT;断裂; 例40:dir=DIR.DIR_BOTTOM;断裂; } } }; 顶部功能isInSnakeBody(左){ 我(var=0; i< snake.length;我+ +){ 如果蛇[我].offsetTop==top&,蛇[我].offsetLeft==左){ 返回true; } } }//这种随机生成食物的方法效率低,随着蛇身体的增长,随机生成食物的时间会变慢。 函数showFood () { var con=. getelementbyid(“容器”); 食物=document.createElement(“跨度”); food.className=笆澄铩? food.style.width=box.width +“px”; food.style.height=box.height +“px”; var,最高; {做 左=Math.floor ((con.offsetWidth-2)/box.width * math . random ()) * box.width; 顶级=Math.floor ((con.offsetHeight-2)/box.height * math . random ()) * box.height; },(isInSnakeBody(左); food.style.left=左+“px”; food.style.top=最高+“px”; con.appendChild(食物); } 函数initMap () { var con=. getelementbyid(“容器”); var行=Math.floor (con.offsetWidth/box.width); 高校var=Math.floor (con.offsetHeight/box.height); var num=行*的方式; var newSpan=零; (var i=1; i<=num;我+ +){ newSpan=document.createElement(“跨度”); newSpan.style.width=box.width +“px”; newSpan.style.height=box.height +“px”; con.appendChild (newSpan); } } 函数createSnake () { var newBody=零; var con=. getelementbyid(“容器”); (var i=1; i<=5;我+ +){ newBody=document.createElement(“跨度”); newBody.style.width=box.width +“px”; newBody.style.height=box.height +“px”; newBody.style.left=(张)* box.width +“px”; newBody.style.top=" 0 px”; newBody.className=吧摺? con.appendChild (newBody); snake.push (newBody); } } 函数snakeMove () { var con=. getelementbyid(“容器”);//蛇头移动 var头=蛇(snake.length-1); var newTop=head.offsetTop,新左派=head.offsetLeft; 开关(dir) { 案例DIR.DIR_LEFT:新左派——=box.width;打破; 案例DIR.DIR_RIGHT:新左派+=box.width;打破; 案例DIR.DIR_TOP: newTop -=box.height;打破; 案例DIR.DIR_BOTTOM: newTop +=box.height;打破; 默认值:休息; }//如果超出边界,计算蛇头下一个位置的坐标 如果(newLeft> con.offsetWidth-2-1){新左派=0;} 如果(newLeft<0){新左派=con.offsetWidth-2-box.width;} 如果(newTop<0) {newTop=con.offsetHeight-2-box.height;} 如果(newTop> con.offsetHeight-2-1) {newTop=0;}//判断新蛇头的位置是不是在蛇身体里面//(var=0; ijs实现贪吃蛇小游戏(容易理解)