2011-07-28 58 views
2

我想写一个程序来说明"Towers of Hanoi"拼图的程序化解决方案,其中磁盘由不同大小的绝对定位的div-s表示。为了使一招我有这样的函数:jQuery动画顺序没有回调

function move(peg_from, peg_to) 
{ 
//check if the move is valid 
//update the game state 
//...... 
//get the div we are moving, calculate it's new position 
//move: 
the_div.animate({left: new_left, top: new_top}, 500); 
} 

然后向溶液中可能看起来是这样的:

move(1, 3); 
move(1, 2); 
move(3, 2); 
//... etc... 

或递归,或什么的。无论如何,我希望能够'评估'任何代码,根据move(x,y)定义,而不是根据jQuery的动画或回调函数来定义。问题是,所有动画都是同时发生的,而它需要处于通话顺序。有没有办法做到这一点?

我曾尝试将.delay()添加到动画中,也许它可以工作,但无论如何我无法弄清楚正确的超时时间。 setTimeout()没有任何可见的效果。谷歌搜索显示使用动画回调的一些建议,但我不认为它们适用于我的情况。

+0

与工作游戏更新的答案(*手册*) –

回答

7

答案A non-nested animation sequence in jQuery?您的问题相匹配,以及(很少修改)..

您需要.queue()您animatios ..

var q = $({}); 

function moveToQueue(eg_from, peg_to) { 
    q.queue(function(next) { 
     //check if the move is valid 
     //update the game state 
     //...... 
     //get the div we are moving, calculate it's new position 
     //move: 
     the_div.animate({left: new_left, top: new_top}, 500, next); 
    }); 
} 


// usage 
moveToQueue(1, 3); 
moveToQueue(1, 2); 
moveToQueue(3, 2); 

更新

因为我喜欢它..
这里是一个完整的工作解决方案.. http://jsfiddle.net/gaby/nZ4MU/

+0

更新与完整的功能.. –

+0

谢谢。这是我做的:http://lazunin.com/hanoi.html – Headcrab

+1

顺便说一句,移动所有的游戏逻辑在函数之外(next){}是不是更好。 G。只留下大括号the_div.animate(...);并将其他所有事物都调高一级?尤其是因为对moveToQueue的调用不一定会添加动画(移动可能无效)。 – Headcrab