net.flutterflies.fwapaderp.game.TeamManager.java Source code

Java tutorial

Introduction

Here is the source code for net.flutterflies.fwapaderp.game.TeamManager.java

Source

/**
 * Distributed as part of Fwap'a Derp UHC. A UHC plugin for Spigot 1.9
 * made by Ashrynn Macke (Flutterflies). You should have received a copy
 * of the MIT license with this code, if not please find it here:
 * https://opensource.org/licenses/MIT
 */
package net.flutterflies.fwapaderp.game;

import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvParser;
import net.flutterflies.fwapaderp.FwapaDerp;
import net.flutterflies.fwapaderp.scoreboard.UHCTeam;
import net.flutterflies.fwapaderp.utils.StringRef;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;

/**
 * Manages all instances of UHCTeam
 */
public class TeamManager {

    //Instance of the main plugin class
    private final FwapaDerp plugin;

    //The List of Teams
    private ArrayList<UHCTeam> teamList;

    //List of all players alive, linked to their respective team <player, team>
    private Map<String, String> playerMap;

    //List of all dead players
    private ArrayList<Player> deadPlayers;

    /**
     * Construct a new instance of the team manager
     *
     * @param plugin instance of the main plugin class
     */
    public TeamManager(FwapaDerp plugin) {
        this.plugin = plugin;

        teamList = new ArrayList<>();
        playerMap = new HashMap<>();
        deadPlayers = new ArrayList<>();
    }

    public void assignPlayers(Collection<? extends Player> players) {
        plugin.getLogger().info("Online Players: " + players.size());
        Scoreboard scoreboard = plugin.getGameManager().getScoreboardManager().getScoreboard();

        for (Player player : players) {
            Team sbTeam = scoreboard.getTeam(findTeamByPlayer(player.getName()).getTeamColor());
            assignPlayer(player, sbTeam);
        }
    }

    public void assignPlayer(Player player, Team team) {
        // Try to add a player; if the player doesn't exist, skip
        try {
            team.addEntry(player.getName());
        } catch (NullPointerException ignored) {
            plugin.getLogger().severe(Arrays.deepToString(player.getScoreboard().getTeams().toArray(new Team[1])));
        }
    }

    /**
     * Converts a .csv spreadsheet template into a UHCTeam object
     *
     * @param teamsList Used purely as a reference to an earlier object, overwriting it
     * @return A list of all UHCTeams
     */
    public ArrayList<UHCTeam> createTeamsFromCSV(ArrayList<UHCTeam> teamsList) {
        ArrayList<String[]> rows = new ArrayList<>();
        File teamsFile = new File(plugin.getDataFolder(), "teams.csv");
        CsvMapper mapper = new CsvMapper();

        //Clear any existing teams on the team list
        teamsList.clear();

        mapper.enable(CsvParser.Feature.WRAP_AS_ARRAY);

        //Try to load values from teams.csv
        try {
            MappingIterator<String[]> iterator = mapper.readerFor(String[].class).readValues(teamsFile);
            while (iterator.hasNext()) {
                rows.add(rows.size(), iterator.next());
            }
        } catch (IOException e) {
            plugin.getLogger().log(Level.SEVERE, "Could not find the file teams.csv! Please either supply"
                    + "a teams.csv file or disable usePreMadeTeams in the plugin's config file.");
            System.exit(0);
        }

        //For each row in the csv file create a new team
        for (int i = 1; i < rows.size(); i++) {
            String[] team = rows.get(i);
            List<String> teamPlayerList = new ArrayList<>();
            for (int j = 2; j < team.length; j++) {
                if (!team[j].equals("")) {
                    teamPlayerList.add(teamPlayerList.size(), team[j]);
                }
            }
            teamsList.add(teamsList.size(),
                    new UHCTeam(team[0], team[1].toUpperCase().replace(' ', '_'), teamPlayerList));
        }

        //Write Teams to a yaml file
        for (int i = 0; i < teamList.size(); i++) {
            //Get the team
            UHCTeam team = teamList.get(i);

            //Write the team name
            plugin.getTeamConfig().set("teams.team" + (i + 1) + ".name", team.getTeamName(false));
            //Write the team's color
            plugin.getTeamConfig().set("teams.team" + (i + 1) + ".color", team.getTeamColor());
            //Write all the players in the team
            for (int j = 0; j < team.getTeamSize(); j++) {
                plugin.getTeamConfig().set("teams.team" + (i + 1) + ".players.player" + (j + 1),
                        team.getPlayers().get(j));
            }
        }
        plugin.saveTeamsConfig();

        return teamsList;
    }

