Managing Information

Discussion in 'Plugin Development' started by ExtremeOrphan, Sep 14, 2019.

Thread Status:
Not open for further replies.
  1. Offline

    ExtremeOrphan

    Hello, I am trying to make a plugin where there is a wanted list (this is for a city role-play server) and people can be added, while all of it works so far I am trying to find a way to associate a string which would be the charges as to why the player is wanted with each individual player on the wanted list so that when my GUI opens it will show their name and their charges in the lore.

    Right now people who are on the wanted list are stored in a HashSet and I loop through all the players online that are in the HashSet to display their heads in a GUI. What I need is a way to associate Charges (a string) with each username stored in the HashSet.

    Thank you!

    P.S. Here is all my code incase it may be relevant:

    Main.java
    Code:
    package com.jeremyrpeters.vcwantedlist;
    
    import java.util.HashSet;
    
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.RegisteredServiceProvider;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import net.milkbowl.vault.chat.Chat;
    import net.milkbowl.vault.economy.Economy;
    import net.milkbowl.vault.permission.Permission;
    
    public class Main extends JavaPlugin {
    
        FileConfiguration config = this.getConfig();
       
        public static HashSet<String> wanted_list = new HashSet<String>();
       
        public static Economy econ = null;
        public static Permission perms = null;
        public static Chat chat = null;
       
        private boolean setupChat() {
           
            RegisteredServiceProvider<Chat> chatProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.chat.Chat.class);
            if (chatProvider != null) {
               
                chat = chatProvider.getProvider();
    
            }
           
            return (chat != null);
        }
       
        @Override
        public void onEnable() {
    
            PluginManager pm = getServer().getPluginManager();
           
            pm.registerEvents(new EventListener(this), this);
           
            getCommand("wanted").setExecutor(new WantedCommand(this));
           
            saveDefaultConfig();
           
            setupChat();
           
        }
       
        @Override
        public void onDisable() {
           
            Main.wanted_list.clear();
           
        }
    }
    
    WantedCommand.java
    Code:
    package com.jeremyrpeters.vcwantedlist;
    
    import java.util.ArrayList;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.DyeColor;
    import org.bukkit.Material;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    import org.bukkit.inventory.meta.SkullMeta;
    
    import com.jeremyrpeters.vcwantedlist.Main;
    
    import net.milkbowl.vault.chat.Chat;
    
    public class WantedCommand implements CommandExecutor {
       
        Main plugin;
        
        public WantedCommand (Main instance) {
           
            plugin = instance;
       
        }
       
        @SuppressWarnings("deprecation")
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
           
            if(cmd.getName().equalsIgnoreCase("wanted")) {
               
                Player p = (Player) sender;
               
                if (args.length >= 1) {
               
                    if (args[0].equalsIgnoreCase("add")) {
                   
                        if (p.hasPermission("vcwanted.use")) {
                   
                            if (args.length == 2) {
                   
                                Player target = Bukkit.getPlayerExact(args[1]);
                       
                                if (Bukkit.getOnlinePlayers().contains(target)) {
                       
                                    if (!(Main.wanted_list.contains(target.getName()))) {
                       
                                        Main.wanted_list.add(target.getName());
                                   
                                        p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                                + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.Wanted List Added").replaceAll("%player%", target.getPlayer().getName())));
                                    }
                               
                                    else {
                                   
                                        p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                                + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.Player Already Wanted").replaceAll("%player%", target.getPlayer().getName())));
                                    }
                                }
                           
                                else {
                               
                                    p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                            + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.Cant Find Player")));
                               
                                }
                            }
                       
                            else {
                           
                                p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                        + ChatColor.RED + "Error, please specify a player! e.g., /wanted add ExtremeOrphan");
                            }
                        }
                   
                        else {
                   
                            p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                    + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.No Permission")));
                        }
                   
                    }
               
                    if (args[0].equalsIgnoreCase("list")) {
                       
                        if (p.hasPermission("vcwanted.getwanted")) {
                   
                            if (!(Main.wanted_list.isEmpty())) {
                           
                                p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                        + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.Wanted List Open")));
                         
                                Inventory wanted_list = Bukkit.createInventory(null, 54, ChatColor.DARK_GRAY + "[" + ChatColor.DARK_GREEN + ChatColor.BOLD +"Wanted List" + ChatColor.DARK_GRAY + "]");
                               
                                ItemStack filler_glass = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 15);
                                ItemMeta glassmeta = filler_glass.getItemMeta();
                               
                                glassmeta.setDisplayName(ChatColor.DARK_GRAY + " ");
                               
                                filler_glass.setItemMeta(glassmeta);
                               
                                wanted_list.setItem(0, filler_glass);
                                wanted_list.setItem(1, filler_glass);
                                wanted_list.setItem(2, filler_glass);
                                wanted_list.setItem(3, filler_glass);
                                wanted_list.setItem(4, filler_glass);
                                wanted_list.setItem(5, filler_glass);
                                wanted_list.setItem(6, filler_glass);
                                wanted_list.setItem(7, filler_glass);
                                wanted_list.setItem(8, filler_glass);
    
                                wanted_list.setItem(45, filler_glass);
                                wanted_list.setItem(46, filler_glass);
                                wanted_list.setItem(47, filler_glass);
                                wanted_list.setItem(48, filler_glass);
                                wanted_list.setItem(49, filler_glass);
                                wanted_list.setItem(50, filler_glass);
                                wanted_list.setItem(51, filler_glass);
                                wanted_list.setItem(52, filler_glass);
                                wanted_list.setItem(53, filler_glass);
                               
                                for (Player all_players : Bukkit.getOnlinePlayers()) { //We're only using this loop to populate the inventory we're creating with all the heads.
                               
                                    if (Main.wanted_list.contains(all_players.getName())) {
                                   
                                        ItemStack wanted_player = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3);
                              
                                        SkullMeta wanted_playersMeta = (SkullMeta) wanted_player.getItemMeta();
                                   
                                        wanted_playersMeta.setOwner(all_players.getName());
                               
                                        wanted_playersMeta.setDisplayName(ChatColor.DARK_GREEN + all_players.getName());
                                       
                                        String prefix = Main.chat.getPlayerPrefix(all_players);
    
                                        ArrayList<String> charges = new ArrayList<String>();
                               
                                        charges.add("");
                                        charges.add(ChatColor.GREEN + "Job: " + ChatColor.translateAlternateColorCodes('&', prefix));
                                        charges.add(ChatColor.GREEN + "Charges: " + ChatColor.RED + all_players.getHealth());
                                                           
                                        wanted_playersMeta.setLore(charges);
                               
                                        wanted_player.setItemMeta(wanted_playersMeta); //Modify the specific skull of this player's info with what we set above
                               
                                        wanted_list.addItem(wanted_player); //Put the skull in the next empty slot in the inventory, which should start empty anyways. Then, start over with the next online player
                           
                                    } //Finished, added all player heads into the inventory, now we need to open it                       
                                }
                               
                                p.openInventory(wanted_list);
    
                            }
                           
                            else {
                               
                                p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                        + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.Nobody Wanted")));
                            }
                        }
                       
                        else {
                       
                            p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                    + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.No Permission")));
                       
                        }
                    }
               
                    if (args[0].equalsIgnoreCase("remove")) {
                   
                        if (p.hasPermission("vcwanted.use")) {
    
                            if (args.length == 2) {
                       
                                Player target = Bukkit.getPlayerExact(args[1]);
                       
                                if (Bukkit.getOnlinePlayers().contains(target)) {
    
                                    if (Main.wanted_list.contains(target.getName())) {
                                   
                                        Main.wanted_list.remove(target.getName());
                       
                                        p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                                + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.Wanted List Removed").replaceAll("%player%", target.getPlayer().getName())));
                           
                                    }
                       
                                    else {
                           
                                        p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                                + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.Player Not Wanted").replaceAll("%player%", target.getPlayer().getName())));
                                    }
                                }
                           
                                else {
                               
                                    p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                            + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.Cant Find Player")));
                                }
                            }
                   
                            else {
                           
                                p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                        + ChatColor.RED + "Error, please specify a player! e.g., /wanted remove ExtremeOrphan");
                       
                            }
                        }
                   
                        else {
                   
                                p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                        + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.No Permission")));
                        }
                    }
               
                    if (args[0].equalsIgnoreCase("reload")) {
                   
                        if (p.hasPermission("vcwanted.reload")) {
                       
                            plugin.reloadConfig();
                       
                            p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                    + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.Plugin Reloaded")));
                        }
                   
                        else {
                       
                            p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                    + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.No Permission")));
    
                        }
                    }
                }
               
                if (args.length < 1) {
                   
                    p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix")) + ChatColor.RED + "Error, please specify command arguements (e.g., add, remove, list).");
    
                }
                return true;
            }
            return true;
        }
    }
    
    EventListener.java
    Code:
    package com.jeremyrpeters.vcwantedlist;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.EventPriority;
    import org.bukkit.event.Listener;
    import org.bukkit.event.entity.PlayerDeathEvent;
    import org.bukkit.event.inventory.InventoryClickEvent;
    import org.bukkit.event.player.PlayerQuitEvent;
    import org.bukkit.inventory.ItemStack;
    
    public class EventListener implements Listener {
       
        Main plugin;
        
        public EventListener (Main instance) {
           
            plugin = instance;
       
        }
       
        @EventHandler
        public void onPlayerDisconnect(PlayerQuitEvent e) {
           
            Player p = e.getPlayer();
           
            if (Main.wanted_list.contains(p.getName())) {
               
                Main.wanted_list.remove(p.getName());
               
                for(Player police : Bukkit.getServer().getOnlinePlayers()) {
                   
                    if (police.hasPermission("vcwanted.notifyleave")) {
                       
                        police.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.Wanted Player Left").replaceAll("%player%", e.getPlayer().getName())));
                    }
                }
            }
        }
       
        @EventHandler(priority = EventPriority.HIGHEST)
        public void onPlayerDeath(PlayerDeathEvent e) {
           
            Player p = e.getEntity();
           
            if (Main.wanted_list.contains(p.getName())) {
               
                Main.wanted_list.remove(p.getName());
                           
                for(Player police : Bukkit.getServer().getOnlinePlayers()) {
                   
                    if (police.hasPermission("vcwanted.notifydeath")) {
                       
                        police.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Prefix"))
                                + ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("Messages.Wanted Player Death").replaceAll("%player%", p.getName())));
                   
                    }
                }
            }
        }
       
        @EventHandler
        public void onInventoryClick(InventoryClickEvent e) {
           
            if (!ChatColor.stripColor(e.getInventory().getName()).equals("[Wanted List]"))
               
                return;
           
            Player player = (Player) e.getWhoClicked();
           
            e.setCancelled(true);
           
            ItemStack clickedItem = e.getCurrentItem();
           
            if (clickedItem == null || clickedItem.getType() == Material.AIR || !clickedItem.hasItemMeta()) {
               
                //You could just set the event cancelled (ignore them if they click on air, but keep inventory open)
                e.setCancelled(true);
               
                return;
            }
           
            if (e.getCurrentItem().getType() == Material.SKULL_ITEM) {
               
            }
        }
    }
     
  2. Online

    timtower Administrator Administrator Moderator

    @ExtremeOrphan Why not make a Wanted class that stores who is wanted, maybe a bounty and what charges there are.
     
  3. Offline

    ExtremeOrphan

    @timtower Im not sure what you mean by that.
     
  4. Online

    timtower Administrator Administrator Moderator

    @ExtremeOrphan Instead of a HashSet:
    Code:
    Class Wanted
    {
    UUID player;
    String reason;
    double bounty?
    }
     
  5. Offline

    ExtremeOrphan

    @timtower How would I go about accessing and setting these variables? Never done anything this way.
     
  6. Online

    timtower Administrator Administrator Moderator

    Depends on what methods / fields you use.
     
  7. Offline

    ExtremeOrphan

    @timtower Still don't really understand, is it possible to provide an example?

    I've done this but I still dont know how to save the info etc.

    Code:
        
    static void makeWanted(Player player, String reason) {
       
            if (!(reason.isEmpty())) {
               
                Player p = player;
                String test = reason;
               
               
            }
        }
    
     
    Last edited: Sep 15, 2019
  8. Online

    timtower Administrator Administrator Moderator

    @ExtremeOrphan You make a list for it somewhere. Then you create an instance of the class and add it to the list.
    And please stay away from static. You don't need it.
     
  9. Offline

    ExtremeOrphan

    @timtower thats what I do for my HashSet, its defined in my main class and accessed via. instance in my WantedCommand in order to add people to it. However if I added "p.getName() + charges" then I am unsure of how to find that element in the list/hashset later since I will be searching for the element use the name of the person who is wanted, not the full element, which is what is needed as .contains() uses .equals(). and I don't expect the player using the command to input their charges identically to how they're stored.
     
  10. Online

    timtower Administrator Administrator Moderator

    @ExtremeOrphan You don't put a single string in the set.
    You put a class in, that class contains the name and the charges.
     
  11. Offline

    ExtremeOrphan

    @timtower I don't understand what you mean by put the class in, and or how to make the "class" contain the name and charges.
     
  12. Online

    timtower Administrator Administrator Moderator

  13. Offline

    ExtremeOrphan

    @timtower Yes. Unless you just mean "put a class in" as in add a class to my project, which is what I've done, and if that's what you mean I just dont know how to store the information there.
     
  14. Online

    timtower Administrator Administrator Moderator

    @ExtremeOrphan What part of it don't you understand? You fill the variables, you put it somewhere safe.
     
  15. Offline

    ExtremeOrphan

    @timtower Right, I havent really had much experience using my own variables besides where I'm defining them and immediately using them. Im unsure how to go about storing them and accessing them later, from another class.

    Also, if I dont put static it gives me an error "Cannot make static reference to a non-static... field or method"

    @timtower I have attempted some form of what I think you mean however it produces a very weird string when called on in my GUI:

    [​IMG]
    Wanted.java
    Code:
    package com.jeremyrpeters.vcwantedlist;
    
    import java.util.UUID;
    
    import org.bukkit.entity.Player;
    
    public class Wanted {
    
        public static Player wanted_player;
        public static String wanted_charges;
    
        static void makeWanted(Player player, String reason) {
    
            if (!(reason.isEmpty())) {
             
                player.sendMessage("makeWanted(); successfully run!");
             
                Main.wanted_list.add(player.getName());
             
                wanted_charges = reason;
                wanted_player = player;
         
            }
        } 
    }
    
    GUI use of charges variable:
    Code:
    String prefix = Main.chat.getPlayerPrefix(all_players);
    
    ArrayList<String> charges = new ArrayList<String>();
                             
    charges.add("");
    charges.add(ChatColor.GREEN + "Job: " + prefix);
    charges.add(ChatColor.GREEN + "Charges: " + Wanted.wanted_charges);
                                                         
    wanted_playersMeta.setLore(charges);
    
    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Sep 15, 2019
  16. Offline

    CraftCreeper6

    @ExtremeOrphan
    Like @timtower said, make a WantedPlayer class. Have as many variables in there as you like, then add getters and setters for those variables. Create a constructor if you like too.

    Then, store them all in a List<WantedPlayer>. This will make it easier to search for players and the reason they are wanted etc...
     
  17. Offline

    Strahan

    I'm new to this method of data storage as well. Makes sense, and I can implement it to test fine. But I have one thing I'm not sure about. Using OPs data as an example, say you have your WantedPlayer class and it's populated with 5 people. You have your List<WantedPlayer> wanted. If I want to check if a certain player is wanted, right now I'm doing:

    Code:
    for (WantedPlayer wp : wanted) {
      if (wp.getUniqueId() != targetPlayer.getUniqueId()) continue;
      sender.sendMessage("Yep, they're wanted for " + wp.getReason());
      return true;
    }
    sender.sendMessage("They are in the clear!");
    Is there a way that doesn't involve a loop? Thanks!
     
  18. Offline

    KarimAKL

    @Strahan I think you can use the contains() method if you override the equals() method.
     
  19. Offline

    Strahan

    Thanks. I must be screwing something up... I am doing:

    Code:
    Player target = getServer().getPlayer(args[0]);
    if (target == null) { sender.sendMessage("Player not online!"); return true;
    sender.sendMessage((wanted.contains(target.getUniqueId())?"wanted":"clear")); 
    ...and in the class I have:

    Code:
    public class WantedPlayers {
        UUID player;
        String reason;
        Double bounty;
      
        public WantedPlayers(UUID u) {
            player = u;
        }
      
        @Override
        public boolean equals(Object checkValue) {
            if (!(checkValue instanceof UUID)) return false;
            return player == (UUID)checkValue;
        }
      
        public UUID getPlayer() {
            return player;
        }
      
        public void setBounty(Double b) {
            bounty = b;
        }
      
        public Double getBounty() {
            return bounty;
        }
      
        public void setReason(String r) {
            reason = r;
        }
      
        public String getReason() {
            return reason;
        }
      
    }
    Did I not override the equals properly, or am I not calling it properly? Sorry to be dense lol
     
  20. Offline

    KarimAKL

    @Strahan Compare UUID using equlas(), not ==.
     
  21. Offline

    Strahan

    Oops. I updated it to use .equals, but it still fails to match. If I add an instance of the class to my List then run my check code:

    Code:
    Player targetPlayer = getServer().getPlayer(args[0]);
    if (targetPlayer == null) { sender.sendMessage("Player not online!"); return true; }
    
    sender.sendMessage(".contains says: " + (wanted.contains(targetPlayer.getUniqueId())?"wanted":"clear"));
    for (WantedPlayers wp : wanted) {
      if (!wp.getUniqueId().equals(targetPlayer.getUniqueId())) continue;
      sender.sendMessage("loop says they're wanted");
      return true;
    }
    sender.sendMessage("loop says they are clear");
    I get:
    .contains says: clear
    loop says they're wanted
     
  22. Offline

    CraftCreeper6

    @Strahan
    You're checking if a list of WantedPlayers contains a string, this will never return true.
     
  23. Offline

    Strahan

    No, I'm checking if it contains a UUID. I thought that bit with the overriding of .equals was to make that work...?
     
  24. Offline

    CraftCreeper6

    @Strahan
    I mean this part:
    Code:
    sender.sendMessage(".contains says: " + (wanted.contains(targetPlayer.getUniqueId())?"wanted":"clear"));
     
  25. Offline

    KarimAKL

    @CraftCreeper6 getUniqueId() returns a UUID, not a String.

    @Strahan You need to make the equals check if it's a "WantedPlayers" object, and then if the player of that object has the same UUID.
     
  26. Offline

    CraftCreeper6

    @KarimAKL
    My bad on that one, in any case, "wanted" is a list of WantedPlayers, not UUIDs.
     
    KarimAKL likes this.
  27. Offline

    Strahan

    Ahhhhh OK. I switched the check to:
    Code:
    Player targetPlayer = getServer().getPlayer(args[0]);
    if (targetPlayer == null) { sender.sendMessage("Player not online!"); return true; }
    
    sender.sendMessage(".contains says: " + (wanted.contains(new WantedPlayers(targetPlayer.getUniqueId()))?"wanted":"clear"));
    ...and the WantedPlayers class .equals override to:
    Code:
    @Override
    public boolean equals(Object checkValue) {
        if (!(checkValue instanceof WantedPlayers)) return false;
        return (((WantedPlayers)checkValue).getUniqueId() == this.player);
    }
    It works, just wanted to check if that looked proper or if I was doing it in a stupid way? hehe Thanks.
     
    KarimAKL likes this.
  28. Offline

    CraftCreeper6

    Strahan likes this.
  29. Offline

    Strahan

    OK, I have a follow up question :) I saw the post about logging clicks and my first thought was rather than make several maps, one for each action as suggested, a multidimensional map like Map<UUID, Map<Action, Integer>> would be less hassle. Then I said wait, wait, wait. I just learned about storing data in a class, lets try to leverage that to do this instead of the map! Sooo, I built my class. However, since this isn't a simple case of yes/no the class has the value, it actually has to return and manage values I ran into some snags.

    One has to have some sort of collection of class objects that exists in a context outside the scope of the function. So I figured OK, like last time I'll make a List. I worked it all out and I have it working good now, but it seems terribly awkward. Like when I want to increment the click count... in the PlayerInteractEvent I need to check if the List contains an instance for the player. That's easy, using the info you guys gave about overriding equals. But it's a list.. I need to replace it, so I need to remove the existing instance. I ended up using indexOf to do it, but as I said it feels awfully awkward. Is there a better way? Or should I be using something other than a List? I thought perhaps I should use a Map<UUID, PlayerClicks> and ditch the UUID integration in the class, would that be the better way?

    This is the code I have:
    Code:
    public class Test14 extends JavaPlugin implements Listener {
        List<PlayerClicks> clickCounts = new ArrayList<PlayerClicks>();
    
        @Override
      public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
            Player p = (Player)sender;
            p.sendMessage("There have been " + getClicks(p, Action.valueOf(args[0])) + " click(s)");
            return true;
      }
    
        @EventHandler
        public void onPIE(PlayerInteractEvent e) {
            PlayerClicks newPC = new PlayerClicks(e.getPlayer().getUniqueId());
            if (!clickCounts.contains(newPC)) {
                newPC.addClick(e.getAction());
                clickCounts.add(newPC);
            } else {
                int index = clickCounts.indexOf(newPC);
                PlayerClicks clicker = clickCounts.get(index);
                clicker.addClick(e.getAction());
                clickCounts.remove(index);
                clickCounts.add(clicker);
            }
        }
    
        int getClicks(Player p, Action act) {
            int index = clickCounts.indexOf(new PlayerClicks(p.getUniqueId()));
            if (index == -1) return 0;
            PlayerClicks clicker = clickCounts.get(index);
            return clicker.getClickCount(act);  
        }
    }
    
    public class PlayerClicks {
        UUID uniqueId;
        Map<Action, Integer> clickCount = new HashMap<Action, Integer>();
    
        public PlayerClicks(UUID uniqueId) {
            this.uniqueId = uniqueId;
        }
    
        public void addClick(Action act) {
            if (clickCount.containsKey(act)) {
                clickCount.put(act, clickCount.get(act)+1);
            } else {
                clickCount.put(act, 1);
            }
        }
    
        public Integer getClickCount(Action act) {
            return (clickCount.containsKey(act)?clickCount.get(act):0);
        }
    
        public UUID getUniqueId() {
            return uniqueId;
        }
    
        @Override
        public boolean equals(Object checkValue) {
            if (!(checkValue instanceof PlayerClicks)) return false;
            return (((PlayerClicks)checkValue).getUniqueId() == this.uniqueId);
        }
    }
    It works fine, but I wasn't sure about that juggling with the index of the List in the event.

    (PS I know there are bad practices in there like casts without type checks, and I normally would never do that, but this is just a test plugin)
     
Thread Status:
Not open for further replies.

Share This Page