2

我正在编写一种在每个玩家轮到后切换玩家编号的方法。我正在使用一个布尔数组来跟踪仍在玩的玩家(尚未被淘汰)。所以游戏开始时的数组被初始化为true,是游戏中玩家人数的大小。当玩家被淘汰时,索引的相应值被设置为 false(例如,如果玩家 2 被淘汰,数组的第三个索引被设置为 false)。(注意:玩家 0 确实存在,所以如果有两个玩家在玩,他们是玩家 0 和玩家 1。)如果玩家编号等于最后一个玩家,那么它需要从头开始,找到第一个玩家还在游戏中。否则,玩家编号会增加到第一个仍在玩的玩家。这是我所拥有的:

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;
}

有什么改变或建议吗?它不太工作,看不到哪里出了问题。

我试图实现其中一个答案,但我不知道如何实现它。有没有人有办法解决吗?

4

2 回答 2

1

如果您有玩家 0,1,2,3。那么长度为 4。但参数currentPlayer只能有 0-3 值,因为那是玩家编号,所以尝试改变这个:

if(currentPlayer == playerList.length) {
    for(int i = 0; i < playerList.length; i++) {
        if(playerList[i] == true) {
            currentPlayer = i;
            break;
        }
    }
}

到:

if(currentPlayer + 1 == playerList.length) {
    for(int i = 0; i < playerList.length; i++) {
        if(playerList[i] == true) {
            currentPlayer = i;
            break;
        }
    }
}
于 2012-11-22T20:07:12.240 回答
0

如果您使用 ArrayList 数据结构来存储当前未淘汰的所有玩家会怎样。因此,当玩家被淘汰时,您可以从 ArrayList 中删除该对象。这样您就不需要使用布尔值来跟踪玩家状态。

public static int switchPlayer(int currentPlayer, ArrayList playerList) {
    // move to the next player
    currentPlayer++;

    // reset back to the first player if we reached the end player
    if(currentPlayer >= playerList)
        currentPlayer = 0;

    return currentPlayer;
}

现在,最初,在您的代码的某些部分中,我认为您将值设置为“false”以指示用户已被淘汰。但是,我的想法是删除被淘汰的玩家。例如,如果您希望第二个玩家被淘汰,那么您可以在数组列表中执行以下操作:

list.remove(2);
于 2012-11-22T02:56:28.327 回答