Search in sources :

Example 1 with EconomyResponse

use of net.milkbowl.vault.economy.EconomyResponse in project acidisland by tastybento.

the class ControlPanel method onInventoryClick.

@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
    if (DEBUG)
        plugin.getLogger().info("DEBUG:" + event.getEventName());
    // The player that
    Player player = (Player) event.getWhoClicked();
    // clicked the item
    // The item that was clicked
    ItemStack clicked = event.getCurrentItem();
    // The inventory that was clicked in
    Inventory inventory = event.getInventory();
    if (inventory.getName() == null) {
        if (DEBUG)
            plugin.getLogger().info("DEBUG: inventory name is null");
        return;
    }
    // ASkyBlock plugin = ASkyBlock.getPlugin();
    int slot = event.getRawSlot();
    // Challenges
    if (inventory.getName().equals(plugin.myLocale(player.getUniqueId()).challengesguiTitle)) {
        event.setCancelled(true);
        if (event.getClick().equals(ClickType.SHIFT_RIGHT)) {
            if (DEBUG)
                plugin.getLogger().info("DEBUG: click type shift Right");
            inventory.clear();
            player.closeInventory();
            player.updateInventory();
            return;
        }
        if (event.getSlotType() == SlotType.OUTSIDE) {
            if (DEBUG)
                plugin.getLogger().info("DEBUG: slot type outside");
            inventory.clear();
            player.closeInventory();
            return;
        }
        // Get the list of items in this inventory
        // plugin.getLogger().info("DEBUG: You clicked on slot " + slot);
        List<CPItem> challenges = plugin.getChallenges().getCP(player);
        if (challenges == null) {
            plugin.getLogger().warning("Player was accessing Challenge Inventory, but it had lost state - was server restarted?");
            inventory.clear();
            player.closeInventory();
            Util.runCommand(player, Settings.CHALLENGECOMMAND);
            return;
        }
        // challenges.size());
        if (slot >= 0 && slot < challenges.size()) {
            if (DEBUG)
                plugin.getLogger().info("DEBUG: slot within challenges");
            CPItem item = challenges.get(slot);
            // END TEST
            if (DEBUG) {
                plugin.getLogger().info("DEBUG: CP Item is " + item.getItem().toString());
                plugin.getLogger().info("DEBUG: Clicked is " + clicked.toString());
            }
            // These two should be identical because it is made before
            if (clicked.equals(item.getItem())) {
                if (DEBUG)
                    plugin.getLogger().info("DEBUG: You clicked on a challenge item");
                // Next section indicates the level of panel to open
                if (item.getNextSection() != null) {
                    inventory.clear();
                    player.closeInventory();
                    player.openInventory(plugin.getChallenges().challengePanel(player, item.getNextSection()));
                } else if (item.getCommand() != null) {
                    Util.runCommand(player, item.getCommand());
                    inventory.clear();
                    player.closeInventory();
                    player.openInventory(plugin.getChallenges().challengePanel(player));
                }
            }
        }
        return;
    }
    /*
         * Minishop section
         */
    if (miniShop != null && inventory.getName().equals(miniShop.getName())) {
        // The
        // inventory
        // is
        // our
        // custom
        // Inventory
        String message = "";
        // plugin.getLogger().info("You clicked on slot " + slot);
        // Don't let them pick it up
        event.setCancelled(true);
        if (!Settings.useEconomy || slot == -999) {
            player.closeInventory();
            return;
        }
        if (event.getClick().equals(ClickType.SHIFT_RIGHT)) {
            player.closeInventory();
            player.updateInventory();
            return;
        }
        if (store.containsKey(slot)) {
            // We have a winner!
            MiniShopItem item = store.get(slot);
            if (clicked.equals(item.getItem())) {
                // Check what type of click - LEFT = BUY, RIGHT = sell
                if (event.getClick().equals(ClickType.LEFT)) {
                    // Check if item is for sale
                    if (item.getPrice() > 0D) {
                        // Check they can afford it
                        if (!VaultHelper.econ.has(player, Settings.worldName, item.getPrice())) {
                            // message = "You cannot afford that item!";
                            message = (plugin.myLocale().minishopYouCannotAfford).replace("[description]", item.getDescription());
                        } else {
                            EconomyResponse r = VaultHelper.econ.withdrawPlayer(player, Settings.worldName, item.getPrice());
                            if (r.transactionSuccess()) {
                                // message = "You bought " +
                                // item.getQuantity() + " " +
                                // item.getDescription() + " for " +
                                // VaultHelper.econ.format(item.getPrice());
                                message = plugin.myLocale().minishopYouBought.replace("[number]", Integer.toString(item.getQuantity()));
                                message = message.replace("[description]", item.getDescription());
                                message = message.replace("[price]", VaultHelper.econ.format(item.getPrice()));
                                Map<Integer, ItemStack> items = player.getInventory().addItem(item.getItemClean());
                                if (!items.isEmpty()) {
                                    for (ItemStack i : items.values()) {
                                        player.getWorld().dropItem(player.getLocation(), i);
                                    }
                                }
                                // Fire event
                                MiniShopEvent shopEvent = new MiniShopEvent(player.getUniqueId(), item, TransactionType.BUY);
                                plugin.getServer().getPluginManager().callEvent(shopEvent);
                            } else {
                                // message =
                                // "There was a problem puchasing that item: "
                                // + r.errorMessage;
                                message = (plugin.myLocale().minishopBuyProblem).replace("[description]", item.getDescription());
                            }
                        }
                    }
                } else if (event.getClick().equals(ClickType.RIGHT) && allowSelling && item.getSellPrice() > 0D) {
                    // Check if they have the item
                    if (player.getInventory().containsAtLeast(item.getItemClean(), item.getQuantity())) {
                        player.getInventory().removeItem(item.getItemClean());
                        VaultHelper.econ.depositPlayer(player, Settings.worldName, item.getSellPrice());
                        // message = "You sold " + item.getQuantity() + " "
                        // + item.getDescription() + " for " +
                        // VaultHelper.econ.format(item.getSellPrice());
                        message = plugin.myLocale().minishopYouSold.replace("[number]", Integer.toString(item.getQuantity()));
                        message = message.replace("[description]", item.getDescription());
                        message = message.replace("[price]", VaultHelper.econ.format(item.getSellPrice()));
                        // Fire event
                        MiniShopEvent shopEvent = new MiniShopEvent(player.getUniqueId(), item, TransactionType.SELL);
                        plugin.getServer().getPluginManager().callEvent(shopEvent);
                    } else {
                        // message =
                        // "You do not have enough of that item to sell it.";
                        message = (plugin.myLocale().minishopSellProblem).replace("[description]", item.getDescription());
                        ;
                    }
                }
                // player.closeInventory(); // Closes the inventory
                if (!message.isEmpty()) {
                    Util.sendMessage(player, message);
                }
            }
        }
        return;
    }
    // Check control panels
    for (String panelName : controlPanel.keySet()) {
        if (inventory.getName().equals(panelName)) {
            event.setCancelled(true);
            // plugin.getLogger().info("DEBUG: panel name " + panelName);
            if (slot == -999) {
                player.closeInventory();
                return;
            }
            if (event.getClick().equals(ClickType.SHIFT_RIGHT)) {
                player.closeInventory();
                player.updateInventory();
                return;
            }
            HashMap<Integer, CPItem> thisPanel = panels.get(panelName);
            if (slot >= 0 && slot < thisPanel.size()) {
                // plugin.getLogger().info("DEBUG: slot is " + slot);
                // Do something
                String command = thisPanel.get(slot).getCommand();
                String nextSection = ChatColor.translateAlternateColorCodes('&', thisPanel.get(slot).getNextSection());
                if (!command.isEmpty()) {
                    // Closes the inventory
                    player.closeInventory();
                    event.setCancelled(true);
                    // plugin.getLogger().info("DEBUG: performing command "
                    // + command);
                    Util.runCommand(player, command);
                    return;
                }
                if (!nextSection.isEmpty()) {
                    // Closes the inventory
                    player.closeInventory();
                    Inventory next = controlPanel.get(nextSection);
                    if (next == null) {
                    // plugin.getLogger().info("DEBUG: next panel is null");
                    }
                    // plugin.getLogger().info("DEBUG: opening next cp "+nextSection);
                    player.openInventory(next);
                    event.setCancelled(true);
                    return;
                }
                // Closes the inventory
                player.closeInventory();
                event.setCancelled(true);
                return;
            }
        }
    }
}
Also used : Player(org.bukkit.entity.Player) MiniShopEvent(com.wasteofplastic.acidisland.events.MiniShopEvent) EconomyResponse(net.milkbowl.vault.economy.EconomyResponse) ItemStack(org.bukkit.inventory.ItemStack) Inventory(org.bukkit.inventory.Inventory) EventHandler(org.bukkit.event.EventHandler)

