Search in sources :

Example 1 with MissileWarsPlugin

use of com.leomelonseeds.missilewars.MissileWarsPlugin in project MissileWars by Leomelonseeds.

the class Arena method endGame.

/**
 * End a MissileWars game with a winning team
 *
 * @param winningTeam the winning team
 */
public void endGame(MissileWarsTeam winningTeam) {
    // Ignore if game isn't running
    if (!running) {
        return;
    }
    MissileWarsPlugin plugin = MissileWarsPlugin.getPlugin();
    // Cancel all tasks
    for (BukkitTask task : tasks) {
        task.cancel();
    }
    running = false;
    resetting = true;
    waitingForTie = false;
    redTeam.stopDeckItems();
    blueTeam.stopDeckItems();
    // Produce winner/discord messages
    TextChannel discordChannel = DiscordSRV.getPlugin().getMainTextChannel();
    String discordMessage;
    String winner;
    // Notify players and discord users of win
    if (winningTeam == null) {
        // Send titles
        redTeam.sendTitle("tie");
        blueTeam.sendTitle("tie");
        // Set notify messages
        discordMessage = ":pencil: A game was tied in arena " + this.getName();
        winner = "&e&lNONE";
    } else if (winningTeam == blueTeam) {
        // Send titles
        blueTeam.sendTitle("victory");
        redTeam.sendTitle("defeat");
        // Set notify messages
        List<String> blueList = new ArrayList<>();
        for (MissileWarsPlayer player : players) {
            if (blueTeam.containsPlayer(player.getMCPlayerId())) {
                blueList.add(player.getMCPlayer().getName());
            }
        }
        String blueWinners = String.join(", ", blueList);
        discordMessage = ":tada: Team **blue** (" + blueWinners + ") has won a game in arena " + this.getName();
        winner = "&9&lBLUE";
    } else {
        // Send titles
        redTeam.sendTitle("victory");
        blueTeam.sendTitle("defeat");
        // Set notify messages
        List<String> redList = new ArrayList<>();
        for (MissileWarsPlayer player : players) {
            if (redTeam.containsPlayer(player.getMCPlayerId())) {
                redList.add(player.getMCPlayer().getName());
            }
        }
        String redWinners = String.join(", ", redList);
        discordMessage = ":tada: Team **red** (" + redWinners + ") has won a game in arena " + this.getName();
        winner = "&c&lRED";
    }
    discordChannel.sendMessage(discordMessage).queue();
    // Setup player variables
    List<String> winningMessages = ConfigUtils.getConfigTextList("messages.classic-end", null, null, null);
    String earnMessage = ConfigUtils.getConfigText("messages.earn-currency", null, null, null);
    FileConfiguration ranksConfig = ConfigUtils.getConfigFile(MissileWarsPlugin.getPlugin().getDataFolder().toString(), "ranks.yml");
    int spawn_missile = ranksConfig.getInt("experience.spawn_missile");
    int use_utility = ranksConfig.getInt("experience.use_utility");
    int kill = ranksConfig.getInt("experience.kill");
    int portal_broken = ranksConfig.getInt("experience.portal_broken");
    int shield_health = ranksConfig.getInt("experience.shield_health");
    int win = ranksConfig.getInt("experience.win");
    int red_portal_amount = (blueTeam.getFirstPortalStatus() ? portal_broken : 0) + (blueTeam.getSecondPortalStatus() ? portal_broken : 0);
    int blue_portal_amount = (redTeam.getFirstPortalStatus() ? portal_broken : 0) + (redTeam.getSecondPortalStatus() ? portal_broken : 0);
    int red_shield_health_amount = ((int) ((100 - blueTeam.getShieldHealth())) / 10) * shield_health;
    int blue_shield_health_amount = ((int) ((100 - redTeam.getShieldHealth())) / 10) * shield_health;
    // Find players with most deaths and kills
    List<MissileWarsPlayer> mostKills = new ArrayList<>();
    List<MissileWarsPlayer> mostDeaths = new ArrayList<>();
    for (MissileWarsPlayer player : players) {
        if (!getTeam(player.getMCPlayerId()).equals("no team")) {
            if (mostKills.isEmpty() || mostKills.get(0).getKills() < player.getKills()) {
                mostKills.clear();
                mostKills.add(player);
            } else if (mostKills.get(0).getKills() == player.getKills()) {
                mostKills.add(player);
            }
            if (mostDeaths.isEmpty() || mostDeaths.get(0).getDeaths() < player.getDeaths()) {
                mostDeaths.clear();
                mostDeaths.add(player);
            } else if (mostDeaths.get(0).getDeaths() == player.getDeaths()) {
                mostDeaths.add(player);
            }
        }
    }
    // Produce most kills/deaths list
    List<String> mostKillsList = new ArrayList<>();
    for (MissileWarsPlayer player : mostKills) {
        mostKillsList.add(ConfigUtils.getFocusName(player.getMCPlayer()));
    }
    String most_kills = String.join(", ", mostKillsList);
    List<String> mostDeathsList = new ArrayList<>();
    for (MissileWarsPlayer player : mostDeaths) {
        mostDeathsList.add(ConfigUtils.getFocusName(player.getMCPlayer()));
    }
    String most_deaths = String.join(", ", mostDeathsList);
    int most_kills_amount = mostKills.isEmpty() ? 0 : mostKills.get(0).getKills();
    int most_deaths_amount = mostDeaths.isEmpty() ? 0 : mostDeaths.get(0).getDeaths();
    Economy econ = MissileWarsPlugin.getPlugin().getEconomy();
    LocalDateTime endTime = LocalDateTime.now();
    long gameTime = Duration.between(startTime, endTime).toSeconds();
    // Update stats for each player
    for (MissileWarsPlayer player : players) {
        player.getMCPlayer().setGameMode(GameMode.SPECTATOR);
        // Send win message
        for (String s : winningMessages) {
            s = s.replaceAll("%umw_winning_team%", winner);
            s = s.replaceAll("%umw_most_kills_amount%", Integer.toString(most_kills_amount));
            s = s.replaceAll("%umw_most_deaths_amount%", Integer.toString(most_deaths_amount));
            s = s.replaceAll("%umw_most_kills%", most_kills);
            s = s.replaceAll("%umw_most_deaths%", most_deaths);
            player.getMCPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', s));
        }
        // -1 = TIE, 0 = LOST, 1 = WIN
        int won = winningTeam == null ? -1 : 0;
        // Calculate currency gain per-game
        int amountEarned = 0;
        int playerAmount = 0;
        int teamAmount = 0;
        UUID uuid = player.getMCPlayerId();
        if (!getTeam(uuid).equals("no team")) {
            playerAmount = spawn_missile * player.getMissiles() + use_utility * player.getUtility() + kill * player.getKills();
            if (blueTeam.containsPlayer(uuid)) {
                teamAmount = blue_portal_amount + blue_shield_health_amount;
                if (winningTeam == blueTeam) {
                    teamAmount += win;
                    won = 1;
                }
            } else {
                teamAmount = red_portal_amount + red_shield_health_amount;
                if (winningTeam == redTeam) {
                    teamAmount += win;
                    won = 1;
                }
            }
            long playTime = Duration.between(player.getJoinTime(), endTime).toSeconds();
            double percentPlayed = (double) playTime / gameTime;
            amountEarned = playerAmount + (int) (percentPlayed * teamAmount);
            // Update player stats
            SQLManager sql = MissileWarsPlugin.getPlugin().getSQL();
            sql.updateClassicStats(uuid, won, 1, player.getKills(), player.getMissiles(), player.getUtility(), player.getDeaths());
            sql.updateWinstreak(uuid, mapType, won);
            sql.updateExp(uuid, amountEarned);
            String earnMessagePlayer = earnMessage.replaceAll("%umw_amount_earned%", Integer.toString(amountEarned));
            player.getMCPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', earnMessagePlayer));
        }
        econ.depositPlayer(player.getMCPlayer(), amountEarned);
    }
    long waitTime = plugin.getConfig().getInt("victory-wait-time") * 20L;
    // Remove all players after a short time or immediately if none exist
    if (plugin.isEnabled() && players.size() > 0) {
        new BukkitRunnable() {

            @Override
            public void run() {
                removePlayers();
                startTime = null;
            }
        }.runTaskLater(plugin, waitTime);
        new BukkitRunnable() {

            @Override
            public void run() {
                resetWorld();
            }
        }.runTaskLater(plugin, waitTime + 40L);
    } else {
        removePlayers();
        resetWorld();
        startTime = null;
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) BukkitTask(org.bukkit.scheduler.BukkitTask) ArrayList(java.util.ArrayList) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) MissileWarsPlugin(com.leomelonseeds.missilewars.MissileWarsPlugin) SQLManager(com.leomelonseeds.missilewars.utilities.SQLManager) FileConfiguration(org.bukkit.configuration.file.FileConfiguration) TextChannel(github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel) MissileWarsPlayer(com.leomelonseeds.missilewars.teams.MissileWarsPlayer) Economy(net.milkbowl.vault.economy.Economy) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) UUID(java.util.UUID)