    /**
     * Finds the team of which the player is a member
     *
     * @param player Player to find
     * @return The team the player was found in
     */
    public UHCTeam findTeamByPlayer(String player) {
        UHCTeam playerTeam = null;

        for (UHCTeam team : teamList) {
            if (team.contains(player)) {
                playerTeam = team;
            }
        }

        return playerTeam;
    }

    /**
     * Finds the team of which the color is the team's identifier
     *
     * @param teamColor Color to find
     * @return The team using the color
     */
    public UHCTeam findTeamByColor(String teamColor) {
        UHCTeam uhcTeam = null;
        teamColor = teamColor.toUpperCase().replace(" ", "_");

        for (UHCTeam team : teamList) {
            if (team.getTeamColor().equals(teamColor)) {
                uhcTeam = team;
            }
        }

        return uhcTeam;
    }

    /**
     * Lists all the teams registered, including their members, and sends them to chat
     *
     * @param sender The issuer of the command
     */
    public void listAllTeams(CommandSender sender) {
        // Initial part of the message
        String msg = ChatColor.AQUA + "==================\n" + ChatColor.GREEN + "Teams:\n";

        // Loop through every team, displaying team name, color and members
        for (UHCTeam team : teamList) {
            msg += "- " + team.getTeamColorCode() + team.getTeamName(false) + " [" + team.getTeamColor() + "]"
                    + ChatColor.GREEN + " (";

            for (int i = 0; i < team.getTeamSize(); i++) {
                msg += "" + team.getTeamColorCode() + team.getPlayers().get(i) + ChatColor.GREEN;

                if (i < team.getTeamSize() - 2) {
                    msg += ", ";
                }

                if (i == team.getTeamSize() - 2) {
                    msg += " and ";
                }
            }

            msg += ")\n";
        }

        msg += ChatColor.AQUA + "\n==================" + ChatColor.RESET;

        // Send a private message to the issuer of the command
        sender.sendMessage(msg);
    }

    /**
     * List a single team, specified by the color of the team
     *
     * @param teamColor The color to identify the team with
     * @param sender The issuer of the command
     */
    public void listTeam(String teamColor, CommandSender sender) {
        // Find the team to list
        UHCTeam team = findTeamByColor(teamColor.toUpperCase().replace(" ", "_"));

        if (team == null) {
            // If the team wasn't found, display a message to the user
            sender.sendMessage(ChatColor.DARK_RED + teamColor.toUpperCase().replace(" ", "_")
                    + "wasn't a valid team color!" + ChatColor.RESET);
        } else {
            // Else, build the message for the target team
            String msg = ChatColor.AQUA + "==================\n" + ChatColor.GREEN + team.getTeamColorCode()
                    + team.getTeamName(false) + " [" + team.getTeamColor() + "]" + ChatColor.GREEN + " (";

            for (int i = 0; i < team.getTeamSize(); i++) {
                msg += "" + team.getTeamColorCode() + team.getPlayers().get(i) + ChatColor.GREEN;

                if (i < team.getTeamSize() - 2) {
                    msg += ", ";
                }

                if (i == team.getTeamSize() - 2) {
                    msg += " and ";
                }
            }

            msg += ")\n" + ChatColor.AQUA + "==================" + ChatColor.RESET;

            // Send the information to the issuer
            sender.sendMessage(msg);
        }
    }