Example 2 with EconomyResponse

use of net.milkbowl.vault.economy.EconomyResponse in project acidisland by tastybento.

the class Schematic method resetMoney.

private void resetMoney(Player player) {
    if (!Settings.useEconomy) {
        return;
    }
    // Set player's balance in acid island to the starting balance
    try {
        // Settings.general_worldName);
        if (VaultHelper.econ == null) {
            // plugin.getLogger().warning("DEBUG: econ is null!");
            VaultHelper.setupEconomy();
        }
        Double playerBalance = VaultHelper.econ.getBalance(player, Settings.worldName);
        // plugin.getLogger().info("DEBUG: playerbalance = " +
        // playerBalance);
        // Round the balance to 2 decimal places and slightly down to
        // avoid issues when withdrawing the amount later
        BigDecimal bd = new BigDecimal(playerBalance);
        bd = bd.setScale(2, RoundingMode.HALF_DOWN);
        playerBalance = bd.doubleValue();
        // + playerBalance);
        if (playerBalance != Settings.startingMoney) {
            if (playerBalance > Settings.startingMoney) {
                Double difference = playerBalance - Settings.startingMoney;
                EconomyResponse response = VaultHelper.econ.withdrawPlayer(player, Settings.worldName, difference);
                // plugin.getLogger().info("DEBUG: withdrawn");
                if (response.transactionSuccess()) {
                    plugin.getLogger().info("FYI:" + player.getName() + " had " + VaultHelper.econ.format(playerBalance) + " when they typed /island and it was set to " + Settings.startingMoney);
                } else {
                    plugin.getLogger().warning("Problem trying to withdraw " + playerBalance + " from " + player.getName() + "'s account when they typed /island!");
                    plugin.getLogger().warning("Error from economy was: " + response.errorMessage);
                }
            } else {
                Double difference = Settings.startingMoney - playerBalance;
                EconomyResponse response = VaultHelper.econ.depositPlayer(player, Settings.worldName, difference);
                if (response.transactionSuccess()) {
                    plugin.getLogger().info("FYI:" + player.getName() + " had " + VaultHelper.econ.format(playerBalance) + " when they typed /island and it was set to " + Settings.startingMoney);
                } else {
                    plugin.getLogger().warning("Problem trying to deposit " + playerBalance + " from " + player.getName() + "'s account when they typed /island!");
                    plugin.getLogger().warning("Error from economy was: " + response.errorMessage);
                }
            }
        }
    } catch (final Exception e) {
        plugin.getLogger().severe("Error trying to zero " + player.getName() + "'s account when they typed /island!");
        plugin.getLogger().severe(e.getMessage());
    }
}
Also used : EconomyResponse(net.milkbowl.vault.economy.EconomyResponse) BigDecimal(java.math.BigDecimal) IOException(java.io.IOException)

Example 3 with EconomyResponse

use of net.milkbowl.vault.economy.EconomyResponse in project acidisland by tastybento.

the class Challenges method giveReward.

/**
 * Gives the reward for completing the challenge
 *
 * @param player
 * @param challenge
 * @return ture if reward given successfully
 */
