Multiple Custom Enchants

Discussion in 'Plugin Development' started by Richard12799, Jul 13, 2018 at 2:50 PM.

  1. Offline

    Richard12799

    Hello! So I'm creating a custom enchant plugin, but whenever I add an enchant to an item, it seems to add all the custom enchants I have in my project. Any ideas?


    First Enchant:
    Code:
    package me.richard12799.customenchant;
    
    import org.bukkit.Material;
    import org.bukkit.enchantments.Enchantment;
    import org.bukkit.enchantments.EnchantmentTarget;
    import org.bukkit.entity.Entity;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.entity.EntityShootBowEvent;
    import org.bukkit.inventory.ItemStack;
    
    public class TripleShot extends Enchantment {
       
    
        public TripleShot(int id) {
            super(id);
        }
       
        @Override
        public int getId() {
            return 1001;
        }
    
        @Override
        public boolean canEnchantItem(ItemStack arg0) {
            return true;
        }
    
        @Override
        public boolean conflictsWith(Enchantment arg0) {
            return false;
        }
    
        @Override
        public EnchantmentTarget getItemTarget() {
            return null;
        }
    
        @Override
        public int getMaxLevel() {
            return 1;
        }
    
        @Override
        public String getName() {
            return "TripleShot";
        }
    
        @Override
        public int getStartLevel() {
            return 1;
        }
    
        @Override
        public boolean isCursed() {
            return false;
        }
    
        @Override
        public boolean isTreasure() {
            return false;
        }
    }
    

    Second enchant:
    Code:
    package me.richard12799.customenchant;
    
    import org.bukkit.enchantments.Enchantment;
    import org.bukkit.enchantments.EnchantmentTarget;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.entity.EntityShootBowEvent;
    import org.bukkit.event.entity.ProjectileHitEvent;
    import org.bukkit.inventory.ItemStack;
    
    public class Explosive extends Enchantment {
    
        public Explosive(int id) {
            super(id);
        }
       
       
        @Override
        public int getId() {
            return 1002;
        }
    
        @Override
        public boolean canEnchantItem(ItemStack arg0) {
            return true;
        }
    
        @Override
        public boolean conflictsWith(Enchantment arg0) {
            return false;
        }
    
        @Override
        public EnchantmentTarget getItemTarget() {
            return null;
        }
    
        @Override
        public int getMaxLevel() {
            return 1;
        }
    
        @Override
        public String getName() {
            return "Explosive";
        }
    
        @Override
        public int getStartLevel() {
            return 1;
        }
    
        @Override
        public boolean isCursed() {
            return false;
        }
    
        @Override
        public boolean isTreasure() {
            return false;
        }
       
       
    }
    

    Main Class:
    Code:
    package me.richard12799.customenchant;
    
    import java.lang.reflect.Field;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.enchantments.Enchantment;
    import org.bukkit.entity.Player;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public class CustomEnchant extends JavaPlugin {
      
        private Inventory enchantInventory;
      
        public TripleShot tripleShot;
        public Explosive explosive;
          
        public List<Enchantment> ench;
      
        public int[][] costGrid;
          
        @Override
        public void onEnable() {
            super.onEnable();
            LoadEnchantments();
          
            costGrid = new int[2000][10];
          
            int[] tripleCost = costGrid[1001];
            tripleCost[1]=23;
          
            //TODO load config and get costs and send them in to grid
          
          
            getServer().getPluginManager().registerEvents(new Events(this), this);
          
            ench = new ArrayList<Enchantment>();
          
            tripleShot = new TripleShot(1001);
            ench.add(tripleShot);
          
            explosive = new Explosive(1002);
            ench.add(explosive);
          
            // TODO Add all enchants
          
        }
      
        @SuppressWarnings("unchecked")
        public void onDisable() {
            try {
                Field byIdField = Enchantment.class.getDeclaredField("byId");
                Field byNameField = Enchantment.class.getDeclaredField("byName");
    
                byIdField.setAccessible(true);
                byNameField.setAccessible(true);
    
                HashMap<Integer, Enchantment> byId = (HashMap<Integer, Enchantment>) byIdField.get(null);
                HashMap<Integer, Enchantment> byName = (HashMap<Integer, Enchantment>) byNameField.get(null);
    
              
                for(Enchantment e: ench) {
                    if (byId.containsKey(e.getId())) {
                        byId.remove(e.getId());
                    }
    
                    if (byName.containsKey(e.getName())) {
                        byName.remove(e.getName());
                    }
                }
              
            } catch (Exception ignored) {
            }
        }
    
        private void LoadEnchantments() {
            try {
                try {
                    Field f = Enchantment.class.getDeclaredField("acceptingNew");
                    f.setAccessible(true);
                    f.set(null, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
                try {
                    Enchantment.registerEnchantment(tripleShot);
                    Enchantment.registerEnchantment(explosive);
                    //TODO register all enchantments
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
      
        @Override
        public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
          
            if(label.equalsIgnoreCase("cenchant")) {
                if(!(sender instanceof Player)) {
                    return false;
                }
                Player player = (Player) sender;
                ItemStack item = player.getInventory().getItemInMainHand();
                if(item == null || item.getType() == Material.AIR) {
                    player.sendMessage("§cYou must have an item in your hand to enchant!");
                    return false;
                }
                createEnchantInventory(item);
                player.openInventory(enchantInventory);
                return true;
            }
          
            return false;
        }
      
        private void createEnchantInventory(ItemStack item) {
            enchantInventory=Bukkit.createInventory(null,27,"Custom Enchants");
          
            System.out.println(item.getItemMeta().getEnchants().toString());
          
            Map<Enchantment, Integer> enchants = new HashMap<Enchantment, Integer>();
          
    //        for(Enchantment e: enchants.keySet()) {
    //            used.add(e.getName());
    //            System.out.println(e.getName() + " " + enchants.get(e));
    //        }
          
            for(Enchantment e: ench) {
                System.out.println(e.getName()+e.getId());
                if(item.containsEnchantment(e)) {
                    System.out.println("y");
                    enchants.put(e, item.getEnchantmentLevel(e));
                } else {
                    System.out.println("n");
                    enchants.put(e, 0);
                }
            }
          
          
          
            for(Enchantment e: enchants.keySet()) {
                if(e.getName().equalsIgnoreCase("TripleShot")) {
                    int level = enchants.get(e);
                    addItem(e.getId(),Material.BOW,e.getName(), level, level==e.getMaxLevel());
                } else if(e.getName().equalsIgnoreCase("Explosive")) {
                    int level = enchants.get(e);
                    addItem(e.getId(), Material.BOW, e.getName(), level, level == e.getMaxLevel());
                }
            }
          
          
        }
      
    //    private Map<Enchantment, Integer> getEnchants(List<String> lore) {
    //      
    //        Map<Enchantment, Integer> map = new HashMap<Enchantment, Integer>();
    //      
    //        for(String s: lore) {
    //            String[] split = s.split(" ");
    //            for(Enchantment e: ench) {
    //                if(ChatColor.stripColor(split[0]).equalsIgnoreCase(e.getName())) {
    //                    map.put(e, getNum(split[1]));
    //                }
    //            }
    //        }
    //        return map;
    //    }
    //  
    //    private int getNum(String s) {
    //        if(s.equals("I")) return 1;
    //        else if(s.equals("II")) return 2;
    //        else if(s.equals("III")) return 3;
    //        else if(s.equals("IV")) return 4;
    //        else if(s.equals("V")) return 5;
    //        else if(s.equals("VI")) return 6;
    //        else if(s.equals("VII")) return 7;
    //        else if(s.equals("VIII")) return 8;
    //        else if(s.equals("IX")) return 9;
    //        else if(s.equals("X")) return 10;
    //        else return 0;
    //      
    //    }
      
        private void addItem(int id, Material m, String name, int amount, boolean maxed) {
            // TODO Fix update level system
            ItemStack i = new ItemStack(m);
            i.setAmount(1);
            ItemMeta im = i.getItemMeta();
            List<String> lore = new ArrayList<String>();
            lore.add("");
            if(maxed) lore.add(ChatColor.RED+"Max Level");
            else lore.add(ChatColor.GRAY+"Upgrade to Level "+(amount+1));
          
            if(!maxed) lore.add(ChatColor.GOLD+"Cost: $"+costGrid[id][amount+1]);
          
            lore.add("");
            im.setLore(lore);
            im.setDisplayName("§a"+name);
            i.setItemMeta(im);
            enchantInventory.addItem(i);
            System.out.println("Added "+m.toString()+ " of amount "+amount);
        }
      
    }
    
    Events Class:
    Code:
    package me.richard12799.customenchant;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.enchantments.Enchantment;
    import org.bukkit.entity.Entity;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.entity.EntityShootBowEvent;
    import org.bukkit.event.entity.ProjectileHitEvent;
    import org.bukkit.event.inventory.InventoryClickEvent;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    
    public class Events implements Listener {
       
        private CustomEnchant plugin;
       
        public Events(CustomEnchant p) {
            plugin=p;
        }
       
        @EventHandler
        public void onJoin(PlayerJoinEvent event) {
            Player player = event.getPlayer();
    
            ItemStack item = new ItemStack(Material.BOW);
            ItemMeta meta = item.getItemMeta();
            ArrayList<String> lore = new ArrayList<String>();
            lore.add(ChatColor.GRAY + plugin.explosive.getName() + " I");
            meta.setDisplayName(ChatColor.GOLD + "Explosive Axe");
            meta.setLore(lore);
            item.setItemMeta(meta);
            item.addUnsafeEnchantment(plugin.explosive, 1);
           
            player.getInventory().addItem(item);
        }
       
        @EventHandler
        public void onArrowShoot(EntityShootBowEvent event) {
            if(event.getEntity() instanceof Player) {
                if(event.getBow().containsEnchantment(plugin.explosive)) {
                    event.getProjectile().setCustomName("Explode");
                    event.getProjectile().setCustomNameVisible(false);
                }
            }
        }
       
        @EventHandler
        public void onShoot(EntityShootBowEvent event) {
            if(event.getEntity() instanceof Player) {
                Player player = (Player) event.getEntity();
                if(!player.getInventory().getItemInMainHand().containsEnchantment(plugin.tripleShot)) return;
                System.out.println(player.getInventory().getItemInMainHand().containsEnchantment(plugin.tripleShot));
                if (event.getForce()==1.0) {
                    System.out.println("3arrows");
                    Entity mainArrow = event.getProjectile();
                 
                    for (int i = 1;i < 3;i++) {
                        mainArrow.getWorld().spawnArrow(mainArrow.getLocation(), mainArrow.getVelocity(), 3, 3).setShooter(event.getEntity());
                    }
                }
            }
        }
       
        @EventHandler
        public void onArrowLand(ProjectileHitEvent event) {
            if(event.getEntity() == null || event.getEntity().getCustomName() == null) return;
            if(event.getEntity().getCustomName().equals("Explode")) {
                if(event.getHitBlock() != null) {
                    event.getEntity().getWorld().createExplosion(event.getHitBlock().getLocation(), 2);
                }
                if(event.getHitEntity() != null) {
                    event.getEntity().getWorld().createExplosion(event.getHitEntity().getLocation(), 2);
                }
            }
        }
       
        @EventHandler
        public void onClick(InventoryClickEvent event) {
           
            ItemStack clicked = event.getCurrentItem();
           
            if(event.getInventory().getName().equalsIgnoreCase("Custom Enchants")) {
                Player player = (Player) event.getWhoClicked();
                    String name = clicked.getItemMeta().getDisplayName();
                    if(name != null) {
                        for(Enchantment e: plugin.ench) {
                            if(e.getName().equalsIgnoreCase(ChatColor.stripColor(name))) {
                                ItemStack itemToEnchant = ((Player) event.getWhoClicked()).getInventory().getItemInMainHand();
                                int currentEnchant = itemToEnchant.containsEnchantment(e)?itemToEnchant.getEnchantmentLevel(e):0;
                                if(itemToEnchant.getType() != clicked.getType()) { //TODO won't work with armor
                                    event.getWhoClicked().sendMessage("§cThis enchant cannot be applied to your current item!");
                                    event.setCancelled(true);
                                    return;
                                }
                                if(itemToEnchant != null) {
                                   
                                    if(currentEnchant == e.getMaxLevel()) {
                                        player.sendMessage("§cYou have already reached the max level for this enchant!");
                                        event.setCancelled(true);
                                        return;
                                    }
                                   
                                   
                                   
                                    clicked.setAmount(currentEnchant==0?1:currentEnchant+1);
                                    player.updateInventory();
                                    List<String> lore = itemToEnchant.getItemMeta().getLore();
                                    if(lore == null) {
                                        lore = new ArrayList<String>();
                                        lore.add(ChatColor.DARK_PURPLE+e.getName()+" "+numToNumeral(currentEnchant+1));
                                    } else {
                                        boolean found = false;
                                        for(int i=0;i<lore.size();i++) {
                                            if(lore.get(i).contains(e.getName())) {
                                                found = true;
                                                lore.set(i, ChatColor.DARK_PURPLE+e.getName()+" "+numToNumeral(currentEnchant+1));
                                            }
                                        }
                                        if(!found) {
                                            lore.add(ChatColor.DARK_PURPLE+e.getName()+" "+numToNumeral(currentEnchant+1));
                                        }
                                    }
                                    ItemMeta im = itemToEnchant.getItemMeta();
                                    im.setLore(lore);
                                    itemToEnchant.setItemMeta(im);
                                    System.out.println(itemToEnchant.containsEnchantment(plugin.ench.get(0))+ " "+ itemToEnchant.containsEnchantment(plugin.ench.get(1)));
                                    itemToEnchant.addEnchantment(plugin.explosive, currentEnchant+1);
                                    System.out.println(itemToEnchant.containsEnchantment(plugin.ench.get(0))+ " "+ itemToEnchant.containsEnchantment(plugin.ench.get(1)));
                                    System.out.println(itemToEnchant.getItemMeta().hasEnchant(plugin.explosive)+ " "+itemToEnchant.getItemMeta().hasEnchant(plugin.tripleShot));
    
                                    System.out.println("Enchanting "+e.getName()+ " "+(currentEnchant+1));
                                    player.sendMessage(ChatColor.AQUA+"Enchantment successfully added!");
                                    player.closeInventory();
                                    event.setCancelled(true);
                                    // TODO incorporate costs and deduct from user acc
                                }
                                return;
                            }
                        }
                    }
            }
           
        }
       
        public String numToNumeral(int i) {
            if(i==1) return "I";
            else if(i==2) return "II";
            else if(i==3) return "III";
            else if(i==4) return "IV";
            else if(i==5) return "V";
            else if(i==6) return "VI";
            else if(i==7) return "VII";
            else if(i==8) return "VIII";
            else if(i==9) return "IX";
            else return "null";
        }
    }
    
    This line of code adds both of the enchantments to the item:
    Code:
    itemToEnchant.addEnchantment(plugin.explosive, currentEnchant+1);


    Please help! Thank you!
     
    Last edited: Jul 15, 2018 at 11:22 AM
  2. Offline

    MightyOne

    The chance that something is going wrong in one line of code is quiet small. Post the rest of the class.

    Also combining an enchantment class with a listener class is not advisable for a good project structure at all.
     
  3. Offline

    Richard12799

    @MightyOne I updated the main post with my Main Class and Events Class added. I also removed the listeners from my enchant classes and combined them into my Events class. Let me know if you can help!
     

Share This Page