Search in sources :

Example 6 with InventoryTag

use of com.denizenscript.denizen.objects.InventoryTag in project Denizen-For-Bukkit by DenizenScript.

the class EntityInventory method adjust.

@Override
public void adjust(Mechanism mechanism) {
    // -->
    if (mechanism.matches("inventory_contents")) {
        ListTag list = ListTag.valueOf(mechanism.getValue().asString(), mechanism.context);
        InventoryTag inv = entity.getInventory();
        inv.clear();
        int i = 0;
        for (String str : list) {
            inv.setSlots(i, ItemTag.valueOf(str, mechanism.context).getItemStack());
            i++;
        }
    }
}
Also used : ListTag(com.denizenscript.denizencore.objects.core.ListTag) InventoryTag(com.denizenscript.denizen.objects.InventoryTag)

Example 7 with InventoryTag

use of com.denizenscript.denizen.objects.InventoryTag in project Denizen-For-Bukkit by DenizenScript.

the class ItemInventory method adjust.

@Override
public void adjust(Mechanism mechanism) {
    // -->
    if (mechanism.matches("inventory_contents") && mechanism.hasValue()) {
        List<ItemStack> items = new ArrayList<>();
        for (ItemTag item : mechanism.valueAsType(ListTag.class).filter(ItemTag.class, mechanism.context)) {
            items.add(item.getItemStack());
        }
        if (item.getItemMeta() instanceof BlockStateMeta) {
            BlockStateMeta bsm = ((BlockStateMeta) item.getItemMeta());
            InventoryHolder invHolder = (InventoryHolder) bsm.getBlockState();
            if (items.size() > getInventoryFor(invHolder).getSize()) {
                mechanism.echoError("Invalid inventory_contents input size; expected " + getInventoryFor(invHolder).getSize() + " or less.");
                return;
            }
            getInventoryFor(invHolder).setContents(items.toArray(new ItemStack[0]));
            bsm.setBlockState((BlockState) invHolder);
            item.setItemMeta(bsm);
        } else if (NMSHandler.getVersion().isAtLeast(NMSVersion.v1_17)) {
            BundleMeta bundle = (BundleMeta) item.getItemMeta();
            bundle.setItems(items);
            item.setItemMeta(bundle);
        }
    }
    if (mechanism.matches("inventory") && mechanism.hasValue()) {
        Deprecations.itemInventoryTag.warn(mechanism.context);
        Argument argument = new Argument("");
        argument.unsetValue();
        argument.object = mechanism.getValue();
        Map.Entry<Integer, InventoryTag> inventoryPair = Conversion.getInventory(argument, mechanism.context);
        if (inventoryPair == null || inventoryPair.getValue().getInventory() == null) {
            return;
        }
        ListTag items = InventoryContents.getFrom(inventoryPair.getValue()).getContents(false);
        ItemStack[] itemArray = new ItemStack[items.size()];
        for (int i = 0; i < itemArray.length; i++) {
            itemArray[i] = ((ItemTag) items.objectForms.get(i)).getItemStack().clone();
        }
        if (item.getItemMeta() instanceof BlockStateMeta) {
            BlockStateMeta bsm = ((BlockStateMeta) item.getItemMeta());
            InventoryHolder invHolder = (InventoryHolder) bsm.getBlockState();
            if (items.size() > getInventoryFor(invHolder).getSize()) {
                mechanism.echoError("Invalid inventory mechanism input size; expected " + getInventoryFor(invHolder).getSize() + " or less.");
                return;
            }
            getInventoryFor(invHolder).setContents(itemArray);
            bsm.setBlockState((BlockState) invHolder);
            item.setItemMeta(bsm);
        } else if (NMSHandler.getVersion().isAtLeast(NMSVersion.v1_17)) {
            BundleMeta bundle = (BundleMeta) item.getItemMeta();
            bundle.setItems(Arrays.asList(itemArray));
            item.setItemMeta(bundle);
        }
    }
}
Also used : BundleMeta(org.bukkit.inventory.meta.BundleMeta) Argument(com.denizenscript.denizencore.objects.Argument) ArrayList(java.util.ArrayList) ListTag(com.denizenscript.denizencore.objects.core.ListTag) BlockStateMeta(org.bukkit.inventory.meta.BlockStateMeta) ItemStack(org.bukkit.inventory.ItemStack) ItemTag(com.denizenscript.denizen.objects.ItemTag) InventoryHolder(org.bukkit.inventory.InventoryHolder) Map(java.util.Map) InventoryTag(com.denizenscript.denizen.objects.InventoryTag)

