I am writing a method to switch the player number after each player’s turn. I am using a boolean array that keeps track of the players still playing (that have not been eliminated). So the array at the beginning of the game is initialized to true and is the size of the number of players in the game. As players get eliminated, the corresponding value of the index gets set to false (For example if Player 2 gets eliminated, the third index of the array gets set to false). (Note: Player 0 does exist, so if two players are playing they are Players 0 and Player 1.) If the player number is equal to the last player, then it needs to start back at the beginning and find the first player that is still in the game. Otherwise, the player number increments to the first player that is still playing. Here is what I have:
public static int switchPlayer(int currentPlayer, boolean[] playerList) {
if(currentPlayer == playerList.length) {
for(int i = 0; i < playerList.length; i++) {
if(playerList[i] == true) {
currentPlayer = i;
break;
}
}
}
else {
for(int i = (currentPlayer+1); i < playerList.length; i++) {
if(playerList[i] == true) {
currentPlayer = i;
break;
}
}
}
return currentPlayer;
}
Any changes or suggestions? It is not quite working and cannot see where it is going wrong.
I have tried to implement one of the answers, but I cannot figure out how to get it implemented. Does anyone have a solution?
If you have Players 0,1,2,3. Then length is 4.
But the argument
currentPlayercan only have 0-3 value, since thats the player numbers, so try changing this:to: