2014-09-30 57 views
0

我正在使用Bukkit API为我的Bukkit服务器创建一个使用Java的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语句错误。这意味着存储玩家密钥的HashMap不包含玩家。 真的很奇怪

+0

那么首先,你的增强的for循环的,如果球员在其他球队存在检查爆发。删除中断;声明。 – proulxs 2014-09-30 18:56:45

+0

尝试删除“for(Team team:getTeams())'循环中的'break;'。 – Pokechu22 2014-09-30 18:57:58

+0

感谢您的注意,我只是删除它,但问题似乎仍然存在。立即更新问题。 – Biskotaki 2014-09-30 18:58:25

回答

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() + ".")); 
    } 
}