Example 2 with MissileWarsPlugin

use of com.leomelonseeds.missilewars.MissileWarsPlugin in project MissileWars by Leomelonseeds.

the class CustomItemListener method useStructureItem.

/**
 * Handle missile and other structure item spawning.
 */
@EventHandler
public void useStructureItem(PlayerInteractEvent event) {
    // Check if player is trying to place a structure item
    MissileWarsPlugin plugin = MissileWarsPlugin.getPlugin();
    Player player = event.getPlayer();
    Arena playerArena = getPlayerArena(player);
    if (playerArena == null) {
        return;
    }
    ItemStack hand = getItemUsed(player);
    Block clicked = event.getClickedBlock();
    String structureName = getStructureFromItem(hand);
    if (structureName == null) {
        return;
    }
    // Switch to throwing logic if using a throwable
    if (structureName.contains("shield_") || structureName.contains("platform_") || structureName.contains("torpedo_") || structureName.contains("obsidian_")) {
        return;
    }
    // Stop if not left-click on block
    if (!event.getAction().toString().contains("RIGHT") || clicked == null) {
        return;
    }
    event.setCancelled(true);
    List<String> cancel = plugin.getConfig().getStringList("cancel-schematic");
    for (String s : cancel) {
        if (clicked.getType() == Material.getMaterial(s)) {
            ConfigUtils.sendConfigMessage("messages.cannot-place-structure", player, null, null);
            return;
        }
    }
    // Place structure
    String mapName = "default-map";
    if (playerArena.getMapName() != null) {
        mapName = playerArena.getMapName();
    }
    if (SchematicManager.spawnNBTStructure(structureName, clicked.getLocation(), isRedTeam(player), mapName)) {
        hand.setAmount(hand.getAmount() - 1);
        playerArena.getPlayerInArena(player.getUniqueId()).incrementMissiles();
    } else {
        ConfigUtils.sendConfigMessage("messages.cannot-place-structure", player, null, null);
    }
}
Also used : Player(org.bukkit.entity.Player) MissileWarsPlayer(com.leomelonseeds.missilewars.teams.MissileWarsPlayer) Block(org.bukkit.block.Block) ItemStack(org.bukkit.inventory.ItemStack) MissileWarsPlugin(com.leomelonseeds.missilewars.MissileWarsPlugin) Arena(com.leomelonseeds.missilewars.arenas.Arena) EventHandler(org.bukkit.event.EventHandler)