private boolean giveReward(final Player player, final String challenge) {
    // Grab the rewards from the config.yml file
    String[] permList;
    String[] itemRewards;
    double moneyReward = 0;
    int expReward = 0;
    String rewardText = "";
    // If the friendly name is available use it
    String challengeName = ChatColor.translateAlternateColorCodes('&', getChallengeConfig().getString("challenges.challengeList." + challenge + ".friendlyname", challenge.substring(0, 1).toUpperCase() + challenge.substring(1)));
    // If player has done a challenge already, the rewards are different
    if (!plugin.getPlayers().checkChallenge(player.getUniqueId(), challenge)) {
        // First time
        Util.sendMessage(player, ChatColor.GREEN + plugin.myLocale(player.getUniqueId()).challengesyouHaveCompleted.replace("[challenge]", challengeName));
        if (Settings.broadcastMessages) {
            for (Player p : plugin.getServer().getOnlinePlayers()) {
                Util.sendMessage(p, ChatColor.GOLD + plugin.myLocale(p.getUniqueId()).challengesnameHasCompleted.replace("[name]", player.getName()).replace("[challenge]", challengeName));
            }
        }
        plugin.getMessages().tellOfflineTeam(player.getUniqueId(), ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengesnameHasCompleted.replace("[name]", player.getName()).replace("[challenge]", challengeName));
        itemRewards = getChallengeConfig().getString("challenges.challengeList." + challenge.toLowerCase() + ".itemReward", "").split(" ");
        moneyReward = getChallengeConfig().getDouble("challenges.challengeList." + challenge.toLowerCase() + ".moneyReward", 0D);
        rewardText = ChatColor.translateAlternateColorCodes('&', getChallengeConfig().getString("challenges.challengeList." + challenge.toLowerCase() + ".rewardText", "Goodies!"));
        expReward = getChallengeConfig().getInt("challenges.challengeList." + challenge + ".expReward", 0);
    } else {
        // Repeat challenge
        Util.sendMessage(player, ChatColor.GREEN + plugin.myLocale(player.getUniqueId()).challengesyouRepeated.replace("[challenge]", challengeName));
        itemRewards = getChallengeConfig().getString("challenges.challengeList." + challenge.toLowerCase() + ".repeatItemReward", "").split(" ");
        moneyReward = getChallengeConfig().getDouble("challenges.challengeList." + challenge.toLowerCase() + ".repeatMoneyReward", 0);
        rewardText = ChatColor.translateAlternateColorCodes('&', getChallengeConfig().getString("challenges.challengeList." + challenge.toLowerCase() + ".repeatRewardText", "Goodies!"));
        expReward = getChallengeConfig().getInt("challenges.challengeList." + challenge + ".repeatExpReward", 0);
    }
    // Report the rewards and give out exp, money and permissions if
    // appropriate
    Util.sendMessage(player, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengesrewards + ": " + ChatColor.WHITE + rewardText);
    if (expReward > 0) {
        Util.sendMessage(player, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengesexpReward + ": " + ChatColor.WHITE + expReward);
        player.giveExp(expReward);
    }
    if (Settings.useEconomy && moneyReward > 0 && (VaultHelper.econ != null)) {
        EconomyResponse e = VaultHelper.econ.depositPlayer(player, Settings.worldName, moneyReward);
        if (e.transactionSuccess()) {
            Util.sendMessage(player, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengesmoneyReward + ": " + ChatColor.WHITE + VaultHelper.econ.format(moneyReward));
        } else {
            plugin.getLogger().severe("Error giving player " + player.getUniqueId() + " challenge money:" + e.errorMessage);
            plugin.getLogger().severe("Reward was $" + moneyReward);
        }
    }
    // Dole out permissions
    // plugin.getLogger().info("DEBUG: dole out permissions");
    permList = getChallengeConfig().getString("challenges.challengeList." + challenge.toLowerCase() + ".permissionReward", "").split(" ");
    for (final String s : permList) {
        if (!s.isEmpty()) {
            VaultHelper.addPerm(player, s);
            plugin.getLogger().info("Added permission " + s + " to " + player.getName() + "");
        }
    }
    // Give items
    List<ItemStack> rewardedItems = giveItems(player, itemRewards);
    if (rewardedItems == null) {
        return false;
    }
    // Run reward commands
    if (!plugin.getPlayers().checkChallenge(player.getUniqueId(), challenge)) {
        // First time
        List<String> commands = getChallengeConfig().getStringList("challenges.challengeList." + challenge.toLowerCase() + ".rewardcommands");
        runCommands(player, commands);
    } else {
        // Repeat challenge
        List<String> commands = getChallengeConfig().getStringList("challenges.challengeList." + challenge.toLowerCase() + ".repeatrewardcommands");
        runCommands(player, commands);
    }
    // Mark the challenge as complete
    // if (!plugin.getPlayers().checkChallenge(player.getUniqueId(),challenge)) {
    plugin.getPlayers().completeChallenge(player.getUniqueId(), challenge);
    // }
    // Call the Challenge Complete Event
    final ChallengeCompleteEvent event = new ChallengeCompleteEvent(player, challenge, permList, itemRewards, moneyReward, expReward, rewardText, rewardedItems);
    plugin.getServer().getPluginManager().callEvent(event);
    return true;
}
Also used : Player(org.bukkit.entity.Player) EconomyResponse(net.milkbowl.vault.economy.EconomyResponse) ChallengeCompleteEvent(com.wasteofplastic.acidisland.events.ChallengeCompleteEvent) ItemStack(org.bukkit.inventory.ItemStack)

Example 4 with EconomyResponse

use of net.milkbowl.vault.economy.EconomyResponse in project acidisland by tastybento.

the class Challenges method onCommand.

