Java:更改玩家编号

时间:2012-11-22 02:53:15

标签: java

我正在编写一种方法,在每个玩家回合后切换玩家编号。我正在使用一个布尔数组来跟踪仍在播放的玩家(尚未被淘汰)。因此,游戏开始时的数组初始化为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;
}

有任何变更或建议吗?它不是很有效,也看不出它出了什么问题。

我试图实现其中一个答案,但我无法弄清楚如何实现它。有没有人有解决方案?

2 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分: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);