Example 3 with MissileWarsPlugin

use of com.leomelonseeds.missilewars.MissileWarsPlugin in project MissileWars by Leomelonseeds.

the class Arena method start.

/**
 * Starts a game in the arena with the classic arena. Different gamemodes and maps coming soon.
 *
 * @return true if the game started. Otherwise false
 */
public boolean start() {
    if (running) {
        return false;
    }
    MissileWarsPlugin plugin = MissileWarsPlugin.getPlugin();
    // Select Map
    mapName = "default-map";
    List<String> mapsWithTopVotes = new LinkedList<>();
    for (String map : mapVotes.keySet()) {
        if (mapsWithTopVotes.isEmpty()) {
            mapsWithTopVotes.add(map);
        } else {
            String previousTop = mapsWithTopVotes.get(0);
            if (mapVotes.get(previousTop) == mapVotes.get(map)) {
                mapsWithTopVotes.add(map);
            } else if (mapVotes.get(previousTop) < mapVotes.get(map)) {
                mapsWithTopVotes.clear();
                mapsWithTopVotes.add(map);
            }
        }
    }
    if (!mapsWithTopVotes.isEmpty()) {
        // Set map to random map with top votes
        mapName = mapsWithTopVotes.get(new Random().nextInt(mapsWithTopVotes.size()));
    }
    // Generate map.
    if (!generateMap(mapName)) {
        announceMessage("messages.map-failed", null);
        return false;
    } else {
        announceMessage("messages.starting", null);
    }
    // Acquire red and blue spawns
    FileConfiguration mapConfig = ConfigUtils.getConfigFile(plugin.getDataFolder().toString(), "maps.yml");
    Vector blueSpawnVec = SchematicManager.getVector(mapConfig, "blue-spawn", mapType, mapName);
    Location blueSpawn = new Location(getWorld(), blueSpawnVec.getX(), blueSpawnVec.getY(), blueSpawnVec.getZ());
    Vector redSpawnVec = SchematicManager.getVector(mapConfig, "red-spawn", mapType, mapName);
    Location redSpawn = new Location(getWorld(), redSpawnVec.getX(), redSpawnVec.getY(), redSpawnVec.getZ());
    redSpawn.setYaw(180);
    blueSpawn.setWorld(getWorld());
    redSpawn.setWorld(getWorld());
    // Setup scoreboard and teams
    blueTeam = new MissileWarsTeam(ChatColor.BLUE + "" + ChatColor.BOLD + "Blue", this, blueSpawn);
    redTeam = new MissileWarsTeam(ChatColor.RED + "" + ChatColor.BOLD + "Red", this, redSpawn);
    // Assign players to teams based on queue (which removes their items)
    Set<MissileWarsPlayer> toAssign = new HashSet<>(players);
    double maxSize = getCapacity() / 2;
    double maxQueue = Math.ceil((double) players.size() / 2);
    // Teleport all players to center to remove lobby minigame items/dismount
    tasks.add(new BukkitRunnable() {

        @Override
        public void run() {
            for (MissileWarsPlayer player : players) {
                player.getMCPlayer().teleport(getPlayerSpawn(player.getMCPlayer()));
            }
        }
    }.runTaskLater(plugin, 15));
    // Teleport teams slightly later to wait for map generation
    tasks.add(new BukkitRunnable() {

        @Override
        public void run() {
            // Assign queued players
            while (!blueQueue.isEmpty() || !redQueue.isEmpty()) {
                if (!redQueue.isEmpty()) {
                    MissileWarsPlayer toAdd = redQueue.remove();
                    if (redTeam.getSize() < maxQueue) {
                        redTeam.addPlayer(toAdd);
                        toAssign.remove(toAdd);
                    }
                }
                if (!blueQueue.isEmpty()) {
                    MissileWarsPlayer toAdd = blueQueue.remove();
                    if (blueTeam.getSize() < maxQueue) {
                        blueTeam.addPlayer(toAdd);
                        toAssign.remove(toAdd);
                    }
                }
            }
            // Assign remaining players
            for (MissileWarsPlayer player : toAssign) {
                // Ignore if player is a spectator
                if (spectators.contains(player)) {
                    continue;
                }
                if (blueTeam.getSize() <= redTeam.getSize()) {
                    if (blueTeam.getSize() >= maxSize) {
                        ConfigUtils.sendConfigMessage("messages.queue-join-full", player.getMCPlayer(), null, null);
                    } else {
                        blueTeam.addPlayer(player);
                    }
                } else {
                    if (redTeam.getSize() >= maxSize) {
                        ConfigUtils.sendConfigMessage("messages.queue-join-full", player.getMCPlayer(), null, null);
                    } else {
                        redTeam.addPlayer(player);
                    }
                }
            }
            // Start deck distribution for each team and send messages
            redTeam.scheduleDeckItems();
            redTeam.distributeGear();
            redTeam.sendTitle("classic-start");
            redTeam.sendSound("game-start");
            blueTeam.scheduleDeckItems();
            blueTeam.distributeGear();
            blueTeam.sendTitle("classic-start");
            blueTeam.sendSound("game-start");
        }
    }.runTaskLater(plugin, 20));
    // Setup game timers
    // Game start
    startTime = LocalDateTime.now();
    long gameLength = getSecondsRemaining();
    tasks.add(new BukkitRunnable() {

        @Override
        public void run() {
            if (!(blueTeam.getFirstPortalStatus() || blueTeam.getSecondPortalStatus()) && (redTeam.getFirstPortalStatus() || redTeam.getSecondPortalStatus())) {
                endGame(blueTeam);
            } else if ((blueTeam.getFirstPortalStatus() || blueTeam.getSecondPortalStatus()) && !(redTeam.getFirstPortalStatus() || redTeam.getSecondPortalStatus())) {
                endGame(redTeam);
            } else {
                endGame(null);
            }
        }
    }.runTaskLater(plugin, gameLength * 20));
    // Chaos time start
    int chaosStart = getChaosTime();
    tasks.add(new BukkitRunnable() {

        @Override
        public void run() {
            blueTeam.setChaosMode(true);
            redTeam.setChaosMode(true);
            redTeam.broadcastConfigMsg("messages.chaos-mode", null);
            blueTeam.broadcastConfigMsg("messages.chaos-mode", null);
        }
    }.runTaskLater(plugin, (gameLength - chaosStart) * 20));
    // Game is 1800 seconds long.
    int[] reminderTimes = { 600, 1500, 1740, 1770, 1790, 1795, 1796, 1797, 1798, 1799 };
    for (int i : reminderTimes) {
        tasks.add(new BukkitRunnable() {

            @Override
            public void run() {
                announceMessage("messages.game-end-reminder", null);
            }
        }.runTaskLater(plugin, i * 20));
    }
    // Despawn leaves after a while
    leaves = new HashMap<>();
    tasks.add(new BukkitRunnable() {

        @Override
        public void run() {
            Map<Location, Integer> temp = new HashMap<>(leaves);
            for (Entry<Location, Integer> e : temp.entrySet()) {
                int i = e.getValue();
                Location loc = e.getKey();
                if (i <= 0) {
                    if (loc.getBlock().getType().toString().contains("LEAVES")) {
                        loc.getBlock().setType(Material.AIR);
                    }
                    leaves.remove(loc);
                } else {
                    leaves.put(loc, i - 5);
                }
            }
        }
    }.runTaskTimer(plugin, 100, 100));
    running = true;
    return true;
}
Also used : HashMap(java.util.HashMap) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) MissileWarsPlugin(com.leomelonseeds.missilewars.MissileWarsPlugin) LinkedList(java.util.LinkedList) FileConfiguration(org.bukkit.configuration.file.FileConfiguration) MissileWarsPlayer(com.leomelonseeds.missilewars.teams.MissileWarsPlayer) Random(java.util.Random) Vector(org.bukkit.util.Vector) MissileWarsTeam(com.leomelonseeds.missilewars.teams.MissileWarsTeam) Location(org.bukkit.Location) HashSet(java.util.HashSet)

