2011-07-28 57 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