切换Java游戏中的玩家

时间:2017-10-20 17:12:44

标签: java

我试图为学习目的创建一个简单的游戏。这个游戏有两个玩家,每个玩家都有自己的对象。每转一圈,玩家都会转换。

每次是其他玩家转牌我都会使用以下方式切换玩家:

if (currentPlayer == playerOne)
{
    currentPlayer = playerTwo;
}
else if (currentPlayer == playerTwo)
{
    currentPlayer = playerOne;
}

请注意,currentPlayerplayerOne/Two是同一类的对象。

我想知道这样做是否不好或是否有更好的方法来切换播放器

2 个答案:

答案 0 :(得分:2)

可以这样做。然后,您的所有代码都会依赖currentPlayer来确定哪个播放器是当前播放器。

要做到这一点,两个玩家应该共享相同的类型,也许是Player类。您将当前播放器声明为:

Player currentPlayer;

构建你的球员

Player playerOne = new Player(...);
Player playerTwo = new Player(...);

请注意,...部分不是您要输入的内容,而是占位符,表示您在设计Player构造函数时要写的实际信息。

答案 1 :(得分:0)

您可以将玩家保留在列表中,并通过在该列表中获取其索引来切换它们:

 // initialize
 List<Player> players = Arrays.asList(new Player(...),new Player(...));
 Player currentPlayer = players.get(0);


 // switch Player:
 currentPlayer = players.get(1-players.indexOf(currentPlayer));

 // version for more than two players:
 // select the next player from list and restart with the first after the last:
 currentPlayer = players.get((players.indexOf(currentPlayer)+1)%players.size());

 // similar by cycling the list
 currentPlayer = players.remove(0); // get the next player from list
 players.add(currentPlayer); // put it at the end of the list