Example 4 with MissileWarsPlugin

use of com.leomelonseeds.missilewars.MissileWarsPlugin in project MissileWars by Leomelonseeds.

the class Arena method scheduleStart.

/**
 * Schedule the start of the game based on the config time.
 */
public void scheduleStart() {
    MissileWarsPlugin plugin = MissileWarsPlugin.getPlugin();
    int secCountdown = plugin.getConfig().getInt("lobby-wait-time");
    // Schedule the start of the game if not already running
    if (startTime == null) {
        // Respawns citizens if they are not present
        if (getWorld().getEntityCount() < 9) {
            try {
                ((Citizens) CitizensAPI.getPlugin()).reload();
            } catch (NPCLoadException e) {
                Bukkit.getLogger().log(Level.WARNING, "Citizens in " + getWorld().getName() + " couldn't be reloaded.");
            }
        }
        startTime = LocalDateTime.now().plusSeconds(secCountdown);
        String startMsg = "messages.lobby-countdown-start";
        announceMessage(startMsg, null);
        tasks.add(new BukkitRunnable() {

            @Override
            public void run() {
                start();
            }
        }.runTaskLater(plugin, secCountdown * 20));
        // Schedule 30-second countdown
        int cdNear = plugin.getConfig().getInt("lobby-countdown-near");
        for (int secInCd = secCountdown; secInCd > 0; secInCd--) {
            int finalSecInCd = secInCd;
            tasks.add(new BukkitRunnable() {

                @Override
                public void run() {
                    if (finalSecInCd <= cdNear) {
                        String startMsg = "messages.lobby-countdown-near";
                        announceMessage(startMsg, null);
                    }
                    setXpLevel(finalSecInCd);
                }
            }.runTaskLater(plugin, (secCountdown - secInCd) * 20));
        }
    }
}
Also used : Citizens(net.citizensnpcs.Citizens) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) NPCLoadException(net.citizensnpcs.api.exception.NPCLoadException) MissileWarsPlugin(com.leomelonseeds.missilewars.MissileWarsPlugin)

