0

所以这是我的蛇脚本 -

http://jsfiddle.net/6bKHc/24/

我开始创建一个蛇游戏,但基本上 move(top), move(bottom) ec 不起作用。任何想法为什么?我知道我不能像这样将元素传递给变量,所以也许你可以告诉我如何正确地做到这一点?

4

2 回答 2

0

好的,清除语法并查看错误,这应该可以帮助您入门

$(document).keydown(function(event){
    var move, inter;
    inter = setInterval(move = function() {
        var dir = $(".snake").data('dir');
        var snake = $('.snake');

        if(dir == 'top') {
            snake.stop().animate({"top": "+=5px"});
        }
        if(dir == 'bottom') {
            snake.stop().animate({"top": "-=5px"});
        }
        if(dir == 'left') {
            snake.stop().animate({"left": "+=5px"});
        }
        if(dir == 'right') {
            snake.stop().animate({"top": "-=5px"});
        }
    }, 500);
    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');    
    }; });​

小提琴

几个明显的补充:

  • 边界检查
  • 动画的流畅度。
于 2012-06-22T09:20:21.097 回答
0

为了让它工作,你必须像下面这样修改你的代码:

$(document).keydown(function() {
    var inter;
    return function(event) {
        var move, prevDirection;
        clearInterval(inter);
        inter = setInterval(move = function(direction) {
            var value, prop;
            switch (direction || prevDirection) {
            case "top":
                prop = "top";
                value = -5;
                break;
            case "bottom":
                prop = "top";
                value = 5;
                break;
            case "left":
                prop = "left";
                value = -5;
                break;
            case "right":
                prop = "left";
                value = 5;
                break;
            }
            if (direction) prevDirection = direction;
            $(".snake").css(prop, $(".snake").position()[prop] + value);

        }, 500);
        if (event.which == 40) {
            move('bottom');
        } else if (event.which == 39) {
            move('right');
        } else if (event.which == 37) {
            move('left');
        } else if (event.which == 38) {
            move('top')
        };
    }
}());​
  ​

http://jsfiddle.net/6bKHc/42/

于 2012-06-22T09:02:10.283 回答