Search in sources :

Example 1 with EnchantItemEvent

use of org.bukkit.event.enchantment.EnchantItemEvent in project Glowstone by GlowstoneMC.

the class EnchantmentManager method onPlayerEnchant.

public void onPlayerEnchant(int clicked) {
    if (enchLevelCosts[clicked] <= 0 || isMaliciousClicked(clicked))
        return;
    ItemStack item = inventory.getItem();
    List<LeveledEnchant> enchants = calculateCurrentEnchants(item, clicked, enchLevelCosts[clicked]);
    if (enchants == null)
        enchants = new ArrayList<>();
    EnchantItemEvent event = EventFactory.callEvent(new EnchantItemEvent(player, player.getOpenInventory(), inventory.getLocation().getBlock(), item.clone(), enchLevelCosts[clicked], toMap(enchants), clicked));
    if (event.isCancelled() || player.getGameMode() != GameMode.CREATIVE && event.getExpLevelCost() > player.getLevel())
        return;
    boolean isBook = item.getType() == Material.BOOK;
    if (isBook)
        item.setType(Material.ENCHANTED_BOOK);
    Map<Enchantment, Integer> toAdd = event.getEnchantsToAdd();
    if (toAdd == null || toAdd.isEmpty()) {
        return;
    }
    for (Entry<Enchantment, Integer> enchantment : toAdd.entrySet()) {
        try {
            if (isBook) {
                EnchantmentStorageMeta meta = (EnchantmentStorageMeta) item.getItemMeta();
                //TODO is true correct here?
                meta.addStoredEnchant(enchantment.getKey(), enchantment.getValue(), true);
                item.setItemMeta(meta);
            } else {
                item.addUnsafeEnchantment(enchantment.getKey(), enchantment.getValue());
            }
        } catch (IllegalArgumentException e) {
        //ignore, since plugins are allowed to add enchantments that can't be applied
        }
    }
    player.enchanted(clicked);
    if (player.getGameMode() != GameMode.CREATIVE) {
        ItemStack res = inventory.getSecondary();
        res.setAmount(res.getAmount() - clicked + 1);
        if (res.getAmount() <= 0)
            inventory.setSecondary(null);
    }
    xpSeed = player.getXpSeed();
    update();
}
Also used : EnchantmentStorageMeta(org.bukkit.inventory.meta.EnchantmentStorageMeta) EnchantItemEvent(org.bukkit.event.enchantment.EnchantItemEvent) ItemStack(org.bukkit.inventory.ItemStack) Enchantment(org.bukkit.enchantments.Enchantment) GlowEnchantment(net.glowstone.constants.GlowEnchantment)

Aggregations

GlowEnchantment (net.glowstone.constants.GlowEnchantment)1 Enchantment (org.bukkit.enchantments.Enchantment)1 EnchantItemEvent (org.bukkit.event.enchantment.EnchantItemEvent)1 ItemStack (org.bukkit.inventory.ItemStack)1 EnchantmentStorageMeta (org.bukkit.inventory.meta.EnchantmentStorageMeta)1