Example 5 with MissileWarsPlugin

use of com.leomelonseeds.missilewars.MissileWarsPlugin in project MissileWars by Leomelonseeds.

the class MissileWarsCommand method onCommand.

@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    // Send info if no action taken
    if (args.length == 0) {
        sendErrorMsg(sender, "Usage: /umw <CreateArena/DeleteArena/Join/Leave/OpenGameMenu/EnqueueRed/EnqueueBlue/ForceStart>");
        return true;
    }
    // Check for arena creation
    String action = args[0];
    MissileWarsPlugin plugin = MissileWarsPlugin.getPlugin();
    ArenaManager arenaManager = plugin.getArenaManager();
    if (action.equalsIgnoreCase("DeleteArena")) {
        // Ensure player is allowed to create an arena
        if (!sender.hasPermission("umw.delete-arena")) {
            sendErrorMsg(sender, "You do not have permission to do that!");
            return true;
        }
        // Validate given arena name
        if (args.length < 2) {
            sendErrorMsg(sender, "Usage: /umw DeleteArena <arena-name>");
            return true;
        }
        String arenaName = args[1];
        Arena toRemove = arenaManager.getArena(arenaName);
        if (toRemove == null) {
            sendErrorMsg(sender, "That arena does not exist!");
            return true;
        }
        // Delete the arena
        if (arenaManager.removeArena(toRemove)) {
            sendSuccessMsg(sender, "The arena has been deleted!");
            return true;
        } else {
            sendErrorMsg(sender, "Something went wrong deleting the arena. Notify an admin.");
            return true;
        }
    }
    if (action.equalsIgnoreCase("CreateArena")) {
        // Ensure player is allowed to delete an arena
        if (!sender.hasPermission("umw.create-arena")) {
            sendErrorMsg(sender, "You do not have permission to do that!");
            return true;
        }
        // Validate given arena name
        if (args.length < 2) {
            sendErrorMsg(sender, "Usage: /umw CreateArena <arena-name> [capacity]");
            return true;
        }
        String arenaName = args[1];
        if (arenaManager.getArena(arenaName) != null) {
            sendErrorMsg(sender, "An arena with that name already exists!");
            return true;
        }
        int arenaCapacity = MissileWarsPlugin.getPlugin().getConfig().getInt("arena-cap");
        if (args.length > 2) {
            try {
                arenaCapacity = Integer.parseInt(args[2]);
            } catch (NumberFormatException e) {
                sendErrorMsg(sender, "Capacity must be a number!");
                return true;
            }
        }
        // Create new arena
        if (arenaManager.createArena(arenaName, arenaCapacity)) {
            sendSuccessMsg(sender, "New arena created!");
            return true;
        } else {
            sendErrorMsg(sender, "Something went wrong creating the arena. Notify an admin.");
            return true;
        }
    }
    // Update all arenas. Might take a while
    if (action.equalsIgnoreCase("PerformArenaUpgrade")) {
        if (sender instanceof Player) {
            return false;
        }
        MissileWarsPlugin.getPlugin().getArenaManager().performArenaUpgrade();
        return true;
    }
    // Clear inventories the umw way
    if (action.equalsIgnoreCase("clear")) {
        if (args.length == 1) {
            if (sender instanceof Player) {
                Player player = (Player) sender;
                InventoryUtils.clearInventory(player);
                sendSuccessMsg(sender, "Inventory cleared!");
                return true;
            } else {
                sendSuccessMsg(sender, "Must specify a target.");
                return true;
            }
        } else if (args.length == 2) {
            Player target = getCommandTarget(args, sender);
            if (target == null) {
                sendErrorMsg(sender, "No target found!");
                return true;
            }
            InventoryUtils.clearInventory(target);
            return true;
        }
    }
    // Open game selector
    if (action.equalsIgnoreCase("OpenGameMenu")) {
        // Ensure player is allowed to open game menu
        if (!sender.hasPermission("umw.open-arena-menu")) {
            sendErrorMsg(sender, "You do not have permission to do that!");
            return true;
        }
        // Check if opening for another player
        Player target = getCommandTarget(args, sender);
        if (target == null) {
            sendErrorMsg(sender, "No target found!");
            return true;
        }
        arenaManager.openArenaSelector(target);
        sendSuccessMsg(sender, "Game selector opened!");
        return true;
    }
    // Quit to waiting lobby of a game
    if (action.equalsIgnoreCase("Leave") && sender instanceof Player) {
        Player player = (Player) sender;
        Arena arena = arenaManager.getArena(player.getUniqueId());
        if (arena == null) {
            sendErrorMsg(sender, "You must be in a game to do this!");
            return true;
        }
        if (!(arena.leaveGame(player.getUniqueId()))) {
            sendErrorMsg(sender, "You cannot do this now!");
            return true;
        }
        return true;
    }
    // Join the fullest available game
    if (action.equalsIgnoreCase("Join") && sender instanceof Player) {
        Player player = (Player) sender;
        // Require player to be in the lobby
        if (!player.getWorld().getName().equals("world")) {
            sendErrorMsg(sender, "You must be in the lobby to use this!");
            return true;
        }
        // Allow player to join the fullest arena, or specify an arena name
        if (args.length == 1) {
            for (Arena arena : arenaManager.getLoadedArenas()) {
                if (arena.getNumPlayers() < arena.getCapacity()) {
                    if (arena.joinPlayer(player)) {
                        return true;
                    }
                }
            }
        } else if (args.length >= 2) {
            for (Arena arena : arenaManager.getLoadedArenas()) {
                if (arena.getName().equalsIgnoreCase(args[1])) {
                    if (arena.joinPlayer(player)) {
                        return true;
                    } else {
                        ConfigUtils.sendConfigMessage("messages.arena-full", player, arena, null);
                        return true;
                    }
                }
            }
            sendErrorMsg(sender, "Please specify a valid arena name!");
            return true;
        }
        sendErrorMsg(sender, "All arenas are full! Please open the menu and choose one to spectate.");
        return true;
    }
    // Queue for red team
    if (action.equalsIgnoreCase("EnqueueRed")) {
        // Ensure player is allowed to open team menu
        if (!sender.hasPermission("umw.enqueue")) {
            sendErrorMsg(sender, "You do not have permission to do that!");
            return true;
        }
        // Check if opening for another player
        Player target = getCommandTarget(args, sender);
        if (target == null) {
            sendErrorMsg(sender, "No target found!");
            return true;
        }
        // Check if player is in arena
        Arena arena = arenaManager.getArena(target.getUniqueId());
        if (arena == null) {
            sendErrorMsg(sender, "Target is not in an arena");
            return true;
        }
        // Enqueue for red team
        arena.enqueueRed(target.getUniqueId());
        sendSuccessMsg(sender, "Enqueued player for red team!");
        return true;
    }
    // Queue for blue team
    if (action.equalsIgnoreCase("EnqueueBlue")) {
        // Ensure player is allowed to open team menu
        if (!sender.hasPermission("umw.enqueue")) {
            sendErrorMsg(sender, "You do not have permission to do that!");
            return true;
        }
        // Check if opening for another player
        Player target = getCommandTarget(args, sender);
        if (target == null) {
            sendErrorMsg(sender, "No target found!");
            return true;
        }
        // Check if player is in arena
        Arena arena = arenaManager.getArena(target.getUniqueId());
        if (arena == null) {
            sendErrorMsg(sender, "Target is not in an arena");
            return true;
        }
        // Enqueue for red team
        arena.enqueueBlue(target.getUniqueId());
        sendSuccessMsg(sender, "Enqueued player for blue team!");
        return true;
    }
    // Force start an arena
    if (action.equalsIgnoreCase("ForceStart")) {
        // Ensure sender has permission
        if (!sender.hasPermission("umw.force-start")) {
            sendErrorMsg(sender, "You do not have permission to do that!");
            return true;
        }
        // Check for arena and start it
        if (args.length < 2) {
            sendErrorMsg(sender, "You must specify an arena name!");
            return true;
        }
        Arena target = arenaManager.getArena(args[1]);
        if (target == null) {
            sendErrorMsg(sender, "Arena not found!");
            return true;
        }
        if (target.start()) {
            sendSuccessMsg(sender, "Arena started!");
        } else {
            sendErrorMsg(sender, "Arena is already running!");
        }
        return true;
    }
    if (action.equalsIgnoreCase("Deck")) {
        Player player = (Player) sender;
        Arena arena = arenaManager.getArena(player.getUniqueId());
        if (!(arena == null || arena.getTeam(player.getUniqueId()).equals("no team"))) {
            sendErrorMsg(sender, "You cannot change decks while playing.");
            return true;
        }
        if (args.length != 2) {
            sendErrorMsg(sender, "Usage: /mw deck Vanguard/Berserker/Sentinel/Architect");
            return true;
        }
        String deck = StringUtils.capitalize(args[1].toLowerCase());
        if (plugin.getDeckManager().getDeck(deck) == null) {
            sendErrorMsg(sender, "Please specify a valid deck!");
            return true;
        }
        // Update deck in cache
        JSONObject currentDeck = plugin.getJSON().getPlayer(player.getUniqueId());
        currentDeck.put("Deck", deck);
        plugin.getJSON().setPlayer(player.getUniqueId(), currentDeck);
        sendSuccessMsg(sender, "Set your deck to " + deck + "!");
        return true;
    }
    return true;
}
Also used : ArenaManager(com.leomelonseeds.missilewars.arenas.ArenaManager) Player(org.bukkit.entity.Player) JSONObject(org.json.JSONObject) MissileWarsPlugin(com.leomelonseeds.missilewars.MissileWarsPlugin) Arena(com.leomelonseeds.missilewars.arenas.Arena)

Aggregations

MissileWarsPlugin (com.leomelonseeds.missilewars.MissileWarsPlugin)7 FileConfiguration (org.bukkit.configuration.file.FileConfiguration)4 BukkitRunnable (org.bukkit.scheduler.BukkitRunnable)4 MissileWarsPlayer (com.leomelonseeds.missilewars.teams.MissileWarsPlayer)3 Vector (org.bukkit.util.Vector)3 Arena (com.leomelonseeds.missilewars.arenas.Arena)2 File (java.io.File)2 IOException (java.io.IOException)2 LinkedList (java.util.LinkedList)2 Random (java.util.Random)2 Location (org.bukkit.Location)2 Block (org.bukkit.block.Block)2 Player (org.bukkit.entity.Player)2 ArenaManager (com.leomelonseeds.missilewars.arenas.ArenaManager)1 MissileWarsTeam (com.leomelonseeds.missilewars.teams.MissileWarsTeam)1 SQLManager (com.leomelonseeds.missilewars.utilities.SQLManager)1 Clipboard (com.sk89q.worldedit.extent.clipboard.Clipboard)1 ClipboardFormat (com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat)1 ClipboardReader (com.sk89q.worldedit.extent.clipboard.io.ClipboardReader)1 TextChannel (github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel)1