Can someone help me with this loop

Discussion in 'Spigot Plugin Development' started by Mhalllz, Jun 23, 2018.

  1. I want to to check if any online players have an item in their hand and enable flight if they do

    Code (Text):
    package me.MC_Hoxen.pick;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.logging.Logger;

    import org.bukkit.entity.Player;
    import org.bukkit.Material;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    import org.bukkit.plugin.java.JavaPlugin;
    import org.bukkit.ChatColor;

    public class Main extends JavaPlugin {

        Logger myPluginLogger = getLogger();

        public void onEnable() {

            this.myPluginLogger.info("MC_Hoxen's Pick Plugin has been enabled!");
            getConfig().options().copyDefaults(true);
            saveConfig();
        }

        public void onDisable() {

            this.myPluginLogger.info("MC_Hoxen's Pick Plugin has been disabled!");
            saveConfig();
        }

        ItemStack pick = new ItemStack(Material.getMaterial(getConfig().getInt(
                "Item-ID")), 1);

        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label,
                String[] args) {
            if (sender instanceof Player) {
                Player player = (Player) sender;

                // Create a new ItemStack (type: diamond)

                if (cmd.getName().equalsIgnoreCase("giveitem")) {

                    ItemMeta meta = pick.getItemMeta();
                    List<String> lores = new ArrayList<String>();
                    lores.add(ChatColor.translateAlternateColorCodes('&',
                            getConfig().getString("Lore-1")));
                    lores.add(ChatColor.translateAlternateColorCodes('&',
                            getConfig().getString("Lore-2")));
                    lores.add(ChatColor.translateAlternateColorCodes('&',
                            getConfig().getString("Lore-3")));

                    meta.setDisplayName(ChatColor.translateAlternateColorCodes('&',
                            getConfig().getString("Item-Name")));
                    meta.setLore(lores);
                    pick.setItemMeta(meta);
                    player.getInventory().addItem(pick);
                }

             
            }

            getServer().getScheduler()
                    .scheduleSyncRepeatingTask(this, new Runnable() {
                        public void run() {
                            for (Player on : getServer().getOnlinePlayers()) {

                                if (on.hasPermission("item.use")) {

                                    if (on.getInventory().getItemInHand().equals(pick)) {

                                        on.setAllowFlight(true);
                                        on.setFlying(true);
                                        on.sendMessage("Flight has been enabled");

                                    } else {

                                        on.setAllowFlight(false);
                                        on.setFlying(false);

                                    }

                                } else {

                                    return;

                                }
                            }
                        }
                    }, 50L, 50L); // Run every 2.5 seconds (50 ticks)

            // If the player (or console) uses our command correct, we can
            // return
            // true
            return true;
        }
    }
    Config:
    Code (Text):
    #Item ID list https://minecraft-ids.grahamedgecombe.com/
    Item-ID: 278
    Item-Name: '&8[&6&lGOD&8] &6Pick'
    Lore-1: '&bHolding this item gives you the ability to &afly&b!'
    Lore-2: ''
    Lore-3: ''
    Plugin.yml

    Code (Text):
    name: Pick
    version: 1.0
    main: me.MC_Hoxen.pick.Main
    author: MC_Hoxen
    description: Allows users to fly with a specific item in their hand!
    commands:
      giveitem:
        description: Give you a magic item!
        aliases: [gi]
     
  2. I'm not 100% sure on this, but you may want to try to do

    Code (Text):
    getServer().getScheduler()
                    .scheduleAsyncRepeatingTask(this, new Runnable() {}
    Where it is asynchronous.

    This is also an irrelevant topic, but for your Enabled Flight message, you may also want to check if they already have flight enabled, as to avoid being spammed the message.
     
  3. Perhaps you can listen to this?

    As for when players join with the item in their hand, use PlayerJoinEvent.
     
    • Agree Agree x 1
    • Winner Winner x 1
  4. I figured it out but it overrides essentials fly lol so im prob gnna give up
     
  5. Well, you could just softdepend on essentials, and if its installed have a check first to see if they're flying. That or you could simply check if the player has the essentials fly permission, and if so ignore your version.
     
  6. I would just like to say that the code in your Runnable is going to throw lots of NullPointerExceptions if you don't check if the player doesn't have an item in their hand. Also I'd move your ItemStack code into your command method and not make it static. Also I'd recommend not using items IDs as they have been deprecated since 1.7 as far as I know. And finally, I'd move your Runnable outside of the command because if that command is ran enough times, your server is going to lag and crash.

    Lots of these things you are doing are beginner mistakes and I'd highly suggest learning more Java before tackling the Spigot API.
     
    • Agree Agree x 1
  7. I was going to mention that but apparently I didn’t want to write more than 20 words in my reply.

    Adding onto that - item IDs are straight up being removed (hence why they’re deprecated) in the next update, 1.13, because of the limitations they had. Plus there is no way I’d like to identify an item from some random integer.

    This is what I’d say using to replace IDs - there’s quite a few material names changing in 1.13 (like SKULL_ITEM). To get it to read off a config though... no problem.

    Code (Text):
    Material material = Material.valueOf(config.getString(config-path-here).toUpperCase());
    Reason why I added toUpperCase is because some people decide to enter material names lowercase and Java is case sensitive. All material names are uppercase, so just add that and you may run into less problems (however, I would use a try/catch too in order to check if someone added a silly name like “cow”, because cow is not a material. It’s an entity).

    Sorry if I wrote too much, I woke up barely five minutes ago whereas my last reply was in the afternoon.
     
    • Like Like x 1
  8. [​IMG]

    here you just want to loop through the strings in the lore list (you don't have to make each individual configuration sections for it, just loop through a list in 1 section) it would make your life so much easier

    but what is happening? are you receiving messages? are you able to fly?
     
  9. If you’re talking about Essentials being overrided, let’s say you turned on /fly, you would be able to fly. Holding Mhalllz’s item in your hand lets you fly as well but once you stop holding it, it stops letting you fly, whether you turned on /fly in the first place or not. Although... surely the methods Essentials uses will say that’s happened, you can turn /fly on again. Unless it decides to be extremely confusing for no good reason.

    If not feel free to ignore me. :p
     
  10. FrostedSnowman

    Resource Staff

    Code (Java):
    Bukkit.getOnlinePlayers().stream()
         .filter(player -> player.getItemInHand() != null)
         .filter(player -> player.getItemInHand().equals(certainItemStack))
         .forEach(player -> {
                               player.sendMessage("Lucky you! Looks like you'll have flight enabled!");
                               player.setAllowFlight(true);
                               player.setFlying(true);
                          });
    then to translate the color codes in a list:

    Code (Java):
    stringList.stream().map(s -> ChatColor.translateAlternateColorCodes('&', s)).collect(Collectors.toList());
    sorry for the spoonfeed, but i'm about to head to bed and im feeling generous ;)
     
  11. But... the problem was with the confliction with essentials...
    (although your use of streams is incredibly efficient in this case and very easy to understand, I applaud you)
     
  12. im getting the item id number
     
  13. FrostedSnowman

    Resource Staff

    if you want to know for sure essentials is controlling the flight -initially- then add it as a dependency to your project. im sure there's a way in the api that'll let you know if certain players are flying or not
     
  14. I know that. It's just no where near recommended anymore. ¯\_(ツ)_/¯
     
  15. ID's are deprecated and support for them is getting entirely removed in 1.13. PLEASE use the Material enum and read a String from the config file.
     
    • Agree Agree x 1