Explorar o código

Added ability to add/remove items, no check for overflow yet

jan hai 1 mes
pai
achega
0e3127ab12

+ 1 - 0
src/main/java/me/lethunderhawk/storeMore/StoreMore.java

@@ -31,6 +31,7 @@ public final class StoreMore extends JavaPlugin {
         ItemData.init(this);
         loadConfig();
         loadCommands();
+        registerListener(new StoreMoreListener());
     }
 
 

+ 31 - 5
src/main/java/me/lethunderhawk/storeMore/abstraction/item/ItemStorage.java

@@ -5,6 +5,7 @@ import me.lethunderhawk.storeMore.itemManipulation.LoreDesigner;
 import net.kyori.adventure.text.format.NamedTextColor;
 import org.bukkit.Material;
 import org.bukkit.inventory.ItemStack;
+import org.bukkit.inventory.meta.ItemMeta;
 
 public final class ItemStorage {
     private final Material baseMaterial;
@@ -16,6 +17,12 @@ public final class ItemStorage {
         this.max_capacity = max_capacity;
     }
 
+    @Deprecated
+    public ItemStorage withStorage(ItemStoragePair pair){
+        pairs[0] = pair;
+        return this;
+    }
+
     public int getCurrentUsage(){
         int cummulative = 0;
         for(ItemStoragePair pair : pairs){
@@ -26,18 +33,37 @@ public final class ItemStorage {
     }
 
 
-    public ItemStack buildItem(){
+    private ItemOptions getItemOptions() {
         ItemOptions options = new ItemOptions(baseMaterial);
-        options.setAmount(1);
-        options.setName(LoreDesigner.createSingle("<gold>" + max_capacity.getName() + " Item Cell "));
-        options.setLore(LoreDesigner.createLore("Current usage: " + getCurrentUsage() + "/" + max_capacity.getCap() + "<br>This cell currently holds the following types: <br><br>", NamedTextColor.GOLD));
+        options.setAmount(1)
+                .setName(LoreDesigner.createSingle("<gold>" + max_capacity.getName() + " Item Cell "))
+                .setLore(LoreDesigner.createLore("Current usage: " + getCurrentUsage() + "/" + max_capacity.getCap() + "<br>Currently holding: <br><br>", NamedTextColor.GOLD))
+                .setMaxStackSize(1)
+                .setItemStorage(this);
+        return options;
+    }
+
+    public ItemStack buildItem(){
+        ItemOptions options = getItemOptions();
 
         for(ItemStoragePair pair : pairs){
             options.getLore().add(
-                LoreDesigner.createSingle("- " + (pair == null ? "Empty" : pair.getMaterial().name()))
+                LoreDesigner.createSingle("- " + (pair == null ? "Empty" : pair.getMaterial().toString() + " x" + pair.getAmount()))
             );
         }
 
         return options.buildItemStack();
     }
+
+    public void writeIntoItem(ItemStack itemStack){
+        ItemOptions options = getItemOptions();
+
+        for(ItemStoragePair pair : pairs){
+            options.getLore().add(
+                    LoreDesigner.createSingle("- " + (pair == null ? "Empty" : pair.getMaterial().toString() + " x" + pair.getAmount()))
+            );
+        }
+        ItemMeta meta = options.buildItemStack().getItemMeta();
+        itemStack.setItemMeta(meta);
+    }
 }

+ 84 - 3
src/main/java/me/lethunderhawk/storeMore/command/StoreMoreCommand.java

@@ -1,19 +1,29 @@
 package me.lethunderhawk.storeMore.command;
 
 import me.lethunderhawk.storeMore.StoreMore;
-import me.lethunderhawk.storeMore.abstraction.item.CAPACITY;
 import me.lethunderhawk.storeMore.abstraction.item.ItemStorage;
-import me.lethunderhawk.storeMore.abstraction.item.ItemStoragePair;
 import me.lethunderhawk.storeMore.concrete.item.StorageRegistry;
+import me.lethunderhawk.storeMore.itemManipulation.StorageManipulator;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.format.NamedTextColor;
 import org.bukkit.Material;
 import org.bukkit.command.CommandSender;
 import org.bukkit.entity.Player;
 import org.jspecify.annotations.Nullable;
 
+import java.util.*;
+import java.util.stream.Collectors;
+
 public class StoreMoreCommand extends CustomCommand{
     public StoreMoreCommand(StoreMore module) {
         super(module);
     }
+    private static final List<String> MATERIALS =
+            Arrays.stream(Material.values())
+                    .map(Material::name)
+                    .toList();
+    private static final List<String> NUMBER_COMPLETIONS =
+            List.of("1", "2", "3");
 
     @Override
     public CommandNode getRootCommand() {
@@ -27,6 +37,78 @@ public class StoreMoreCommand extends CustomCommand{
     @Override
     public void createCommands() {
         registerSubCommand("getAll", "Gives you all items added by this plugin", this::getAll);
+        registerSubCommand("addItemToCell", "Adds Items to the cell you're holding", this::addItems).setTabCompleter(this::completeItemCommand);
+        registerSubCommand("removeItemFromCell", "Removes Items from the cell you're holding", this::removeItems).setTabCompleter(this::completeItemCommand);
+    }
+
+    private List<String> completeItemCommand(CommandSender sender, String[] args) {
+        // /command <action> <material>
+        if (args.length == 2) {
+            String partial = args[1].toLowerCase(Locale.ROOT);
+
+            return MATERIALS.stream()
+                    .filter(name -> name.toLowerCase(Locale.ROOT).startsWith(partial))
+                    .collect(Collectors.toList());
+        }
+
+        // /command <action> <material> <amount>
+        if (args.length == 3) {
+            boolean isCompleteMaterial = MATERIALS.stream()
+                    .anyMatch(name -> name.equalsIgnoreCase(args[1]));
+
+            if (!isCompleteMaterial) {
+                return Collections.emptyList();
+            }
+
+            String partial = args[2].toLowerCase(Locale.ROOT);
+
+            return NUMBER_COMPLETIONS.stream()
+                    .filter(amount -> amount.toLowerCase(Locale.ROOT).startsWith(partial))
+                    .collect(Collectors.toList());
+        }
+
+        return Collections.emptyList();
+    }
+
+    private void removeItems(CommandSender commandSender, String[] strings) {
+        if(strings.length < 2) return;
+        //commandSender.sendMessage(strings[0] + ";" +  strings[1] + ";" +  strings[2]);
+
+        try{
+            Material mat = Material.getMaterial(strings[0].toUpperCase());
+            if(mat == null) throw new IllegalArgumentException("Invalid material " + strings[0]);
+            int amount = Math.abs(Integer.parseInt(strings[1]));
+            commandSender.sendMessage(Component.text("Trying to remove " + amount + " " + mat.name() + " from item cell...", NamedTextColor.GOLD));
+            if(commandSender instanceof Player p) {
+                StorageManipulator.manipulateItemCellInMainHand(p, mat, -amount);
+            }else{
+                commandSender.sendMessage(Component.text("Must be a player in order to perform this command!", NamedTextColor.RED));
+            }
+        } catch (NumberFormatException e){
+            commandSender.sendMessage(Component.text("Invalid item amount!").color(NamedTextColor.RED));
+        } catch(IllegalArgumentException e){
+            commandSender.sendMessage(Component.text("Invalid item!").color(NamedTextColor.RED));
+        }
+    }
+
+    private void addItems(CommandSender commandSender, String[] strings) {
+        if(strings.length < 2) return;
+        //commandSender.sendMessage(strings[0] + ";" +  strings[1] + ";" +  strings[2]);
+        try{
+            Material mat = Material.getMaterial(strings[0].toUpperCase());
+            if(mat == null) throw new IllegalArgumentException("Invalid material " + strings[0]);
+            int amount = Math.abs(Integer.parseInt(strings[1]));
+            commandSender.sendMessage(Component.text("Trying to add " + amount + " " + mat.name() + " to item cell...", NamedTextColor.GOLD));
+            if(commandSender instanceof Player p) {
+                StorageManipulator.manipulateItemCellInMainHand(p, mat, amount);
+            }else{
+                commandSender.sendMessage(Component.text("Must be a player in order to perform this command!", NamedTextColor.RED));
+            }
+        } catch (NumberFormatException e){
+            commandSender.sendMessage(Component.text("Invalid item amount!").color(NamedTextColor.RED));
+        } catch(IllegalArgumentException e){
+            commandSender.sendMessage(Component.text("Invalid item!").color(NamedTextColor.RED));
+        }
     }
 
     private void getAll(CommandSender commandSender, String[] strings) {
@@ -34,7 +116,6 @@ public class StoreMoreCommand extends CustomCommand{
             for(ItemStorage storage : StorageRegistry.getRegistered()){
                 player.getInventory().addItem(storage.buildItem());
             }
-
         }
     }
 

+ 2 - 1
src/main/java/me/lethunderhawk/storeMore/concrete/item/StorageRegistry.java

@@ -2,13 +2,14 @@ package me.lethunderhawk.storeMore.concrete.item;
 
 import me.lethunderhawk.storeMore.abstraction.item.CAPACITY;
 import me.lethunderhawk.storeMore.abstraction.item.ItemStorage;
+import me.lethunderhawk.storeMore.abstraction.item.ItemStoragePair;
 import org.bukkit.Material;
 import org.bukkit.entity.Item;
 
 public final class StorageRegistry {
     public static ItemStorage[] getRegistered() {
         return new ItemStorage[]{
-                new ItemStorage(Material.STONE_BUTTON, CAPACITY.one_k),
+                new ItemStorage(Material.STONE_BUTTON, CAPACITY.one_k).withStorage(new ItemStoragePair(Material.STONE_BRICK_WALL, 10)),
                 new ItemStorage(Material.STONE_PRESSURE_PLATE, CAPACITY.four_k),
                 new ItemStorage(Material.STONE_SLAB, CAPACITY.sixteen_k),
                 new ItemStorage(Material.STONE, CAPACITY.sixtyFour_k),

+ 39 - 0
src/main/java/me/lethunderhawk/storeMore/itemManipulation/ItemData.java

@@ -3,8 +3,14 @@ package me.lethunderhawk.storeMore.itemManipulation;
 import org.bukkit.NamespacedKey;
 import org.bukkit.inventory.ItemStack;
 import org.bukkit.inventory.meta.ItemMeta;
+import org.bukkit.persistence.PersistentDataContainer;
 import org.bukkit.persistence.PersistentDataType;
 import org.bukkit.plugin.Plugin;
+import org.jspecify.annotations.Nullable;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
 
 public class ItemData {
 
@@ -18,6 +24,18 @@ public class ItemData {
         return new NamespacedKey(plugin, name);
     }
 
+    public static void remove(ItemStack item, String id) {
+        ItemMeta meta = item.getItemMeta();
+        if (meta == null) return;
+
+        meta.getPersistentDataContainer()
+                .remove(key(id));
+
+        item.setItemMeta(meta);
+
+        ItemLoreRenderer.render(item); // auto refresh
+    }
+
     public static void setInt(ItemStack item, String id, int value) {
         ItemMeta meta = item.getItemMeta();
         if (meta == null) return;
@@ -39,6 +57,27 @@ public class ItemData {
 
         return value == null ? def : value;
     }
+    @Nullable
+    public static List<StringIntPair> getIntsStartingWith(ItemStack item, String id, int def) {
+        ItemMeta meta = item.getItemMeta();
+        if (meta == null) return null;
+
+        PersistentDataContainer container = meta.getPersistentDataContainer();
+
+        Set<NamespacedKey> keys = container.getKeys();
+
+
+        List<String> keyStrings = new ArrayList<>(keys.stream().map(NamespacedKey::getKey).toList());
+        keyStrings.removeIf(key -> !key.contains(id));
+
+        List<StringIntPair> pairs = new ArrayList<>();
+
+        for(String s : keyStrings){
+            StringIntPair pair = new StringIntPair(s, container.get(key(s), PersistentDataType.INTEGER));
+            pairs.add(pair);
+        }
+        return pairs;
+    }
 
     public static void setBool(ItemStack item, String id, boolean value) {
         ItemMeta meta = item.getItemMeta();

+ 32 - 5
src/main/java/me/lethunderhawk/storeMore/itemManipulation/ItemOptions.java

@@ -1,5 +1,7 @@
 package me.lethunderhawk.storeMore.itemManipulation;
 
+import me.lethunderhawk.storeMore.abstraction.item.ItemStorage;
+import me.lethunderhawk.storeMore.abstraction.item.ItemStoragePair;
 import me.lethunderhawk.storeMore.util.UnItalic;
 import net.kyori.adventure.text.Component;
 import org.bukkit.Material;
@@ -15,7 +17,11 @@ public class ItemOptions {
     private List<Component> lore;
     private int amount = 1;
     private Material material;
-    private boolean enchantingGlint = false, storeCustomItemTag = true;
+    private boolean enchantingGlint = false, cancelPlace = true;
+    private int maxStackSize = 1;
+    private ItemStorage itemStorage;
+    public static String cancelplace = "cancelplace", itemstorage = "itemstorage";
+    public static String storagePrefix = "storage_";
 
     /**
      * Simple way to customize Items
@@ -36,23 +42,44 @@ public class ItemOptions {
         meta.lore(lore);
         meta.displayName(name);
         meta.setEnchantmentGlintOverride(enchantingGlint);
+        meta.setMaxStackSize(maxStackSize);
 
         item.setItemMeta(UnItalic.removeItalicFromMeta(meta));
 
-        if(storeCustomItemTag){
-            ItemData.setBool(item, "storemoreitem", true);
+        if(cancelPlace){
+            ItemData.setBool(item, cancelplace, true);
+        }
+        if(itemStorage != null){
+            ItemData.setBool(item, itemstorage, true);
+            for(ItemStoragePair pair : itemStorage.pairs){
+                if(pair == null) continue;
+                ItemData.setInt(item, storagePrefix + pair.getMaterial().name(), pair.getAmount());
+            }
         }
         return item;
     }
 
+
+
     // ====== Getters and Setters ======
 
+    public ItemOptions setItemStorage(ItemStorage storage){
+        this.itemStorage = storage;
+        return this;
+    }
+
+    public ItemOptions setMaxStackSize(int maxStackSize){
+        this.maxStackSize = maxStackSize;
+        return this;
+    }
+
     public ItemOptions setEnchantingGlint(boolean enchantingGlint){
         this.enchantingGlint = enchantingGlint;
         return this;
     }
-    public ItemOptions setSaveCustomTag(boolean saveCustomTag){
-        this.storeCustomItemTag = saveCustomTag;
+
+    public ItemOptions setCancelPlace(boolean cancelPlace){
+        this.cancelPlace = cancelPlace;
         return this;
     }
 

+ 36 - 0
src/main/java/me/lethunderhawk/storeMore/itemManipulation/StorageManipulator.java

@@ -0,0 +1,36 @@
+package me.lethunderhawk.storeMore.itemManipulation;
+
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.format.NamedTextColor;
+import org.bukkit.Material;
+import org.bukkit.entity.Player;
+import org.bukkit.inventory.ItemStack;
+import org.bukkit.inventory.meta.ItemMeta;
+
+public class StorageManipulator {
+    private StorageManipulator(){}
+
+    public static void manipulateItemCell(ItemStack stack, Material mat, int amount){
+        if(stack == null || stack.getType() == Material.AIR || amount == 0 || mat == null) return;
+        int newAmount = ItemData.getInt(stack, ItemOptions.storagePrefix + mat.name(), 0) + amount;
+        ItemData.setInt(stack, ItemOptions.storagePrefix + mat.name(), newAmount);
+    }
+
+    public static void manipulateItemCellInMainHand(Player p, Material mat, int amount) {
+        ItemStack item = p.getInventory().getItemInMainHand();
+        if(ItemData.hasBool(item, ItemOptions.itemstorage)){
+            manipulateItemCell(item, mat, amount);
+        }else{
+            p.sendMessage(Component.text("You need to be holding an item cell in your main hand!", NamedTextColor.RED));
+        }
+    }
+
+    public static void getStorageFrom(ItemStack item){
+
+    }
+
+    public static void writeStorageInto(ItemStack item){
+
+        ItemMeta meta = item.getItemMeta();
+    }
+}

+ 4 - 0
src/main/java/me/lethunderhawk/storeMore/itemManipulation/StringIntPair.java

@@ -0,0 +1,4 @@
+package me.lethunderhawk.storeMore.itemManipulation;
+
+public record StringIntPair(String item, int amount) {
+}

+ 14 - 2
src/main/java/me/lethunderhawk/storeMore/listener/StoreMoreListener.java

@@ -1,8 +1,20 @@
 package me.lethunderhawk.storeMore.listener;
 
+import me.lethunderhawk.storeMore.itemManipulation.ItemData;
+import org.bukkit.event.EventHandler;
 import org.bukkit.event.Listener;
+import org.bukkit.event.block.BlockPlaceEvent;
 
-public abstract class StoreMoreListener implements Listener {
-    public abstract String getIdentifier();
+public class StoreMoreListener implements Listener {
+    public String getIdentifier(){
+        return "everythingListener";
+    }
+
+    @EventHandler
+    public void handleBlockPlacing(BlockPlaceEvent e){
+        if(ItemData.hasBool(e.getItemInHand(), "cancelplace")){
+            e.setCancelled(true);
+        }
+    }
 
 }