Greedy Bear
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Greedy Bear</title>
<style type="text/css">
tb{background-color:#fff;}
.head{background-color:Red;}
.tail{background-color:Black;}
.fish{background-color:Green;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var height = 10;
var width = 10;
var length = 1;
var tail = [];
var speed = 1000;
var direction = "right";
var timerID;
$(document).ready(function () {
//初始化游戏界面
$(this).find("body").append("<table border='0' cellspacing='1px' cellpadding='2px' bgcolor='#e0e0e0'></table>");
for (var i = 0; i < height; i++) {
$(this).find("table").append("<tr height='20'></tr>");
for (var j = 0; j < width; j++) {
//给每行,划分若干个单元格
$(this).find("table tr").last().append("<td id='td_" + i + "_" + j + "' width='20'></td>");
}
}
//设置蛇开始的位置。
$(this).find("td").first().addClass("head");
//初始化一条鱼
setFish();
//每个多少时间调用一下Move
timerID = window.setInterval(move, speed);
//响应键盘事件
$(this).keydown(function (event) {
if (event.which == 37) {
direction = "left";
}
else if (event.which == 38) {
direction = "up";
}
else if (event.which == 39) {
direction = "right";
}
else if (event.which == 40) {
direction = "down";
}
else {
return;
}
//防止点一次键盘,时间缩短一些。
window.clearInterval(timerID);
//重新设置间隔
if (move()) {
timerID=window.setInterval(move, speed);
}
});
});
function move() {
//找到舌头
var headEle = $("td[className='head']");
var headId = headEle.attr("id");
if (typeof headId == 'undefined') {
window.clearInterval(timerID);
return false;
}
var att = headId.split("_");
var nextHead, nextId;
//计算蛇下一个位置
if (direction == "right") {
nextId = "td_" + att[1] + "_" + (parseInt(att[2]) + 1);
}
else if (direction == "left") {
nextId = "td_" + att[1] + "_" + (parseInt(att[2]) - 1);
}
else if (direction == "up") {
nextId = "td_" + (parseInt(att[1]) - 1) + "_" + att[2];
}
else if (direction == "down") {
nextId = "td_" + (parseInt(att[1]) + 1) + "_" + att[2];
}
nextHead = $("#" + nextId);
if (typeof nextHead.attr("id") == 'undefined') {
window.clearInterval(timerID);
alert("fail");
return false;
}
//头变成尾巴。蛇每移动一下,tail数组就会增加一个。
headEle.addClass("tail");
tail[tail.length] = headEle;
//遇到鱼的时候,tail数组就不减去刚刚增加的。
if (nextHead.hasClass("fish")) {
nextHead.removeClass("fish");
length++;
setFish();
}
else {
//减去刚刚增加的鱼
tail[0].removeClass("tail");
tail = tail.slice(1);
}
//headEle.addClass("tail");
nextHead.addClass("head");
headEle.removeClass("head");
return true;
}
function setFish() {
var x = Math.floor(Math.random()*height);
var y = Math.floor(Math.random()*width);
$("#td_"+x+"_"+y).addClass("fish");
}
</script>
</head>
<body>
</body>
</html>