Get a Player from a Iterator Bukkit 1.16.5

Viewed 86

I have a problem that today is wearing me down deeply, I created a plugin that adds player to an arraylist when clicking in an inventory (I did so unfortunately because I'm not very good), the game is only one and contains 2 player, I can't make sure that if a player exits, through a method, he can give victory to the other Player, I tried a lot of methods, this is the last one (In this code below I try to put a method where if I remotely understood it should send a victory message to the player, which obviously it does not and then execute LobbyJoin, which is a method that takes you to the lobby):

private void makeWinSupport(Player winner, Player loser) {
    if (playerInGame.contains(winner) && playerInGame.contains(loser)) {
        winner.sendMessage(plugin.cc("&6(!) Hai vinto!"));
        LobbyJoin(loser);
        LobbyJoin(winner);
        playerInGame.remove(winner);
        playerInGame.remove(loser);
    }
}

public void makePlayerWin(Player loser) {
    Iterator<Player> i = playerInGame.iterator();
        System.out.println(1);
        if(i.hasNext() && i == loser) {
            makeWinSupport(i.next(), loser);

        } else {
            makeWinSupport(playerInGame.get(0), loser);
        }

    @EventHandler
public void onQuit(PlayerQuitEvent e) {
    e.setQuitMessage("");
    Player p = e.getPlayer();
    if(playerInGame.contains(p)) {
        makePlayerWin(p);
        }
    }
}
1 Answers

You can use PlayerQuitEvent to remove players from your plugin when they leave. I made this example assuming you have a list called yourPlayerList which stores the 2 competing players, but you can modify it to work with more players.

@EventHandler
public void onPlayerLeave(PlayerQuitEvent event) {
    if(yourPlayerList.remove(event.getPlayer())){//only true if the player was removed from the queue, which only happens if it was in the queue originally
        Player loser=event.getPlayer();//the loser
        Player winner=yourPlayerList.get(0);//the other player is still in the queue
        makeWinSupport(winner,loser);
    }
}

Don't forget to register the event in the event manager.

EDIT: If you want to remove the player from the list and only end the game if there is only one player left, you can do something like this:

@EventHandler
public void onPlayerLeave(PlayerQuitEvent event) {
    if(yourPlayerList.remove(event.getPlayer())&&yourPlayerList.size()==1){//removes the player and checks the amount of active players
        Player winner=yourPlayerList.get(0);
        //here you can call a method which accepts only the winning player. If you have 4 players, there is no reason to include a 'loser' player.
    }
}
Related