<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="jquery-3.2.1.min.js"></script> <script> var x=20; var y=20; var body = []; var head = "0td3"; var add; var e="right"; var int; $(function () { init(); }); //初始化 function init() { addtable(x,y); body = []; body.unshift("0td0"); body.unshift("0td1"); body.unshift("0td2"); head = "0td3"; e="right"; addsnake(body,head); addrandom(x,y); document.onkeydown=function (event) { var a = event || window.event || arguments.callee.caller.arguments[0]; if(a.keyCode==13) { start(); } } } //开始 function start() { $("#start").attr("disabled",true); int = setInterval("move(e)",200); document.onkeydown=function (event) { var a = event || window.event || arguments.callee.caller.arguments[0]; if(a.keyCode==37&&e!="right") { e = "left"; }else if(a.keyCode==38&&e!="down"){ e="up"; }else if(a.keyCode==39&&e!="left"){ e="right"; }else if(a.keyCode==40&&e!="u"){ e="down"; } } } //构建游戏画面 function addtable(a,b) { $("#table").empty(); for(var i=0;i<a;i++){ $("#table").append("<tr id='tr"+i+"'></tr>"); for(var j=0;j<b;j++){ $("#tr"+i).append("<td id='"+i+"td"+j+"'></td>"); } } } //把蛇展示到页面中 function addsnake(a,b) { $("#"+b).attr("class","snakehead"); for(var i=0;i<a.length;i++){ $("#"+a[i]).attr("class","snakebody"); } } //在随机位置添加食物 function addrandom(a,b) { var x = Math.floor(Math.random() * a); var y = Math.floor(Math.random() * b); add=x+"td"+y; while(body.indexOf(add)>=0||add==head){ var x = Math.floor(Math.random() * a); var y = Math.floor(Math.random() * b); add=x+"td"+y; } $("#"+add).attr("class","foot"); } //移动 function move(e) { var a = body.pop(); $("#"+ a).removeClass("snakebody"); body.unshift(head); if(e=="right"){ head=parseInt(head.split("td")[0])+"td"+(parseInt(head.split("td")[1])+1); }if(e=="left"){ head=parseInt(head.split("td")[0])+"td"+(parseInt(head.split("td")[1])-1); } if(e=="up"){ head=(parseInt(head.split("td")[0])-1)+"td"+(parseInt(head.split("td")[1])); } if(e=="down"){ head=(parseInt(head.split("td")[0])+1)+"td"+(parseInt(head.split("td")[1])); } if(head==add){ body.push(a); addrandom(x,y); } isend(body,head); addsnake(body,head); } //判断游戏是否结束 function isend(body,head) { var a=parseInt(head.split("td")[0]); var b=parseInt(head.split("td")[1]); if(a<0||a>x-1||b<0||b>y-1||body.indexOf(head)>=0){ init(); window.clearInterval(int); $("#start").attr("disabled",false); } } </script> <style> .body{ height: 500px; width: 500px; margin: 0px auto; } tr{ height: 20px; } td{ width: 20px; background: blanchedalmond; } .snakebody{ background: blue; } .snakehead{ background: red; } .foot{ background: green; } </style> </head> <body> <div class="body" > <table id="table"> </table> <button type="button" οnclick="start()" id="start">开始</button> </div> </body> </html>
js jq 贪吃蛇小游戏
最新推荐文章于 2022-05-27 14:12:08 发布