How to make alternating turns in Java?

纵然是瞬间 提交于 2019-12-02 07:32:16

in your main method create some form of while loop that checks if the game is over.

while(!gameEnded)
{
    playerTurn();
    computerTurn();
}

unless you are asking how to make it the computer plays first then next turn player plays first. in that case add a counter to track who went last.

while(!gameEnded)
{
    if(counter%2 = 0)
    {
        playerTurn();
        computerTurn();
    }
    if(counter%2 = 1)
    {            
        computerTurn();
        playerTurn();
    }
    couter++;
}

To randomly select the player that goes first on turn one you can initialize the counter with an odd or even number.

int counter = Math.random()*2;
do {
    //
    // Other code from above as required.
    // ...
    //

    computerTurn(); // invoke the computerTurn() method
    //
    // Can numStonesLeft be 0 after the computer turn?
    // If so, perhaps you need an extra check...
    //
    playerTurn(); // invoke the playerTurn() method  
} while (numStonesLeft> 0);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!