Randomly enchanting a book

Discussion in 'Plugin Development' started by Reinified, Feb 23, 2018.

Thread Status:
Not open for further replies.
  1. Here's my code. The only issue (to my knowledge) is the itemstack thing. How would I fix it so it forces you to be holding a book? Thanks for the help in advance.
    Code:
    if (cmd.getName().equalsIgnoreCase("randomenchant")) {
                Player p = (Player) sender;
                if (p.getItemInHand() == new ItemStack(Material.BOOK)) {
                    if (p.getExpToLevel() > 9) {
                    ItemMeta im = p.getItemInHand().getItemMeta();
                    int max = 24;
                    int min = 0;
                    Random randomNum = new Random();
                    int val = min + randomNum.nextInt(max);
                    int max2 = 4;
                    int min2 = 1;
                    Random randomNum2 = new Random();
                    int val2 = min2 + randomNum2.nextInt(max);
                    im.addEnchant(hm.get(val), val2, true);
                    sender.sendMessage(ChatColor.GREEN + "You got: " + hm.get(val).toString() + ". 10 levels have been removed.");
                } else {
                    sender.sendMessage(ChatColor.GREEN + "You must have atleast 10 levels to do this!");
                }
                }else {
                    sender.sendMessage(ChatColor.RED + "You must be holding a book.");
                    sender.sendMessage(p.getItemInHand().toString());
                }
            }
    Clarify: The issue is that whatever you hold, it says you must be holding a book.
    the sender.sendmessage after "you must be holding a book" is for testing purposes only
     
  2. Offline

    Nostos

    I think your problem lies with the else { } statements. try:
    Code:
    else if(p.getExpToLevel() < 10)
    instead of just regular else. same concept applies with the other else:
    Code:
    else if(!p.getItemInHand() == new ItemStack(Material.BOOK))
     
  3. Offline

    DutchJellyV2

    Hey I'm pretty sure you're giving regular enchants to books which will for instance give books actual knockback with a knockback enchant. To give a book the enchant that's only used to enchant other items, you'll have to do the following:
    Code:
    EnchantmentStorageMeta storedEnchantMeta = (EnchantmentStorageMeta)item.getItemMeta();
    Simply add enchants to the storedEnchantMeta instead.
    I hope I helped somehow.
     
Thread Status:
Not open for further replies.

Share This Page