Example 8 with InventoryTag

use of com.denizenscript.denizen.objects.InventoryTag in project Denizen-For-Bukkit by DenizenScript.

the class TakeCommand method execute.

@Override
public void execute(ScriptEntry scriptEntry) {
    InventoryTag inventory = scriptEntry.getObjectTag("inventory");
    ElementTag quantity = scriptEntry.getElement("quantity");
    ListTag displayNameList = scriptEntry.getObjectTag("displayname");
    List<ItemTag> scriptItemList = scriptEntry.getObjectTag("scriptitem");
    ListTag slotList = scriptEntry.getObjectTag("slot");
    ListTag titleAuthor = scriptEntry.getObjectTag("cover");
    ElementTag nbtKey = scriptEntry.getElement("nbt_key");
    ElementTag matcherText = scriptEntry.getElement("matcher_text");
    ListTag flagList = scriptEntry.getObjectTag("flag_name");
    List<MaterialTag> materialList = scriptEntry.getObjectTag("material");
    Type type = (Type) scriptEntry.getObject("type");
    List<ItemTag> items = scriptEntry.getObjectTag("items");
    if (scriptEntry.dbCallShouldDebug()) {
        Debug.report(scriptEntry, getName(), db("Type", type.name()), quantity, inventory, displayNameList, db("scriptname", scriptItemList), db("Items", items), slotList, nbtKey, flagList, matcherText, db("material", materialList), titleAuthor);
    }
    switch(type) {
        case INVENTORY:
            {
                inventory.clear();
                break;
            }
        case ITEMINHAND:
            {
                Player player = Utilities.getEntryPlayer(scriptEntry).getPlayerEntity();
                int inHandAmt = player.getEquipment().getItemInMainHand().getAmount();
                int theAmount = (int) quantity.asDouble();
                ItemStack newHandItem = new ItemStack(Material.AIR);
                if (theAmount > inHandAmt) {
                    Debug.echoDebug(scriptEntry, "...player did not have enough of the item in hand, taking all...");
                    player.getEquipment().setItemInMainHand(newHandItem);
                } else {
                    // amount is just right!
                    if (theAmount == inHandAmt) {
                        player.getEquipment().setItemInMainHand(newHandItem);
                    } else {
                        // amount is less than what's in hand, need to make a new itemstack of what's left...
                        newHandItem = player.getEquipment().getItemInMainHand().clone();
                        newHandItem.setAmount(inHandAmt - theAmount);
                        player.getEquipment().setItemInMainHand(newHandItem);
                        player.updateInventory();
                    }
                }
                break;
            }
        case CURSORITEM:
            {
                Player player = Utilities.getEntryPlayer(scriptEntry).getPlayerEntity();
                int currentAmount = player.getItemOnCursor().getAmount();
                int takeAmount = (int) quantity.asDouble();
                ItemStack newItem = new ItemStack(Material.AIR);
                if (takeAmount > currentAmount) {
                    Debug.echoDebug(scriptEntry, "...player did not have enough of the item on cursor, taking all...");
                    player.setItemOnCursor(newItem);
                } else {
                    if (takeAmount == currentAmount) {
                        player.setItemOnCursor(newItem);
                    } else {
                        newItem = player.getItemOnCursor().clone();
                        newItem.setAmount(currentAmount - takeAmount);
                        player.setItemOnCursor(newItem);
                        player.updateInventory();
                    }
                }
                break;
            }
        case MONEY:
            {
                if (Depends.economy == null) {
                    Debug.echoError(scriptEntry, "No economy loaded! Have you installed Vault and a compatible economy plugin?");
                    return;
                }
                Depends.economy.withdrawPlayer(Utilities.getEntryPlayer(scriptEntry).getOfflinePlayer(), quantity.asDouble());
                break;
            }
        case XP:
            {
                Utilities.getEntryPlayer(scriptEntry).getPlayerEntity().giveExp(-quantity.asInt());
                break;
            }
        case RAWEXACT:
            {
                if (items == null) {
                    Debug.echoError(scriptEntry, "Must specify item/items!");
                    return;
                }
                for (ItemTag targetItem : items) {
                    takeByMatcher(inventory, (item) -> targetItem.matchesRawExact(new ItemTag(item)), quantity.asInt());
                }
                break;
            }
        case ITEM:
            {
                if (items == null) {
                    Debug.echoError(scriptEntry, "Must specify item/items!");
                    return;
                }
                for (ItemTag item : items) {
                    ItemStack is = item.getItemStack().clone();
                    is.setAmount(quantity.asInt());
                    if (!removeItem(inventory.getInventory(), item, item.getAmount())) {
                        Debug.echoDebug(scriptEntry, "Inventory does not contain at least " + quantity.asInt() + " of " + item.identify() + "... Taking all...");
                    }
                }
                break;
            }
        case BYDISPLAY:
            {
                if (displayNameList == null) {
                    Debug.echoError(scriptEntry, "Must specify a displayname!");
                    return;
                }
                for (String name : displayNameList) {
                    takeByMatcher(inventory, (item) -> item.hasItemMeta() && item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName().equalsIgnoreCase(name), quantity.asInt());
                }
                break;
            }
        case BYCOVER:
            {
                if (titleAuthor == null) {
                    Debug.echoError(scriptEntry, "Must specify a cover!");
                    return;
                }
                takeByMatcher(inventory, (item) -> item.hasItemMeta() && item.getItemMeta() instanceof BookMeta && equalOrNull(titleAuthor.get(0), ((BookMeta) item.getItemMeta()).getTitle()) && (titleAuthor.size() == 1 || equalOrNull(titleAuthor.get(1), ((BookMeta) item.getItemMeta()).getAuthor())), quantity.asInt());
                break;
            }
        case FLAGGED:
            {
                if (flagList == null) {
                    Debug.echoError(scriptEntry, "Must specify a flag name!");
                    return;
                }
                for (String flag : flagList) {
                    takeByMatcher(inventory, (item) -> new ItemTag(item).getFlagTracker().hasFlag(flag), quantity.asInt());
                }
                break;
            }
        case NBT:
            {
                if (nbtKey == null) {
                    Debug.echoError(scriptEntry, "Must specify an NBT key!");
                    return;
                }
                takeByMatcher(inventory, (item) -> CustomNBT.hasCustomNBT(item, nbtKey.asString(), CustomNBT.KEY_DENIZEN), quantity.asInt());
                break;
            }
        case SCRIPTNAME:
            {
                if (scriptItemList == null) {
                    Debug.echoError(scriptEntry, "Must specify a valid script name!");
                    return;
                }
                for (ItemTag scriptedItem : scriptItemList) {
                    String script = scriptedItem.getScriptName();
                    if (script == null) {
                        Debug.echoError(scriptEntry, "Item '" + scriptedItem.debuggable() + "' is not a scripted item, cannot take by scriptname.");
                        continue;
                    }
                    takeByMatcher(inventory, (item) -> script.equalsIgnoreCase(new ItemTag(item).getScriptName()), quantity.asInt());
                }
                break;
            }
        case MATERIAL:
            {
                if (materialList == null) {
                    Debug.echoError(scriptEntry, "Must specify a valid material!");
                    return;
                }
                for (MaterialTag material : materialList) {
                    takeByMatcher(inventory, (item) -> item.getType() == material.getMaterial() && !(new ItemTag(item).isItemscript()), quantity.asInt());
                }
                break;
            }
        case MATCHER:
            {
                if (matcherText == null) {
                    Debug.echoError(scriptEntry, "Must specify an item matcher!");
                    return;
                }
                takeByMatcher(inventory, (item) -> BukkitScriptEvent.tryItem(new ItemTag(item), matcherText.asString()), quantity.asInt());
                break;
            }
        case SLOT:
            {
                for (String slot : slotList) {
                    int slotId = SlotHelper.nameToIndexFor(slot, inventory.getInventory().getHolder());
                    if (slotId == -1 || slotId >= inventory.getSize()) {
                        Debug.echoError(scriptEntry, "The input '" + slot + "' is not a valid slot!");
                        return;
                    }
                    ItemStack original = inventory.getInventory().getItem(slotId);
                    if (original != null && original.getType() != Material.AIR) {
                        if (original.getAmount() > quantity.asInt()) {
                            original.setAmount(original.getAmount() - quantity.asInt());
                            inventory.setSlots(slotId, original);
                        } else {
                            inventory.setSlots(slotId, new ItemStack(Material.AIR));
                        }
                    }
                }
                break;
            }
    }
}
Also used : MaterialTag(com.denizenscript.denizen.objects.MaterialTag) Utilities(com.denizenscript.denizen.utilities.Utilities) Arrays(java.util.Arrays) BookMeta(org.bukkit.inventory.meta.BookMeta) NMSHandler(com.denizenscript.denizen.nms.NMSHandler) ItemTag(com.denizenscript.denizen.objects.ItemTag) Player(org.bukkit.entity.Player) InvalidArgumentsException(com.denizenscript.denizencore.exceptions.InvalidArgumentsException) Function(java.util.function.Function) Argument(com.denizenscript.denizencore.objects.Argument) Inventory(org.bukkit.inventory.Inventory) HashSet(java.util.HashSet) MaterialTag(com.denizenscript.denizen.objects.MaterialTag) ScriptEntry(com.denizenscript.denizencore.scripts.ScriptEntry) ElementTag(com.denizenscript.denizencore.objects.core.ElementTag) Material(org.bukkit.Material) ListTag(com.denizenscript.denizencore.objects.core.ListTag) Depends(com.denizenscript.denizen.utilities.depends.Depends) CustomNBT(com.denizenscript.denizen.utilities.nbt.CustomNBT) BukkitScriptEvent(com.denizenscript.denizen.events.BukkitScriptEvent) ItemStack(org.bukkit.inventory.ItemStack) SlotHelper(com.denizenscript.denizen.utilities.inventory.SlotHelper) List(java.util.List) Deprecations(com.denizenscript.denizencore.utilities.Deprecations) Debug(com.denizenscript.denizen.utilities.debugging.Debug) AbstractCommand(com.denizenscript.denizencore.scripts.commands.AbstractCommand) CoreUtilities(com.denizenscript.denizencore.utilities.CoreUtilities) ItemScriptHelper(com.denizenscript.denizen.scripts.containers.core.ItemScriptHelper) InventoryTag(com.denizenscript.denizen.objects.InventoryTag) Player(org.bukkit.entity.Player) ListTag(com.denizenscript.denizencore.objects.core.ListTag) ElementTag(com.denizenscript.denizencore.objects.core.ElementTag) ItemTag(com.denizenscript.denizen.objects.ItemTag) ItemStack(org.bukkit.inventory.ItemStack) InventoryTag(com.denizenscript.denizen.objects.InventoryTag) BookMeta(org.bukkit.inventory.meta.BookMeta)

