2017-04-10 72 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