0
我正在用Bukkit爲我的Minecraft創建一個minigame引擎,但是好像在將遊戲添加到遊戲時存在問題。在成功添加玩家之後,他有能力再次加入,因此不止一次參加。防止hashmap鍵條目多次添加?
這真的很奇怪,因爲在我的if語句中,我會檢查參與者的HashMap是否包含播放器密鑰。如果是這樣,它不應該讓他再次參加比賽。
這是我的方法。
public void addPlayer(Client client) {
// Checks if the game is waiting, and the slots are sufficient.
if (game.isWaiting() && !game.isFull() && !game.getClients().containsKey(client)) {
Random random = new Random();
int teamChance = random.nextInt(game.getTeams().size());
// Adding the player to the match and assigning the default kit.
game.getClients().put(client, game.getDefaultKit());
// Adding the player to a team.
game.getTeams().get(teamChance).add(client);
// Checking if the slots are now maximum, prepare the game.
if (game.isFull()) {
prepareGame();
}
// If the player was added.
if (game.getClients().containsKey(client))
{
Main.log("Added " + client.getName() + " (" + game.getCurrentSlots() + "/" + game.getSlots() + ")" + " to " + game.getType().getName() + " (" + game.getWorld().getName() + ").", Level.INFO);
game.broadcast("Join", client.getName() + " (" + game.getCurrentSlots() + "/" + game.getSlots() + ")");
client.getPlayer().teleport(game.getWorld().getSpawnLocation());
client.reset();
// Adding lobby items to the player's inventory.
new LobbyManager(game);
}
}
從Game
類。
private HashMap<Client, Kit> clients;
// ...
public HashMap<Client, Kit> getClients() {
return this.clients;
}
如何修改此方法以防止玩家被多次添加到遊戲中?
非常感謝您的幫助。
客戶:http://pastebin.com/Fmgc0T3C
你在'Client'類中實現了'equals()'和'hashCode()'嗎? – 2014-10-12 13:20:56
嗯,因爲我對Java來說是一個相當新的東西,似乎玩家被添加,但兩次,因爲客戶端像播放器的包裝類(爲了實現我自己的方法)工作。不,我沒有。 – Biskotaki 2014-10-12 13:22:11
你在使用線程嗎? – conFusl 2014-10-12 13:22:39