将球员添加到球队时遇到困难

时间:2014-09-30 18:53:52

标签: java bukkit

我正在使用Bukkit API为我的Bukkit服务器创建一个游戏引擎。在向该团队添加玩家时,我遇到以下方法的问题。

public void add(Player player) {
  // If the player is trying to join his existing team.
  if (players.containsKey(player)) {
    player.sendMessage(Chat.Info(getModuleName(), "You cannot join your existing team."));
    return;
  }
  // If the team slots are maximized.
  if (players.size() > size) {
    player.sendMessage(Chat.Info(getModuleName(), "That team is full at the moment."));
    return;
  }
  for (Team team: getTeams()) {
    if (team.getPlayers()
      .containsKey(player)) {
      team.remove(player);
      // break; - Removed, still not solved.
    }
  }
  players.put(player, this);
  // Checking if the player joined the team.
  if (players.containsKey(player)) {
    Main.log("Joined " + player.getName() + " to the " + this.name + ".", Level.INFO);
    player.sendMessage(Chat.Info(getModuleName(), "You have joined the " + getColor() + ChatColor.BOLD + getName() + "."));
  }
}

该特定方法是否存在问题?

如果是,该代码的问题是,它会将玩家加入该团队,但如果玩家已经在另一个团队中,那么将他从另一个团队的ArrayList中删除团队,因此,玩家将在多个团队中,在这种情况下,我想阻止它。

关于问题可能存在的任何想法?


更新 在使用消息调试之后,我意识到for-loop中的if语句返回false。这意味着存储播放器键的HashMap不包含播放器。 真奇怪

1 个答案:

答案 0 :(得分:1)

解决

我正在循环所有球队,而不是检查比赛的。


工作代码:

public void add(Game game, Player player)
{
    // If the player is trying to join his existing team.

    if (players.containsKey(player))
    {
        player.sendMessage(Chat.Info(getModuleName(), "You cannot join your existing team."));
        return;
    }

    // If the team slots are maximized.

    if (players.size() > size)
    {
        player.sendMessage(Chat.Info(getModuleName(), "That team is full at the moment."));
        return;
    }

    for (Team team : game.getTeams())
    {
        if (team.getPlayers().get(player) != this)
        {
            team.remove(game, player);
        }
    }

    players.put(player, this);

    // Checking if the player joined the team.

    if (players.containsKey(player))
    {
        Main.log("Joined " + player.getName()  + " to the " + this.name + ".", Level.INFO);

        player.sendMessage(Chat.Info(getModuleName(), "You have joined the " + getColor() + ChatColor.BOLD + getName() + "."));
    }
}