switch (key) {
case 37:{
if (direction != "right") {
direction = "left";
}
break;
}
case 38:{
if (direction != "down") {
direction = "up";
}
break;
}
case 39:{
if (direction != "left") {
direction = "right";
}
break;
}
case 40:{
if (direction != "up") {
direction = "down";
}
break;
}
}
});
function createFood(){
$('#box_' + pos_food.X + '_' + pos_food.Y).attr("class", "");
var x = 0, y = 0;
var isCover = false;
do {
x = parseInt(Math.random() * (width - 1));
y = parseInt(Math.random() * (height - 1));
if (pos_snake instanceof Array) {
for (var i = 0; i < pos_snake.length; i++) {
if (x == pos_snake[i].X && y == pos_snake[i].Y) {
isCover = true;
break;
}
}
}
}
while (isCover);
pos_food.X = x;
pos_food.Y = y;
$('#box_' + pos_food.X + '_' + pos_food.Y).addClass("food");
}
function snakeMove(){
eat();
var head = pos_snake[pos_snake.length - 1];
$("#box_" + pos_snake[0].X + "_" + pos_snake[0].Y).removeClass("snake");
for (var i = 0; i < pos_snake.length - 1; i++) {
pos_snake[i].X = pos_snake[i + 1].X;
pos_snake[i].Y = pos_snake[i + 1].Y;
}
switch (direction) {
case 'left':
head.X--;
break;
case 'up':
head.Y--;
break;
case 'down':
head.Y++;
break;
case 'right':
head.X++;
break;
}
pos_snake[pos_snake.length - 1] = head;
for (var i = 0; i < pos_snake.length; i++) {
var isExits = false;
for (var j = i + 1; j < pos_snake.length; j++) {
if (pos_snake[j].X == pos_snake[i].X && pos_snake[j].Y == pos_snake[i].Y) {
isExits = true;
break;
}
}
if (isExits) {
clearInterval(interval);
alert("咬到自己,游戏结束!");
window.location.reload();
break;
}
$("#box_" + pos_snake[i].X + "_" + pos_snake[i].Y).addClass("snake");
if ($("#box_" + pos_snake[i].X + "_" + pos_snake[i].Y).length <= 0) {
clearInterval(interval);
alert("撞到墙了,游戏结束!");
window.location.reload();
break;
}
}
}