<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>game</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<style>
.head{background-color:red;}
.fish{background-color:blue;}
.tail{background-color:green;}
td{background-color:#fff;}
</style>
<script type="text/javascript">
var w=h=10,t,tail=[],speed=200;//宽高以及速度
var d="right";
var length=1;
$(document).ready(function(){
$(this).find("body").append("<table border='0' cellspacing='1px' cellpadding='2px' bgcolor='#e0e0e0'></table>");
for(var i=0;i<h;i++){
$(this).find("table").append("<tr height='20'></tr>");
for(var j=0;j<w;j++){
$(this).find("table tr").last().append("<td id='td_"+i+"_"+j+"' width='20'></td>");
}
}
$(this).find("td").first().addClass("head");
setFish();
t = window.setInterval(move,speed);
$(this).keydown(function(event){
if(event.which==37){
if(d == "right") return;
d = "left";
}else if(event.which==38){
if(d == "down") return;
d = "up";
}else if(event.which==39){
if(d == "left") return;
d = "right";
}else if(event.which==40){
if(d == "up") return;
d = "down";
}else{
return;
}
window.clearInterval(t);
if(move()){
t = window.setInterval(move,speed);
}
});
});
function move(){
var headTd = $("td[className='head']");
var headId = headTd.attr("id");
var arr = headId.split("_");
var nextHead,nextId;
if(d=="left"){
nextId = "td_"+arr[1]+"_"+(parseInt(arr[2])-1);
}else if(d=="up"){
nextId = "td_"+(parseInt(arr[1])-1)+"_"+arr[2];
}else if(d=="right"){
nextId = "td_"+arr[1]+"_"+(parseInt(arr[2])+1);
}else if(d=="down"){
nextId = "td_"+(parseInt(arr[1])+1)+"_"+arr[2];
}
nextHead = $("#"+nextId);
if(typeof nextHead.attr("id")=='undefined'){
window.clearInterval(t);
alert("失败");
return false;
}else if(nextHead.hasClass("tail")&&nextHead.attr("id")!=tail[0].attr("id")){
window.clearInterval(t);
alert("失败");
return false;
}
headTd.addClass("tail");
tail[tail.length] = headTd;
if(nextHead.hasClass("fish")){
nextHead.removeClass("fish");
length++;
if(length>Math.sqrt(w*h)){
window.clearInterval(t);
alert("恭喜!成功过关");
return false;
}
setFish();
}else{
tail[0].removeClass("tail");
tail = tail.slice(1);
}
nextHead.addClass("head");
headTd.removeClass("head");
return true;
}
function setFish(){
var x = Math.floor(Math.random()*w);
var y = Math.floor(Math.random()*h);
$("#td_"+x+"_"+y).addClass("fish");
}
</script>
</head>
<body>
</body>
</html>
js版贪吃蛇
最新推荐文章于 2024-01-28 17:49:34 发布