2017-04-10 70 views
0

我有一個功能,遊戲(),它看起來像這樣:Android的處理器運行的異步

public void gamePlay() 
{ 
    for (int i = 0; i < 4; i++) 
    { 
     currentRound = i; 
     if (i == 0) 
     { 
      simulateTurns(); 
     } 
     if(i == 1) 
     { 
      simulateTurns(); 
     } 
     if (i > 1) 
     { 
      simulateTurns(); 
     } 
    } 
} 

simulateTurns()使用與Looper.getMainLooper()的參數實例化的處理程序如下之前的遊戲()是曾經被稱爲:

thread = new Handler(Looper.getMainLooper()); 

simulateTurns():

public void simulateTurns() 
{ 
    currentPlayer = players[playerIndex % numPlayers]; 

    if(currentPlayer.getPlayerID() == USER_ID) //user 
    { 
     if(!currentPlayer.hasFolded()) 
      showUserOptions(currentRound); 
     else 
     { 
      playerIndex++; 
      simulateTurns(); 
     } 
    } 
    else 
    { 
     hideUserOptions(0); 

     // Give players the option to raise, call, fold, checking (dumb for now, needs AI and user input) 
     // currentPlayer.getPlayerID() gets the current ID of the player 
     int randAction = (int) (Math.random() * 4); 
     String action = ""; 


     //DEBUG Simulate game 
     Log.w("--------DEBUG--------", "Round: " + currentRound + " Bot: " + currentPlayer.getPlayerID() + " action: " + action + " pot: " + pot); 

     thread.postDelayed(new Runnable(){ 
      public void run() 
      { 
       if(!betsEqual()) 
        simulateTurns(); 
      }}, 5000); 
    } 
} 

在調試日誌,所有輪次看m並行開始,然後記錄第3輪的幾圈。

如何讓for循環與simulateGame()同步運行,以便循環順序運行?

注意:我也在幾個onClickListeners上調用了simulateTurns()。

+0

我發現你的代碼很混亂。也許你應該考慮重新設計它 – nandsito

+0

有一個混亂,但thread.postDelayed也許你的問題。你想要的是每次停止/暫停/睡眠5秒鐘,是不是?如果那樣,改變這個代碼,處理程序不能像這樣工作。 –

回答

1

你的代碼似乎很混亂。如果你試圖按順序模擬一個轉向,你不應該使用異步函數,因爲它意圖是異步的,而你並不尋求這種行爲。

假設你試圖做異步的事情,因爲你正在等待事情發生(或者因爲你不想阻塞UI線程),你將不得不做一些改變,然後再做任何事情。

您正在使用全局變量進行循環計數。這意味着你的循環正在執行真正快速啓動的一切,然後執行異步調用,因此,變量對於所有調用都是max(3)。

你應該有一個叫做「StartNextRound()」的函數,這個函數在你的「simulateTurn()」的末尾被調用。此功能應該檢查,而需要開始新一輪(i < 4),然後調用您的simulateTurn()的新實例。

讓我們總結一下:在需要之前不要啓動異步任務。使用函數啓動新一輪,並在前一輪結束時調用該函數。

這是處理異步字符最簡單的方法。其他選項更加複雜(可能不是內存高效),並且涉及線程之間的處理程序,以便能夠一次啓動所有任務並使其休眠,直到正確的一輪啓動。這是一件非常艱苦的工作,以保持一些不太正確的東西(並且似乎在那裏「出於測試」的目的)。

+0

你的第二個建議幫助我使我的程序工作。非常感謝你! – user3217494

+0

那你能否接受答案,或解釋你爲更多讀者所做的事情? – Feuby

+0

我的確如你所做的那樣,用simulateTurns()函數調用開始回合, – user3217494