Solved What am I doing wrong? (PlayerInteractEvent)

Discussion in 'Spigot Plugin Development' started by FenomPT, Sep 12, 2019 at 1:44 AM.

  1. When I click the item with the right button it just disappears and does nothing.

    Code (Text):
     
    @EventHandler
            public void toggle(PlayerInteractEvent event){
               Player player = event.getPlayer();
         
                ItemStack item = new ItemStack(Material.EXP_BOTTLE, 1);
                ItemMeta meta = player.getItemInHand().getItemMeta();
           
                if(meta.hasDisplayName()){
                    if(event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK){
                        if(player.getInventory().getItemInHand().getType() == Material.EXP_BOTTLE && meta.getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', "&6&lPote de Experiência &f(Lançe)"))){
                            for (String line : meta.getLore()) {
                                if (line.startsWith((ChatColor.translateAlternateColorCodes('&', "&eNiveis de Exp:")))) {
                               
                                   int last = 0;
                                   String bs = line.replace("Niveis de Exp: ", "");
                                   bs = ChatColor.stripColor(bs);
                                   int n = Integer.parseInt(bs);
                                   last = n + 0;
                               
                                   int nivel = player.getLevel();
                                   int experience = 0;
                               
                                    experience = (int) Math.ceil(Math.pow(last, 2) + (6 * last));
                                    int requiredExperience = 2 * last + 7;
                                    double currentExp = Double.parseDouble(Float.toString(last));
                                    experience += Math.ceil(currentExp * requiredExperience);
                               
                                   player.setLevel(nivel + last);
                                    player.sendMessage(ChatColor.translateAlternateColorCodes('&',"&c&l>&4&l> &a&l+ "+experience +" EXP ( "+last+" NIVEIS )"));
                                      player.playSound(player.getLocation(), Sound.LEVEL_UP, 10, 29);
                                           }
                                        }
                                    }
                                       if(item.getAmount() > 1)
                                    item.setAmount(item.getAmount() - 1);
                                    else player.setItemInHand(null);          
                                        }
                                }
                            }
                        }
     
    #1 FenomPT, Sep 12, 2019 at 1:44 AM
    Last edited: Sep 13, 2019 at 1:13 PM
    • Funny Funny x 1
  2. what is your goal making this method?
     
  3. What's wrong? Are you getting an error? Is it not doing what you thought it should do?

    What are you trying to do?
    What's the expected result?
    What's the result you're seeing?

    Have you registered your listener?
     
  4. It's not giving any errors .. I'm trying to do it when you right click on exp bottle it gives exp levels for you .. Before it was working but now the item just disappears and nothing else
    Yes, I registered the listener
     
  5. First of all, HumanEntity#getItemInHand is deprecated in modern versions of the game.

    But more importantly, your issue is most likely with bracket formatting. This bit gets run for any item with a display name regardless of its type:
    Code (Java):
                                       if(item.getAmount() > 1)
                                    item.setAmount(item.getAmount() - 1);
                                    else player.setItemInHand(null);            
                                        }
     
    • Agree Agree x 1
  6. How can I solve? Sorry, but I'm still new at this ahah
     
  7. Just check to make sure your brackets ({ }) are aligned correctly. Your IDE most likely has a function (or even a keyboard shortcut) to automatically indent your code and if you do that, you should be able to tell that something's amiss.
     
  8. Okay, I'll do it when I get home!
     
  9. Strahan

    Benefactor

    Also I'd add that you should be checking if the item has lore and catching NumberFormatException on the parseInt. While yes, it is unlikely to happen as you are checking the display name to ensure the item is the special bottle it's still a good habit to code to anticipate problems. Also you are at the end checking if item amount > 1 to decrement or null the item in hand. Item is an object you created, not what was in hand so it will always be one so if they have a stack of these bottles, it will wipe them all out. I'd just decrement it directly on the amount of item in hand. See the code below for what I mean. It's also a little easier on the eyes to strip color before an equals check and I'd switch to using negative checks instead of positive. What I mean by that is if I take the code you posted above and switch from positive to negative checking, I'd get:

    Code (Text):
    @EventHandler
    public void toggle(PlayerInteractEvent event){
      Player player = event.getPlayer();
     
      ItemStack item = new ItemStack(Material.EXP_BOTTLE, 1);
      ItemMeta meta = player.getItemInHand().getItemMeta();
     
      if (!meta.hasDisplayName()) return;
      if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
      if (player.getInventory().getItemInHand().getType() != Material.EXP_BOTTLE) return;
      if (!meta.getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', "&6&lPote de Experiência &f(Lançe)"))) return;

      for (String line : meta.getLore()) {
        if (!line.startsWith((ChatColor.translateAlternateColorCodes('&', "&eNiveis de Exp:")))) continue;
        int last = 0;
        String bs = line.replace("Niveis de Exp: ", "");
        bs = ChatColor.stripColor(bs);
        int n = Integer.parseInt(bs);
        last = n;
     
        int nivel = player.getLevel();
        int experience = 0;
     
        experience = (int) Math.ceil(Math.pow(last, 2) + (6 * last));
        int requiredExperience = 2 * last + 7;
        double currentExp = Double.parseDouble(Float.toString(last));
        experience += Math.ceil(currentExp * requiredExperience);
     
        player.setLevel(nivel + last);
        player.sendMessage(ChatColor.translateAlternateColorCodes('&',"&c&l>&4&l> &a&l+ "+experience +" EXP ( "+last+" NIVEIS )"));
        player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 10, 29);
      }
      player.getInventory().getItemInMainHand().setAmount(player.getInventory().getItemInMainHand().getAmount()-1);
    }
    Bear in mind I did not fix other issues aside from changing the item decrement and switching to negative checks. Also I used the 1.9+ item in hand methods. I'd also cancel the event, because if you have >1 it will throw and do the level up otherwise.