HashMaps with InventoryEvents

Discussion in 'Plugin Development' started by colorw, Feb 4, 2024.

  1. Offline

    colorw

    Hello, I'm trying to make log system for players on the server. I wanted to store player inventory when he opened chest and after and then compare these two in order to check if he took any item from chest, problem is whenever im trying to get data from hashmap in CloseInventoryEvent it has same value as current, mean that i put player inventory in OpenInventory event and it changes to to same as playerinventory in CloseInventoryEvent. Code below.

    Code:
    
    private static Map<String, Inventory> items = new HashMap<>();
    
        @EventHandler
        public void onInventoryOpenEvent(InventoryOpenEvent e){
    
            if (!isChest(String.valueOf(e.getInventory().getType())))
                return;
    
    
            items.put(e.getPlayer().getName(), e.getPlayer().getInventory());
            items.put(e.getPlayer().getName() + ".chest", e.getInventory());
    
        }
    
        @EventHandler
        public void onInventoryCloseEvent(InventoryCloseEvent e){
    
            if (!isChest(String.valueOf(e.getInventory().getType())))
                return;
    
    
            ItemStack[] itemsAfterOpeningChest = items.get(e.getPlayer().getName()).getContents();
            ItemStack[] itemsNow = e.getPlayer().getInventory().getContents();
    
            for (int i = 0; i < itemsAfterOpeningChest.length; i++){
    
                if (itemsAfterOpeningChest[i] == null)
                    continue;
    
                System.out.println(itemsAfterOpeningChest[i]);
                System.out.println(itemsNow[i]);
            }
    
            items.remove(e.getPlayer().getName());
            items.remove(e.getPlayer().getName() + ".chest");
    
        }
     
  2. Offline

    KarimAKL

    @colorw You could store and compare the contents instead.
    Code:Java
    1. Map<String, ItemStack[]> items = new HashMap<>();
    2.  
    3. // InventoryOpenEvent
    4. Inventory inventory = ...;
    5. String key = ...;
    6. ItemStack[] value = Arrays.copyOf(inventory.getContents(), inventory.getSize());
    7. items.put(key, value);
    8.  
    9. // InventoryCloseEvent
    10. Inventory inventory = ...;
    11. String key = ...;
    12. ItemStack[] contents = items.get(key);
    13. ItemStack[] current = inventory.getContents();
    14.  
    15. if (Arrays.equals(contents, current)) {
    16. // Contents are the same
    17. } else {
    18. // Something has changed
    19. }

    This saves a copy of the current inventory contents in the map, then compares it against the up-to-date contents.
     

Share This Page