/*
     * (non-Javadoc)
     * @see
     * org.bukkit.command.CommandExecutor#onCommand(org.bukkit.command.CommandSender
     * , org.bukkit.command.Command, java.lang.String, java.lang.String[])
     */
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] cmd) {
    if (!(sender instanceof Player)) {
        return false;
    }
    final Player player = (Player) sender;
    if (player.getUniqueId() == null) {
        return false;
    }
    // Check permissions
    if (!VaultHelper.checkPerm(player, Settings.PERMPREFIX + "island.challenges")) {
        Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorNoPermission);
        return true;
    }
    // Check island
    if (plugin.getGrid().getIsland(player.getUniqueId()) == null) {
        Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorNoIsland);
        return true;
    }
    switch(cmd.length) {
        case 0:
            // Display panel
            player.openInventory(challengePanel(player));
            return true;
        case 1:
            if (cmd[0].equalsIgnoreCase("help") || cmd[0].equalsIgnoreCase("complete") || cmd[0].equalsIgnoreCase("c")) {
                Util.sendMessage(sender, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengeshelp1);
                Util.sendMessage(sender, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengeshelp2);
            } else if (isLevelAvailable(player, getChallengeConfig().getString("challenges.challengeList." + cmd[0].toLowerCase().replaceAll("\\.", "") + ".level"))) {
                // Provide info on the challenge
                // Challenge Name
                // Description
                // Type
                // Items taken or not
                // island or not
                final String challenge = cmd[0].toLowerCase().toLowerCase().replaceAll("\\.", "");
                Util.sendMessage(sender, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengesname + ": " + ChatColor.WHITE + challenge);
                Util.sendMessage(sender, ChatColor.WHITE + plugin.myLocale(player.getUniqueId()).challengeslevel + ": " + ChatColor.GOLD + getChallengeConfig().getString("challenges.challengeList." + challenge + ".level", ""));
                String desc = ChatColor.translateAlternateColorCodes('&', getChallengeConfig().getString("challenges.challengeList." + challenge + ".description", "").replace("[label]", Settings.ISLANDCOMMAND));
                List<String> result = new ArrayList<String>();
                if (desc.contains("|")) {
                    result.addAll(Arrays.asList(desc.split("\\|")));
                } else {
                    result.add(desc);
                }
                for (String line : result) {
                    Util.sendMessage(sender, ChatColor.GOLD + line);
                }
                final String type = getChallengeConfig().getString("challenges.challengeList." + challenge + ".type", "").toLowerCase();
                if (type.equals("inventory")) {
                    if (getChallengeConfig().getBoolean("challenges.challengeList." + cmd[0].toLowerCase() + ".takeItems")) {
                        Util.sendMessage(sender, ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengesitemTakeWarning);
                    }
                } else if (type.equals("island")) {
                    Util.sendMessage(sender, ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorItemsNotThere);
                }
                if (plugin.getPlayers().checkChallenge(player.getUniqueId(), challenge) && (!type.equals("inventory") || !getChallengeConfig().getBoolean("challenges.challengeList." + challenge + ".repeatable", false))) {
                    Util.sendMessage(sender, ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengesnotRepeatable);
                    return true;
                }
                double moneyReward = 0;
                int expReward = 0;
                String rewardText = "";
                if (!plugin.getPlayers().checkChallenge(player.getUniqueId(), challenge)) {
                    // First time
                    moneyReward = getChallengeConfig().getDouble("challenges.challengeList." + challenge.toLowerCase() + ".moneyReward", 0D);
                    rewardText = ChatColor.translateAlternateColorCodes('&', getChallengeConfig().getString("challenges.challengeList." + challenge.toLowerCase() + ".rewardText", "Goodies!"));
                    expReward = getChallengeConfig().getInt("challenges.challengeList." + challenge + ".expReward", 0);
                    Util.sendMessage(sender, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengesfirstTimeRewards);
                } else {
                    // Repeat challenge
                    moneyReward = getChallengeConfig().getDouble("challenges.challengeList." + challenge.toLowerCase() + ".repeatMoneyReward", 0D);
                    rewardText = ChatColor.translateAlternateColorCodes('&', getChallengeConfig().getString("challenges.challengeList." + challenge.toLowerCase() + ".repeatRewardText", "Goodies!"));
                    expReward = getChallengeConfig().getInt("challenges.challengeList." + challenge + ".repeatExpReward", 0);
                    Util.sendMessage(sender, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengesrepeatRewards);
                }
                Util.sendMessage(sender, ChatColor.WHITE + rewardText);
                if (expReward > 0) {
                    Util.sendMessage(sender, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengesexpReward + ": " + ChatColor.WHITE + expReward);
                }
                if (Settings.useEconomy && moneyReward > 0) {
                    Util.sendMessage(sender, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengesmoneyReward + ": " + ChatColor.WHITE + VaultHelper.econ.format(moneyReward));
                }
                Util.sendMessage(sender, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengestoCompleteUse + ChatColor.WHITE + " /" + label + " c " + challenge);
            } else {
                Util.sendMessage(sender, ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengesinvalidChallengeName);
            }
            return true;
        case 2:
            if (cmd[0].equalsIgnoreCase("complete") || cmd[0].equalsIgnoreCase("c")) {
                if (!player.getWorld().equals(ASkyBlock.getIslandWorld())) {
                    // Check if in new nether
                    if (!Settings.createNether || !Settings.newNether || ASkyBlock.getNetherWorld() == null || !player.getWorld().equals(ASkyBlock.getNetherWorld())) {
                        Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorWrongWorld);
                        return true;
                    }
                }
                if (checkIfCanCompleteChallenge(player, cmd[1].toLowerCase().toLowerCase().replaceAll("\\.", ""))) {
                    int oldLevel = getLevelDone(player);
                    giveReward(player, cmd[1].toLowerCase().toLowerCase().replaceAll("\\.", ""));
                    // Save player
                    plugin.getPlayers().save(player.getUniqueId());
                    int newLevel = getLevelDone(player);
                    // plugin.getLogger().info("DEBUG: " + oldLevel + " " + newLevel);
                    if (oldLevel < newLevel) {
                        // Update chat
                        plugin.getChatListener().setPlayerChallengeLevel(player);
                        // Run commands and give rewards but only if they haven't done it below
                        // plugin.getLogger().info("DEBUG: old level = " + oldLevel + " new level = " + newLevel);
                        String level = Settings.challengeLevels.get(newLevel);
                        if (!level.isEmpty() && !plugin.getPlayers().checkChallenge(player.getUniqueId(), level)) {
                            // plugin.getLogger().info("DEBUG: level name = " + level);
                            plugin.getPlayers().completeChallenge(player.getUniqueId(), level);
                            String message = ChatColor.translateAlternateColorCodes('&', getChallengeConfig().getString("challenges.levelUnlock." + level + ".message", ""));
                            if (!message.isEmpty()) {
                                Util.sendMessage(player, ChatColor.GREEN + message);
                            }
                            String[] itemReward = getChallengeConfig().getString("challenges.levelUnlock." + level + ".itemReward", "").split(" ");
                            String rewardDesc = getChallengeConfig().getString("challenges.levelUnlock." + level + ".rewardDesc", "");
                            if (!rewardDesc.isEmpty()) {
                                Util.sendMessage(player, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengesrewards + ": " + ChatColor.WHITE + rewardDesc);
                            }
                            List<ItemStack> rewardedItems = giveItems(player, itemReward);
                            double moneyReward = getChallengeConfig().getDouble("challenges.levelUnlock." + level + ".moneyReward", 0D);
                            int expReward = getChallengeConfig().getInt("challenges.levelUnlock." + level + ".expReward", 0);
                            if (expReward > 0) {
                                Util.sendMessage(player, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengesexpReward + ": " + ChatColor.WHITE + expReward);
                                player.giveExp(expReward);
                            }
                            if (Settings.useEconomy && moneyReward > 0 && (VaultHelper.econ != null)) {
                                EconomyResponse e = VaultHelper.econ.depositPlayer(player, Settings.worldName, moneyReward);
                                if (e.transactionSuccess()) {
                                    Util.sendMessage(player, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).challengesmoneyReward + ": " + ChatColor.WHITE + VaultHelper.econ.format(moneyReward));
                                } else {
                                    plugin.getLogger().severe("Error giving player " + player.getUniqueId() + " challenge money:" + e.errorMessage);
                                    plugin.getLogger().severe("Reward was $" + moneyReward);
                                }
                            }
                            String[] permList = getChallengeConfig().getString("challenges.levelUnlock." + level + ".permissionReward", "").split(" ");
                            for (final String s : permList) {
                                if (!s.isEmpty()) {
                                    VaultHelper.addPerm(player, s);
                                    plugin.getLogger().info("Added permission " + s + " to " + player.getName() + "");
                                }
                            }
                            List<String> commands = getChallengeConfig().getStringList("challenges.levelUnlock." + level + ".commands");
                            runCommands(player, commands);
                            // Fire event
                            ChallengeLevelCompleteEvent event = new ChallengeLevelCompleteEvent(player, oldLevel, newLevel, rewardedItems);
                            plugin.getServer().getPluginManager().callEvent(event);
                            // Save player
                            plugin.getPlayers().save(player.getUniqueId());
                        }
                    }
                }
                return true;
            }
            return false;
        default:
            return false;
    }
}
Also used : Player(org.bukkit.entity.Player) EconomyResponse(net.milkbowl.vault.economy.EconomyResponse) ArrayList(java.util.ArrayList) List(java.util.List) ItemStack(org.bukkit.inventory.ItemStack) ChallengeLevelCompleteEvent(com.wasteofplastic.acidisland.events.ChallengeLevelCompleteEvent)