Example 9 with InventoryTag

use of com.denizenscript.denizen.objects.InventoryTag in project Denizen-For-Bukkit by DenizenScript.

the class InventoryScriptContainer method getInventoryFrom.

public InventoryTag getInventoryFrom(TagContext context) {
    InventoryTag inventory;
    context = (context == null ? CoreUtilities.basicContext : context).clone();
    ScriptTag thisScript = new ScriptTag(this);
    context.script = thisScript;
    context.debug = context.debug && shouldDebug();
    try {
        InventoryType type = InventoryType.CHEST;
        if (contains("inventory", String.class)) {
            try {
                type = InventoryType.valueOf(getString("inventory").toUpperCase());
            } catch (IllegalArgumentException ex) {
                Debug.echoError(this, "Invalid inventory type specified. Assuming \"CHEST\" (" + ex.getMessage() + ")");
            }
        } else {
            Debug.echoError(this, "Inventory script '" + getName() + "' does not specify an inventory type. Assuming \"CHEST\".");
        }
        if (type == InventoryType.PLAYER) {
            Debug.echoError(this, "Inventory type 'player' is not valid for inventory scripts - defaulting to 'CHEST'.");
            type = InventoryType.CHEST;
        }
        int size = 0;
        if (contains("size", String.class)) {
            if (type != InventoryType.CHEST) {
                Debug.echoError(this, "You can only set the size of chest inventories!");
            } else {
                String sizeText = TagManager.tag(getString("size"), context);
                if (!ArgumentHelper.matchesInteger(sizeText)) {
                    Debug.echoError(this, "Invalid (not-a-number) size value.");
                } else {
                    size = Integer.parseInt(sizeText);
                }
                if (size == 0) {
                    Debug.echoError(this, "Inventory size can't be 0. Assuming default of inventory type...");
                }
                if (size % 9 != 0) {
                    size = (int) Math.ceil(size / 9.0) * 9;
                    Debug.echoError(this, "Inventory size must be a multiple of 9! Rounding up to " + size + "...");
                }
                if (size < 0) {
                    size = size * -1;
                    Debug.echoError(this, "Inventory size must be a positive number! Inverting to " + size + "...");
                }
            }
        }
        if (size == 0) {
            if (contains("slots", List.class) && type == InventoryType.CHEST) {
                size = getStringList("slots").size() * 9;
            } else {
                size = type.getDefaultSize();
            }
        }
        String title = contains("title", String.class) ? TagManager.tag(getString("title"), context) : null;
        if (type == InventoryType.CHEST) {
            inventory = new InventoryTag(size, title != null ? title : "Chest");
        } else {
            if (title == null) {
                inventory = new InventoryTag(type);
            } else {
                inventory = new InventoryTag(type, title);
            }
        }
        inventory.idType = "script";
        inventory.idHolder = thisScript;
        boolean[] filledSlots = new boolean[size];
        if (contains("slots", List.class)) {
            ItemStack[] finalItems = new ItemStack[size];
            int itemsAdded = 0;
            for (String items : getStringList("slots")) {
                items = TagManager.tag(items, context).trim();
                if (items.isEmpty()) {
                    continue;
                }
                if (!items.startsWith("[") || !items.endsWith("]")) {
                    Debug.echoError(this, "Invalid slots line: [" + items + "]... Ignoring it");
                    continue;
                }
                String[] itemsInLine = items.substring(1, items.length() - 1).split("\\[?\\]?\\s+\\[", -1);
                for (String item : itemsInLine) {
                    if (item.isEmpty()) {
                        finalItems[itemsAdded++] = new ItemStack(Material.AIR);
                        continue;
                    }
                    filledSlots[itemsAdded] = true;
                    if (contains("definitions." + item, String.class)) {
                        ItemTag def = ItemTag.valueOf(TagManager.tag(getString("definitions." + item), context), context);
                        if (def == null) {
                            Debug.echoError(this, "Invalid definition '" + item + "'... Ignoring it and assuming 'AIR'");
                            finalItems[itemsAdded] = new ItemStack(Material.AIR);
                        } else {
                            finalItems[itemsAdded] = def.getItemStack();
                        }
                    } else {
                        try {
                            ItemTag itemTag = ItemTag.valueOf(item, context);
                            if (itemTag == null) {
                                finalItems[itemsAdded] = new ItemStack(Material.AIR);
                                Debug.echoError(this, "Invalid slot item: [" + item + "]... ignoring it and assuming 'AIR'");
                            } else {
                                finalItems[itemsAdded] = itemTag.getItemStack();
                            }
                        } catch (Exception ex) {
                            Debug.echoError(this, "Invalid slot item: [" + item + "]...");
                            Debug.echoError(ex);
                        }
                    }
                    itemsAdded++;
                }
            }
            inventory.setContents(finalItems);
        }
        if (containsScriptSection("procedural items")) {
            List<ScriptEntry> entries = getEntries(context.getScriptEntryData(), "procedural items");
            if (!entries.isEmpty()) {
                InstantQueue queue = new InstantQueue("INV_SCRIPT_ITEM_PROC");
                queue.addEntries(entries);
                if (contains("definitions", Map.class)) {
                    YamlConfiguration section = getConfigurationSection("definitions");
                    for (StringHolder string : section.getKeys(false)) {
                        String definition = string.str;
                        queue.addDefinition(definition, section.getString(definition));
                    }
                }
                queue.procedural = true;
                queue.start();
                if (queue.determinations != null) {
                    ListTag list = ListTag.getListFor(queue.determinations.getObject(0), context);
                    if (list != null) {
                        int x = 0;
                        for (ItemTag item : list.filter(ItemTag.class, context, true)) {
                            while (x < filledSlots.length && filledSlots[x]) {
                                x++;
                            }
                            if (x >= filledSlots.length || filledSlots[x]) {
                                break;
                            }
                            inventory.setSlots(x, item.getItemStack());
                            filledSlots[x] = true;
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        Debug.echoError(this, "Woah! An exception has been called while building this inventory script!");
        Debug.echoError(e);
        inventory = null;
    }
    if (inventory != null) {
        InventoryTag.trackTemporaryInventory(inventory);
    }
    return inventory;
}
Also used : InventoryType(org.bukkit.event.inventory.InventoryType) ScriptEntry(com.denizenscript.denizencore.scripts.ScriptEntry) YamlConfiguration(com.denizenscript.denizencore.utilities.YamlConfiguration) ListTag(com.denizenscript.denizencore.objects.core.ListTag) StringHolder(com.denizenscript.denizencore.utilities.text.StringHolder) ScriptTag(com.denizenscript.denizencore.objects.core.ScriptTag) List(java.util.List) InstantQueue(com.denizenscript.denizencore.scripts.queues.core.InstantQueue) ItemStack(org.bukkit.inventory.ItemStack) ItemTag(com.denizenscript.denizen.objects.ItemTag) InventoryTag(com.denizenscript.denizen.objects.InventoryTag)

Aggregations

InventoryTag (com.denizenscript.denizen.objects.InventoryTag)9 ItemTag (com.denizenscript.denizen.objects.ItemTag)4 ListTag (com.denizenscript.denizencore.objects.core.ListTag)4 ItemStack (org.bukkit.inventory.ItemStack)4 EventHandler (org.bukkit.event.EventHandler)3 Argument (com.denizenscript.denizencore.objects.Argument)2 ElementTag (com.denizenscript.denizencore.objects.core.ElementTag)2 ScriptTag (com.denizenscript.denizencore.objects.core.ScriptTag)2 ScriptEntry (com.denizenscript.denizencore.scripts.ScriptEntry)2 List (java.util.List)2 Player (org.bukkit.entity.Player)2 Inventory (org.bukkit.inventory.Inventory)2 BukkitScriptEvent (com.denizenscript.denizen.events.BukkitScriptEvent)1 NMSHandler (com.denizenscript.denizen.nms.NMSHandler)1 ImprovedOfflinePlayer (com.denizenscript.denizen.nms.abstracts.ImprovedOfflinePlayer)1 MaterialTag (com.denizenscript.denizen.objects.MaterialTag)1 ItemScriptHelper (com.denizenscript.denizen.scripts.containers.core.ItemScriptHelper)1 Utilities (com.denizenscript.denizen.utilities.Utilities)1 Debug (com.denizenscript.denizen.utilities.debugging.Debug)1 Depends (com.denizenscript.denizen.utilities.depends.Depends)1