这是 jsfiddle 示例 - http://jsfiddle.net/6bKHc/120/和代码 -
var move, inter;
inter = setInterval(move = function() {
var dir = $(".snake").data('dir');
var snake = $('.snake');
var food = $('.food');
if(dir == 'top') {
snake.css({"top": snake.position().top + 5 + "px"});
if(snake.width() > 5) {
snake.css({"width": snake.width() - 5 + "px", "height": snake.height() + 5 + "px"});
}
}
if(dir == 'bottom') {
snake.css({"top": snake.position().top - 5 + "px"});
if(snake.width() > 5) {
snake.css({"width": snake.width() - 5 + "px", "height": snake.height() + 5 + "px"});
}
}
if(dir == 'left') {
snake.css({"left": snake.position().left + 5 + "px"});
if(snake.height() > 5) {
snake.css({"width": snake.width() + 5 + "px", "height": snake.height() - 5 + "px"});
}
}
if(dir == 'right') {
snake.css({"left": snake.position().left - 5 + "px"});
if(snake.height() > 5) {
snake.css({"width": snake.width() + 5 + "px", "height": snake.height() - 5 + "px"});
}
}
var snakePosition = snake.position();
var foodPosition = food.position();
var randomNum = Math.ceil(Math.random()*40);
var randomNumber = randomNum*5;
console.log(snakePosition.top + " - snake top + left - " + snakePosition.left);
console.log(foodPosition.top + " - snake top + left - " + foodPosition.left);
if(snakePosition.top == foodPosition.top && snakePosition.left == foodPosition.left) {
console.log(randomNumber);
snake.css({"width": snake.width() + 55 + "px"});
food.css({"left": randomNumber+1+"px", "top": randomNumber+1+"px"});
}
}, 200);
$(document).keydown(function(event){
if(event.which == 40) {
$(".snake").data('dir','top');
} else if(event.which == 39) {
$(".snake").data('dir','left');
} else if(event.which == 37) {
$(".snake").data('dir','right');
} else if(event.which == 38) {
$(".snake").data('dir','bottom');
};
});
当蛇变大时,它会自动使块也变大,我的意思是当你向下移动时,它不会在一侧停留 5px。我不知道如何描述它,但只要开始游戏并尝试吃食物然后移动,你就会明白我的意思。