Example 5 with EconomyResponse

use of net.milkbowl.vault.economy.EconomyResponse in project acidisland by tastybento.

the class Challenges method hasRequired.

/**
 * Checks if a player has enough for a challenge. Supports two types of
 * checks, inventory and island. Removes items if required.
 *
 * @param player
 * @param challenge
 * @param type
 * @return true if the player has everything required
 */
public boolean hasRequired(final Player player, final String challenge, final String type) {
    // Check money
    double moneyReq = 0D;
    if (Settings.useEconomy) {
        moneyReq = getChallengeConfig().getDouble("challenges.challengeList." + challenge + ".requiredMoney", 0D);
        if (moneyReq > 0D) {
            if (!VaultHelper.econ.has(player, Settings.worldName, moneyReq)) {
                Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorNotEnoughItems);
                String desc = ChatColor.translateAlternateColorCodes('&', getChallengeConfig().getString("challenges.challengeList." + challenge + ".description").replace("[label]", Settings.ISLANDCOMMAND));
                List<String> result = new ArrayList<String>();
                if (desc.contains("|")) {
                    result.addAll(Arrays.asList(desc.split("\\|")));
                } else {
                    result.add(desc);
                }
                for (String line : result) {
                    Util.sendMessage(player, ChatColor.RED + line);
                }
                return false;
            }
        }
    }
    final String reqList = getChallengeConfig().getString("challenges.challengeList." + challenge + ".requiredItems");
    // standard items can be collected
    if (type.equalsIgnoreCase("inventory")) {
        List<ItemStack> toBeRemoved = new ArrayList<ItemStack>();
        Material reqItem;
        int reqAmount = 0;
        if (!reqList.isEmpty()) {
            for (final String s : reqList.split(" ")) {
                final String[] part = s.split(":");
                // Material:Qty
                if (part.length == 2) {
                    try {
                        // Correct some common mistakes
                        if (part[0].equalsIgnoreCase("potato")) {
                            part[0] = "POTATO_ITEM";
                        } else if (part[0].equalsIgnoreCase("brewing_stand")) {
                            part[0] = "BREWING_STAND_ITEM";
                        } else if (part[0].equalsIgnoreCase("carrot")) {
                            part[0] = "CARROT_ITEM";
                        } else if (part[0].equalsIgnoreCase("cauldron")) {
                            part[0] = "CAULDRON_ITEM";
                        } else if (part[0].equalsIgnoreCase("skull")) {
                            part[0] = "SKULL_ITEM";
                        }
                        // TODO: add netherwart vs. netherstalk?
                        if (StringUtils.isNumeric(part[0])) {
                            reqItem = Material.getMaterial(Integer.parseInt(part[0]));
                        } else {
                            reqItem = Material.getMaterial(part[0].toUpperCase());
                        }
                        reqAmount = Integer.parseInt(part[1]);
                        ItemStack item = new ItemStack(reqItem);
                        if (DEBUG) {
                            plugin.getLogger().info("DEBUG: required item = " + reqItem.toString());
                            plugin.getLogger().info("DEBUG: item amount = " + reqAmount);
                        }
                        if (!player.getInventory().contains(reqItem)) {
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: item not in inventory");
                            return false;
                        } else {
                            // check amount
                            int amount = 0;
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: Amount in inventory = " + player.getInventory().all(reqItem).size());
                            // enough required items
                            for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem).entrySet()) {
                                // Get the item
                                ItemStack i = en.getValue();
                                // If the item is enchanted, skip - it doesn't count
                                if (!i.getEnchantments().isEmpty()) {
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: item has enchantment - doesn't count");
                                    continue;
                                }
                                // in the same way, they need adding too...
                                if (i.getDurability() == 0 || (reqItem == Material.MAP && i.getType() == Material.MAP)) {
                                    // amount += i.getAmount();
                                    if ((amount + i.getAmount()) < reqAmount) {
                                        // Remove all of this item stack - clone
                                        // otherwise it will keep a reference to
                                        // the
                                        // original
                                        toBeRemoved.add(i.clone());
                                        amount += i.getAmount();
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: amount is <= req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount());
                                    } else if ((amount + i.getAmount()) == reqAmount) {
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: amount is = req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount());
                                        toBeRemoved.add(i.clone());
                                        amount += i.getAmount();
                                        break;
                                    } else {
                                        // Remove a portion of this item
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: amount is > req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount());
                                        item.setAmount(reqAmount - amount);
                                        item.setDurability(i.getDurability());
                                        toBeRemoved.add(item);
                                        amount += i.getAmount();
                                        break;
                                    }
                                }
                            }
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: amount " + amount);
                            if (amount < reqAmount) {
                                return false;
                            }
                        }
                    } catch (Exception e) {
                        plugin.getLogger().severe("Problem with " + s + " in challenges.yml!");
                        Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady);
                        String materialList = "";
                        boolean hint = false;
                        for (Material m : Material.values()) {
                            materialList += m.toString() + ",";
                            if (m.toString().contains(s.substring(0, 3).toUpperCase())) {
                                plugin.getLogger().severe("Did you mean " + m.toString() + "?");
                                hint = true;
                            }
                        }
                        if (!hint) {
                            plugin.getLogger().severe("Sorry, I have no idea what " + s + " is. Pick from one of these:");
                            plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1));
                        } else {
                            plugin.getLogger().severe("Correct challenges.yml with the correct material.");
                        }
                        return false;
                    }
                } else if (part.length == 3) {
                    if (DEBUG)
                        plugin.getLogger().info("DEBUG: Item with durability");
                    // Correct some common mistakes
                    if (part[0].equalsIgnoreCase("potato")) {
                        part[0] = "POTATO_ITEM";
                    } else if (part[0].equalsIgnoreCase("brewing_stand")) {
                        part[0] = "BREWING_STAND_ITEM";
                    } else if (part[0].equalsIgnoreCase("carrot")) {
                        part[0] = "CARROT_ITEM";
                    } else if (part[0].equalsIgnoreCase("cauldron")) {
                        part[0] = "CAULDRON_ITEM";
                    } else if (part[0].equalsIgnoreCase("skull")) {
                        part[0] = "SKULL_ITEM";
                    }
                    if (StringUtils.isNumeric(part[0])) {
                        reqItem = Material.getMaterial(Integer.parseInt(part[0]));
                    } else {
                        reqItem = Material.getMaterial(part[0].toUpperCase());
                    }
                    reqAmount = Integer.parseInt(part[2]);
                    int reqDurability = Integer.parseInt(part[1]);
                    ItemStack item = new ItemStack(reqItem);
                    // Item
                    item.setDurability((short) reqDurability);
                    // check amount
                    int amount = 0;
                    // enough required items
                    for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem).entrySet()) {
                        // Get the item
                        ItemStack i = en.getValue();
                        if (i.hasItemMeta()) {
                            continue;
                        }
                        if (i.getDurability() == reqDurability) {
                            // amount += i.getAmount();
                            if ((amount + i.getAmount()) < reqAmount) {
                                // Remove all of this item stack - clone
                                // otherwise it will keep a reference to
                                // the
                                // original
                                toBeRemoved.add(i.clone());
                                amount += i.getAmount();
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: amount is <= req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount());
                            } else if ((amount + i.getAmount()) == reqAmount) {
                                toBeRemoved.add(i.clone());
                                amount += i.getAmount();
                                break;
                            } else {
                                // Remove a portion of this item
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: amount is > req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount());
                                item.setAmount(reqAmount - amount);
                                item.setDurability(i.getDurability());
                                toBeRemoved.add(item);
                                amount += i.getAmount();
                                break;
                            }
                        }
                    }
                    if (DEBUG) {
                        plugin.getLogger().info("DEBUG: amount is " + amount);
                        plugin.getLogger().info("DEBUG: req amount is " + reqAmount);
                    }
                    if (amount < reqAmount) {
                        if (DEBUG)
                            plugin.getLogger().info("DEBUG: Failure! Insufficient amount of " + item.toString() + " required = " + reqAmount + " actual = " + amount);
                        return false;
                    }
                    if (DEBUG)
                        plugin.getLogger().info("DEBUG: before set amount " + item.toString() + ":" + item.getDurability() + " x " + item.getAmount());
                } else if (part.length == 6 && part[0].contains("POTION")) {
                    // Run through player's inventory for the item
                    ItemStack[] playerInv = player.getInventory().getContents();
                    try {
                        reqAmount = Integer.parseInt(part[5]);
                        if (DEBUG)
                            plugin.getLogger().info("DEBUG: required amount is " + reqAmount);
                    } catch (Exception e) {
                        plugin.getLogger().severe("Could not parse the quantity of the potion item " + s);
                        return false;
                    }
                    int count = reqAmount;
                    for (ItemStack i : playerInv) {
                        // Catches all POTION, LINGERING_POTION and SPLASH_POTION
                        if (i != null && i.getType().toString().contains("POTION")) {
                            // POTION:NAME:<LEVEL>:<EXTENDED>:<SPLASH/LINGER>:QTY
                            if (plugin.getServer().getVersion().contains("(MC: 1.8") || plugin.getServer().getVersion().contains("(MC: 1.7")) {
                                // Test potion
                                Potion potion = null;
                                try {
                                    // This may fail if there are custom potions in the player's inventory
                                    // If so, just skip this item stack.
                                    potion = Potion.fromItemStack(i);
                                } catch (Exception e) {
                                    potion = null;
                                }
                                if (potion != null) {
                                    PotionType potionType = potion.getType();
                                    boolean match = true;
                                    if (DEBUG) {
                                        plugin.getLogger().info("DEBUG: name check " + part[1]);
                                        plugin.getLogger().info("DEBUG: potion = " + potion);
                                        plugin.getLogger().info("DEBUG: potionType = " + potionType);
                                        plugin.getLogger().info("DEBUG: part[1] = " + part[1]);
                                    }
                                    // Name check
                                    if (potionType != null && !part[1].isEmpty()) {
                                        // Custom potions may not have names
                                        if (potionType.name() != null) {
                                            if (!part[1].equalsIgnoreCase(potionType.name())) {
                                                match = false;
                                                if (DEBUG)
                                                    plugin.getLogger().info("DEBUG: name does not match");
                                            } else {
                                                if (DEBUG)
                                                    plugin.getLogger().info("DEBUG: name matches");
                                            }
                                        } else {
                                            plugin.getLogger().severe("Potion type is unknown. Please pick from the following:");
                                            for (PotionType pt : PotionType.values()) {
                                                plugin.getLogger().severe(pt.name());
                                            }
                                            match = false;
                                        }
                                    } else {
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: potionType = null");
                                        match = false;
                                    }
                                    // Level check (upgraded)
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: level check " + part[2]);
                                    if (!part[2].isEmpty()) {
                                        // There is a level declared - check it
                                        if (StringUtils.isNumeric(part[2])) {
                                            int level = Integer.valueOf(part[2]);
                                            if (level != potion.getLevel()) {
                                                if (DEBUG)
                                                    plugin.getLogger().info("DEBUG: level does not match");
                                                match = false;
                                            }
                                        }
                                    }
                                    // Extended check
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: extended check " + part[3]);
                                    if (!part[3].isEmpty()) {
                                        if (part[3].equalsIgnoreCase("EXTENDED") && !potion.hasExtendedDuration()) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: extended does not match");
                                        }
                                        if (part[3].equalsIgnoreCase("NOTEXTENDED") && potion.hasExtendedDuration()) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: extended does not match");
                                        }
                                    }
                                    // Splash check
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: splash/linger check " + part[4]);
                                    if (!part[4].isEmpty()) {
                                        if (part[4].equalsIgnoreCase("SPLASH") && !potion.isSplash()) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: not splash");
                                        }
                                        if (part[4].equalsIgnoreCase("NOSPLASH") && potion.isSplash()) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: not no splash");
                                        }
                                    }
                                    // Quantity check
                                    if (match) {
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: potion matches!");
                                        ItemStack removeItem = i.clone();
                                        if (removeItem.getAmount() > reqAmount) {
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: found " + removeItem.getAmount() + " qty in inv");
                                            removeItem.setAmount(reqAmount);
                                        }
                                        count = count - removeItem.getAmount();
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: " + count + " left");
                                        toBeRemoved.add(removeItem);
                                    }
                                }
                            } else {
                                // V1.9 and above
                                PotionMeta potionMeta = (PotionMeta) i.getItemMeta();
                                // If any of the settings above are missing, then any is okay
                                boolean match = true;
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: name check " + part[1]);
                                // Name check
                                if (!part[1].isEmpty()) {
                                    // There is a name
                                    if (PotionType.valueOf(part[1]) != null) {
                                        if (!potionMeta.getBasePotionData().getType().name().equalsIgnoreCase(part[1])) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: name does not match");
                                        } else {
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: name matches");
                                        }
                                    } else {
                                        plugin.getLogger().severe("Potion type is unknown. Please pick from the following:");
                                        for (PotionType pt : PotionType.values()) {
                                            plugin.getLogger().severe(pt.name());
                                        }
                                        match = false;
                                    }
                                }
                                // plugin.getLogger().info("DEBUG: level check " + part[2]);
                                if (!part[2].isEmpty()) {
                                    // There is a level declared - check it
                                    if (StringUtils.isNumeric(part[2])) {
                                        int level = Integer.valueOf(part[2]);
                                        if (level == 1 && potionMeta.getBasePotionData().isUpgraded()) {
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: level does not match");
                                            match = false;
                                        }
                                        if (level != 1 && !potionMeta.getBasePotionData().isUpgraded()) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: level does not match");
                                        }
                                    }
                                }
                                // Extended check
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: extended check " + part[3]);
                                if (!part[3].isEmpty()) {
                                    if (part[3].equalsIgnoreCase("EXTENDED") && !potionMeta.getBasePotionData().isExtended()) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: extended does not match");
                                    }
                                    if (part[3].equalsIgnoreCase("NOTEXTENDED") && potionMeta.getBasePotionData().isExtended()) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: extended does not match");
                                    }
                                }
                                // Splash or Linger check
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: splash/linger check " + part[4]);
                                if (!part[4].isEmpty()) {
                                    if (part[4].equalsIgnoreCase("SPLASH") && !i.getType().equals(Material.SPLASH_POTION)) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not splash");
                                    }
                                    if (part[4].equalsIgnoreCase("NOSPLASH") && i.getType().equals(Material.SPLASH_POTION)) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not no splash");
                                    }
                                    if (part[4].equalsIgnoreCase("LINGER") && !i.getType().equals(Material.LINGERING_POTION)) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not linger");
                                    }
                                    if (part[4].equalsIgnoreCase("NOLINGER") && i.getType().equals(Material.LINGERING_POTION)) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not no linger");
                                    }
                                }
                                // Quantity check
                                if (match) {
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: potion matches!");
                                    ItemStack removeItem = i.clone();
                                    if (removeItem.getAmount() > reqAmount) {
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: found " + removeItem.getAmount() + " qty in inv");
                                        removeItem.setAmount(reqAmount);
                                    }
                                    count = count - removeItem.getAmount();
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: " + count + " left");
                                    toBeRemoved.add(removeItem);
                                }
                            }
                        }
                        if (count <= 0) {
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: Player has enough");
                            break;
                        }
                        if (DEBUG)
                            plugin.getLogger().info("DEBUG: still need " + count + " to complete");
                    }
                    if (count > 0) {
                        if (DEBUG)
                            plugin.getLogger().info("DEBUG: Player does not have enough");
                        return false;
                    }
                } else {
                    plugin.getLogger().severe("Problem with " + s + " in challenges.yml!");
                    return false;
                }
            }
        }
        if (getChallengeConfig().getBoolean("challenges.challengeList." + challenge + ".takeItems")) {
            // int qty = 0;
            if (DEBUG)
                plugin.getLogger().info("DEBUG: Removing items");
            for (ItemStack i : toBeRemoved) {
                // qty += i.getAmount();
                if (DEBUG)
                    plugin.getLogger().info("DEBUG: Remove " + i.toString() + "::" + i.getDurability() + " x " + i.getAmount());
                HashMap<Integer, ItemStack> leftOver = player.getInventory().removeItem(i);
                if (!leftOver.isEmpty()) {
                    plugin.getLogger().warning("Exploit? Could not remove the following in challenge " + challenge + " for player " + player.getName() + ":");
                    for (ItemStack left : leftOver.values()) {
                        plugin.getLogger().info(left.toString());
                    }
                    return false;
                }
            }
            // Remove money
            if (moneyReq > 0D) {
                EconomyResponse er = VaultHelper.econ.withdrawPlayer(player, moneyReq);
                if (!er.transactionSuccess()) {
                    plugin.getLogger().warning("Exploit? Could not remove " + VaultHelper.econ.format(moneyReq) + " from " + player.getName() + " in challenge " + challenge);
                    plugin.getLogger().warning("Player's balance is " + VaultHelper.econ.format(VaultHelper.econ.getBalance(player)));
                }
            }
        // plugin.getLogger().info("DEBUG: total = " + qty);
        }
        return true;
    }
    if (type.equalsIgnoreCase("island")) {
        final HashMap<MaterialData, Integer> neededItem = new HashMap<MaterialData, Integer>();
        final HashMap<EntityType, Integer> neededEntities = new HashMap<EntityType, Integer>();
        if (!reqList.isEmpty()) {
            for (int i = 0; i < reqList.split(" ").length; i++) {
                final String[] sPart = reqList.split(" ")[i].split(":");
                try {
                    // Find out if the needed item is a Material or an Entity
                    boolean isEntity = false;
                    for (EntityType entityType : EntityType.values()) {
                        if (entityType.toString().equalsIgnoreCase(sPart[0])) {
                            isEntity = true;
                            break;
                        }
                    }
                    if (isEntity) {
                        // plugin.getLogger().info("DEBUG: Item " + sPart[0].toUpperCase() + " is an entity");
                        EntityType entityType = EntityType.valueOf(sPart[0].toUpperCase());
                        if (entityType != null) {
                            neededEntities.put(entityType, Integer.parseInt(sPart[1]));
                        // plugin.getLogger().info("DEBUG: Needed entity is " + Integer.parseInt(sPart[1]) + " x " + EntityType.valueOf(sPart[0].toUpperCase()).toString());
                        }
                    } else {
                        Material item;
                        if (StringUtils.isNumeric(sPart[0])) {
                            item = Material.getMaterial(Integer.parseInt(sPart[0]));
                        } else {
                            item = Material.getMaterial(sPart[0].toUpperCase());
                        }
                        if (item != null) {
                            // We have two cases : quantity only OR durability + quantity
                            final int quantity;
                            final byte durability;
                            if (sPart.length == 2) {
                                // Only a quantity is specified
                                quantity = Integer.parseInt(sPart[1]);
                                durability = 0;
                            } else {
                                quantity = Integer.parseInt(sPart[2]);
                                durability = Byte.parseByte(sPart[1]);
                            }
                            neededItem.put(new MaterialData(item, durability), quantity);
                        // plugin.getLogger().info("DEBUG: Needed item is " + Integer.parseInt(sPart[1]) + " x " + Material.getMaterial(sPart[0]).toString());
                        } else {
                            plugin.getLogger().warning("Problem parsing required item for challenge " + challenge + " in challenges.yml!");
                            return false;
                        }
                    }
                } catch (Exception intEx) {
                    plugin.getLogger().warning("Problem parsing required items for challenge " + challenge + " in challenges.yml - skipping");
                    return false;
                }
            }
        }
        // We now have two sets of required items or entities
        // Check the items first
        final Location l = player.getLocation();
        // if (!neededItem.isEmpty()) {
        final int px = l.getBlockX();
        final int py = l.getBlockY();
        final int pz = l.getBlockZ();
        // Get search radius - min is 10, max is 50
        int searchRadius = getChallengeConfig().getInt("challenges.challengeList." + challenge + ".searchRadius", 10);
        if (searchRadius < 10) {
            searchRadius = 10;
        } else if (searchRadius > 50) {
            searchRadius = 50;
        }
        for (int x = -searchRadius; x <= searchRadius; x++) {
            for (int y = -searchRadius; y <= searchRadius; y++) {
                for (int z = -searchRadius; z <= searchRadius; z++) {
                    final MaterialData b = new Location(l.getWorld(), px + x, py + y, pz + z).getBlock().getState().getData();
                    if (neededItem.containsKey(b)) {
                        if (neededItem.get(b) == 1) {
                            neededItem.remove(b);
                        } else {
                            // Reduce the require amount by 1
                            neededItem.put(b, neededItem.get(b) - 1);
                        }
                    }
                }
            }
        }
        // Check if all the needed items have been amassed
        if (!neededItem.isEmpty()) {
            // plugin.getLogger().info("DEBUG: Insufficient items around");
            for (MaterialData missing : neededItem.keySet()) {
                Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " " + neededItem.get(missing) + " x " + Util.prettifyText(missing.getItemType().toString()) + ":" + missing.getData());
            }
            return false;
        } else {
            // Check for needed entities
            for (Entity entity : player.getNearbyEntities(searchRadius, searchRadius, searchRadius)) {
                // entity.getType().toString());
                if (neededEntities.containsKey(entity.getType())) {
                    // plugin.getLogger().info("DEBUG: Entity in list");
                    if (neededEntities.get(entity.getType()) == 1) {
                        neededEntities.remove(entity.getType());
                    // plugin.getLogger().info("DEBUG: Entity qty satisfied");
                    } else {
                        neededEntities.put(entity.getType(), neededEntities.get(entity.getType()) - 1);
                    // plugin.getLogger().info("DEBUG: Entity qty reduced by 1");
                    }
                } else {
                // plugin.getLogger().info("DEBUG: Entity not in list");
                }
            }
            if (neededEntities.isEmpty()) {
                return true;
            } else {
                for (EntityType missing : neededEntities.keySet()) {
                    Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " " + neededEntities.get(missing) + " x " + Util.prettifyText(missing.toString()));
                }
                return false;
            }
        }
    }
    return true;
}
Also used : Entity(org.bukkit.entity.Entity) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) Entry(java.util.Map.Entry) EconomyResponse(net.milkbowl.vault.economy.EconomyResponse) Potion(org.bukkit.potion.Potion) Material(org.bukkit.Material) PotionMeta(org.bukkit.inventory.meta.PotionMeta) IOException(java.io.IOException) EntityType(org.bukkit.entity.EntityType) PotionType(org.bukkit.potion.PotionType) MaterialData(org.bukkit.material.MaterialData) ItemStack(org.bukkit.inventory.ItemStack) Location(org.bukkit.Location)

Aggregations

EconomyResponse (net.milkbowl.vault.economy.EconomyResponse)5 ItemStack (org.bukkit.inventory.ItemStack)4 Player (org.bukkit.entity.Player)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 ChallengeCompleteEvent (com.wasteofplastic.acidisland.events.ChallengeCompleteEvent)1 ChallengeLevelCompleteEvent (com.wasteofplastic.acidisland.events.ChallengeLevelCompleteEvent)1 MiniShopEvent (com.wasteofplastic.acidisland.events.MiniShopEvent)1 BigDecimal (java.math.BigDecimal)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1 Entry (java.util.Map.Entry)1 Location (org.bukkit.Location)1 Material (org.bukkit.Material)1 Entity (org.bukkit.entity.Entity)1 EntityType (org.bukkit.entity.EntityType)1 EventHandler (org.bukkit.event.EventHandler)1 Inventory (org.bukkit.inventory.Inventory)1 PotionMeta (org.bukkit.inventory.meta.PotionMeta)1