    /**
     * Generates a player map, containing all alive players linked to their team
     *
     * @param teamList The list of UHCTeams the match started with
     * @return The player map
     */
    public Map<String, String> makePlayerMap(ArrayList<UHCTeam> teamList) {
        Map<String, String> playersMap = new HashMap<>();

        for (UHCTeam team : teamList) {
            for (String player : team.getPlayers()) {
                // Team color is used as an identifier per team
                playersMap.put(player, team.getTeamColor());
            }
        }

        return playersMap;
    }

    /**
     * Make a player switch between teams
     *
     * @param playerName The name of the player to move
     * @param teamColor The color of the destination team
     * @param sender The issuer of the command
     */
    public void movePlayer(String playerName, String teamColor, CommandSender sender) {
        // Find the player and team color
        Player player = Bukkit.getPlayer(playerName);
        teamColor = teamColor.toUpperCase().replace(" ", "_");

        // Check if the player is valid (online/alive)
        if (player == null || !Bukkit.getOnlinePlayers().contains(player)) {
            sender.sendMessage(ChatColor.DARK_RED + "The player you are looking for isn't online at the moment!"
                    + ChatColor.RESET);
        } else if (deadPlayers.contains(player)) {
            sender.sendMessage(
                    ChatColor.DARK_RED + "The player you are targeting is already dead!" + ChatColor.RESET);
        } else {
            Team scTeam = player.getScoreboard().getEntryTeam(playerName);

            // Check if the player is on a scoreboard team
            if (scTeam == null) {
                sender.sendMessage(ChatColor.DARK_RED + "The player you targeted doesn't have a team attached!"
                        + ChatColor.RESET);
            } else {
                // Check if the color input was valid (if there was a team with that color value)
                if (findTeamByColor(teamColor) == null) {
                    sender.sendMessage(ChatColor.DARK_RED
                            + "The team you want to move to doesn't match any team names!" + ChatColor.RESET);
                } else if (findTeamByColor(teamColor).contains(playerName)) {
                    sender.sendMessage(ChatColor.DARK_RED + "The player you targeted is already on that team!"
                            + ChatColor.RESET);
                } else {
                    // Remove the player from their old team (Both UHC and scoreboard)
                    findTeamByPlayer(playerName).removePlayer(playerName);
                    scTeam.removeEntry(playerName);

                    // Add the player to their new teams (Both UHC and scoreboard)
                    findTeamByColor(teamColor).addPlayer(playerName);
                    player.getScoreboard().getTeam(teamColor).addEntry(playerName);

                    // Send a messgae to the moved player
                    player.sendMessage(StringRef.getPlayerMoveMessage(findTeamByPlayer(playerName)));

                    // Overwrite the player map, updating it with the new team
                    playerMap.put(playerName, teamColor);

                    // If the Discord bot is active, switch the roles of the player too
                    if (plugin.getGameManager().getSettings().useDiscord()) {
                        plugin.getBot().handlePlayerSwitch(playerName,
                                findTeamByPlayer(playerName).getTeamName(false));
                    }
                }
            }
        }

    };

    /**
     * @return The list off all teams that started the game
     */
    public ArrayList<UHCTeam> getTeamList() {
        return teamList;
    }

    /**
     * @return A map of all players tied to their team
     */
    public Map<String, String> getPlayerMap() {
        return playerMap;
    }

    /**
     * @return A list of all the dead players
     */
    public ArrayList<Player> getDeadPlayers() {
        return deadPlayers;
    }

    /**
     * Set a new List of teams
     *
     * @param teamList The new team list
     */
    public void setTeamList(ArrayList<UHCTeam> teamList) {
        this.teamList = teamList;
    }

    /**
     * Set a new map of players
     *
     * @param playerMap The new map of player
     */
    public void setPlayerMap(Map<String, String> playerMap) {
        this.playerMap = playerMap;
    }
}