Search in sources :

Example 11 with StringHolder

use of com.denizenscript.denizencore.utilities.text.StringHolder in project Denizen-For-Bukkit by DenizenScript.

the class InteractScriptContainer method getIdMapFor.

/**
 * Gets the available IDs with its trigger value in the form of a Map. The 'key' is
 * the name of the ID and the value is the value of the 'Trigger' key that is owned
 * by the ID key.
 * <p/>
 * <b>Example:</b>
 * <tt>
 * Example Interact Script: <br/>
 * Type: interact <br/>
 * Steps: <br/>
 * Current Step:
 * Click Trigger:           <--- obtained with the Trigger class <br/>
 * <br/>
 * id:                    <--- id of the specific trigger script/script options <br/>
 * Trigger: iron_sword  <--- value of the id key <br/>
 * Script: <br/>
 * - ...
 * - ... <br/>
 * <br/>
 * Script:                <--- since this is an id-less entry for the click trigger, <br/>
 * - ...                       it will be ignored and not in the Map. <br/>
 * - ... <br/>
 * </tt>
 * <p/>
 * <p>Note: This is handled internally with the parse() method in AbstractTrigger, so for
 * basic triggers, you probably don't need to even call this.</p>
 *
 * @param trigger The trigger involved
 * @param player  The Denizen Player object for the player who triggered it
 * @return A map of options in the trigger's script, excluding a plain 'script'
 */
public Map<String, String> getIdMapFor(Class<? extends AbstractTrigger> trigger, PlayerTag player) {
    // Get the trigger name
    String triggerName = Denizen.getInstance().triggerRegistry.get(trigger).getName();
    // Get the step
    String step = InteractScriptHelper.getCurrentStep(player, getName());
    // Check for entries
    String keyBase = "steps." + step + "." + triggerName + " trigger";
    if (contains(keyBase, Map.class)) {
        // Trigger exists in Player's current step, get ids.
        Map<String, String> idMap = new LinkedHashMap<>();
        // Iterate through IDs to build the idMap
        try {
            for (StringHolder id : getConfigurationSection(keyBase).getKeys(false)) {
                if (!id.str.equalsIgnoreCase("script")) {
                    idMap.put(id.str, getString(keyBase + "." + id.str + ".trigger", ""));
                }
            }
        } catch (Exception ex) {
            Debug.echoError("Warning: improperly defined " + trigger.getSimpleName() + " trigger for script '" + getName() + "' (basic formatting error?)!");
            Debug.echoError(ex);
        }
        return idMap;
    } else // No entries, so just return an empty list to avoid NPEs
    {
        return Collections.emptyMap();
    }
}
Also used : StringHolder(com.denizenscript.denizencore.utilities.text.StringHolder)

Example 12 with StringHolder

use of com.denizenscript.denizencore.utilities.text.StringHolder 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)

Example 13 with StringHolder

use of com.denizenscript.denizencore.utilities.text.StringHolder in project Denizen-For-Bukkit by DenizenScript.

the class ItemScriptContainer method getItemFrom.

public ItemTag getItemFrom(TagContext context) {
    if (isProcessing) {
        Debug.echoError("Item script contains (or chains to) a reference to itself. Cannot process.");
        return null;
    }
    if (context == null) {
        context = new BukkitTagContext(null, null, new ScriptTag(this));
    } else {
        context = new BukkitTagContext((BukkitTagContext) context);
        context.script = new ScriptTag(this);
    }
    // Try to use this script to make an item.
    ItemTag stack;
    isProcessing = true;
    try {
        if (!contains("material", String.class)) {
            Debug.echoError("Item script '" + getName() + "' does not contain a material. Script cannot function.");
            return null;
        }
        // Check validity of material
        String material = TagManager.tag(getString("material"), context);
        if (material.startsWith("m@")) {
            material = material.substring(2);
        }
        stack = ItemTag.valueOf(material, this);
        // Make sure we're working with a valid base ItemStack
        if (stack == null) {
            Debug.echoError("Item script '" + getName() + "' contains an invalid or incorrect material '" + material + "' (did you spell the material name wrong?). Script cannot function.");
            return null;
        }
        // Handle listed mechanisms
        if (contains("mechanisms", Map.class)) {
            YamlConfiguration mechs = getConfigurationSection("mechanisms");
            for (StringHolder key : mechs.getKeys(false)) {
                ObjectTag obj = CoreUtilities.objectToTagForm(mechs.get(key.low), context, true, true);
                stack.safeAdjust(new Mechanism(key.low, obj, context));
            }
        }
        // Set Display Name
        if (contains("display name", String.class)) {
            String displayName = TagManager.tag(getString("display name"), context);
            NMSHandler.getItemHelper().setDisplayName(stack, displayName);
        }
        // Set if the object is bound to the player
        if (contains("bound", String.class)) {
            Deprecations.boundWarning.warn(context);
        }
        // Set Lore
        if (contains("lore", List.class)) {
            List<String> lore = NMSHandler.getItemHelper().getLore(stack);
            if (lore == null) {
                lore = new ArrayList<>();
            }
            for (String line : getStringList("lore")) {
                line = TagManager.tag(line, context);
                lore.add(line);
            }
            CoreUtilities.fixNewLinesToListSeparation(lore);
            NMSHandler.getItemHelper().setLore(stack, lore);
        }
        // Set Durability
        if (contains("durability", String.class)) {
            short durability = Short.valueOf(getString("durability"));
            stack.setDurability(durability);
        }
        // Set Enchantments
        if (contains("enchantments", List.class)) {
            for (String enchantment : getStringList("enchantments")) {
                enchantment = TagManager.tag(enchantment, context);
                try {
                    // Build enchantment context
                    int level = 1;
                    int colon = enchantment.lastIndexOf(':');
                    if (colon == -1) {
                        Debug.echoError("Item script '" + getName() + "' has enchantment '" + enchantment + "' without a level.");
                    } else {
                        level = Integer.valueOf(enchantment.substring(colon + 1).replace(" ", ""));
                        enchantment = enchantment.substring(0, colon).replace(" ", "");
                    }
                    // Add enchantment
                    EnchantmentTag ench = EnchantmentTag.valueOf(enchantment, context);
                    if (ench == null) {
                        Debug.echoError("Item script '" + getName() + "' specifies enchantment '" + enchantment + "' which is invalid.");
                        continue;
                    }
                    if (stack.getBukkitMaterial() == Material.ENCHANTED_BOOK) {
                        EnchantmentStorageMeta meta = (EnchantmentStorageMeta) stack.getItemMeta();
                        meta.addStoredEnchant(ench.enchantment, level, true);
                        stack.setItemMeta(meta);
                    } else {
                        stack.getItemStack().addUnsafeEnchantment(ench.enchantment, level);
                        stack.resetCache();
                    }
                } catch (Exception ex) {
                    Debug.echoError("While constructing item script '" + getName() + "', encountered error while applying enchantment '" + enchantment + "':");
                    Debug.echoError(ex);
                }
            }
        }
        // Set Color
        if (contains("color", String.class)) {
            Deprecations.itemScriptColor.warn(context);
            String color = TagManager.tag(getString("color"), context);
            LeatherColorer.colorArmor(stack, color);
        }
        // Set Book
        if (contains("book", String.class)) {
            BookScriptContainer book = ScriptRegistry.getScriptContainer(TagManager.tag(getString("book"), context).replace("s@", ""));
            stack = book.writeBookTo(stack, context);
        }
        if (contains("flags", Map.class)) {
            YamlConfiguration flagSection = getConfigurationSection("flags");
            AbstractFlagTracker tracker = stack.getFlagTracker();
            for (StringHolder key : flagSection.getKeys(false)) {
                tracker.setFlag(key.str, CoreUtilities.objectToTagForm(flagSection.get(key.str), context, true, true), null);
            }
            stack.reapplyTracker(tracker);
        }
        stack.setItemScript(this);
    } catch (Exception e) {
        Debug.echoError("Woah! An exception has been called with this item script!");
        Debug.echoError(e);
        stack = null;
    } finally {
        isProcessing = false;
    }
    return stack;
}
Also used : YamlConfiguration(com.denizenscript.denizencore.utilities.YamlConfiguration) Mechanism(com.denizenscript.denizencore.objects.Mechanism) StringHolder(com.denizenscript.denizencore.utilities.text.StringHolder) ObjectTag(com.denizenscript.denizencore.objects.ObjectTag) EnchantmentStorageMeta(org.bukkit.inventory.meta.EnchantmentStorageMeta) BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) ScriptTag(com.denizenscript.denizencore.objects.core.ScriptTag) AbstractFlagTracker(com.denizenscript.denizencore.flags.AbstractFlagTracker) EnchantmentTag(com.denizenscript.denizen.objects.EnchantmentTag) ItemTag(com.denizenscript.denizen.objects.ItemTag)

Example 14 with StringHolder

use of com.denizenscript.denizencore.utilities.text.StringHolder in project Denizen-For-Bukkit by DenizenScript.

the class EntityScriptContainer method getEntityFrom.

public EntityTag getEntityFrom(PlayerTag player, NPCTag npc) {
    EntityTag entity;
    try {
        TagContext context = new BukkitTagContext(player, npc, new ScriptTag(this));
        if (contains("entity_type", String.class)) {
            String entityType = TagManager.tag((getString("entity_type", "")), context);
            entity = EntityTag.valueOf(entityType, context);
        } else {
            throw new Exception("Missing entity_type argument!");
        }
        if (contains("flags", Map.class)) {
            YamlConfiguration flagSection = getConfigurationSection("flags");
            MapTagFlagTracker tracker = new MapTagFlagTracker();
            for (StringHolder key : flagSection.getKeys(false)) {
                tracker.setFlag(key.str, CoreUtilities.objectToTagForm(flagSection.get(key.str), context, true, true), null);
            }
            entity.safeAdjust(new Mechanism("flag_map", tracker.map, context));
        }
        if (contains("mechanisms", Map.class)) {
            YamlConfiguration mechSection = getConfigurationSection("mechanisms");
            Set<StringHolder> strings = mechSection.getKeys(false);
            for (StringHolder string : strings) {
                ObjectTag obj = CoreUtilities.objectToTagForm(mechSection.get(string.low), context, true, true);
                entity.safeAdjust(new Mechanism(string.low, obj, context));
            }
        }
        boolean any = false;
        Set<StringHolder> strings = getContents().getKeys(false);
        for (StringHolder string : strings) {
            if (!nonMechanismKeys.contains(string.low)) {
                any = true;
                ObjectTag obj = CoreUtilities.objectToTagForm(getContents().get(string.low), context, true, true);
                entity.safeAdjust(new Mechanism(string.low, obj, context));
            }
        }
        if (any) {
            Deprecations.entityMechanismsFormat.warn(this);
        }
        if (entity == null || entity.isUnique()) {
            return null;
        }
        entity.setEntityScript(getName());
    } catch (Exception e) {
        Debug.echoError("Woah! An exception has been called with this entity script!");
        Debug.echoError(e);
        entity = null;
    }
    return entity;
}
Also used : BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) TagContext(com.denizenscript.denizencore.tags.TagContext) MapTagFlagTracker(com.denizenscript.denizencore.flags.MapTagFlagTracker) YamlConfiguration(com.denizenscript.denizencore.utilities.YamlConfiguration) Mechanism(com.denizenscript.denizencore.objects.Mechanism) StringHolder(com.denizenscript.denizencore.utilities.text.StringHolder) ObjectTag(com.denizenscript.denizencore.objects.ObjectTag) BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) ScriptTag(com.denizenscript.denizencore.objects.core.ScriptTag) EntityTag(com.denizenscript.denizen.objects.EntityTag)

Example 15 with StringHolder

use of com.denizenscript.denizencore.utilities.text.StringHolder in project Denizen-For-Bukkit by DenizenScript.

the class ItemScriptHelper method rebuildRecipes.

public void rebuildRecipes() {
    for (ItemScriptContainer container : item_scripts.values()) {
        try {
            if (container.contains("recipes", Map.class)) {
                YamlConfiguration section = container.getConfigurationSection("recipes");
                int id = 0;
                for (StringHolder key : section.getKeys(false)) {
                    id++;
                    YamlConfiguration subSection = section.getConfigurationSection(key.str);
                    String type = CoreUtilities.toLowerCase(subSection.getString("type"));
                    String internalId;
                    if (subSection.contains("recipe_id")) {
                        internalId = subSection.getString("recipe_id");
                        recipeIdToItemScript.put("denizen:" + internalId, container);
                    } else {
                        internalId = getIdFor(container, type + "_recipe", id);
                    }
                    String group = subSection.contains("group") ? subSection.getString("group") : "";
                    ItemStack item = container.getCleanReference().getItemStack().clone();
                    if (subSection.contains("output_quantity")) {
                        item.setAmount(Integer.parseInt(subSection.getString("output_quantity")));
                    }
                    switch(type) {
                        case "shaped":
                            registerShapedRecipe(container, item, subSection.getStringList("input"), internalId, group);
                            break;
                        case "shapeless":
                            registerShapelessRecipe(container, item, subSection.getString("input"), internalId, group);
                            break;
                        case "stonecutting":
                            registerStonecuttingRecipe(container, item, subSection.getString("input"), internalId, group);
                            break;
                        case "furnace":
                        case "blast":
                        case "smoker":
                        case "campfire":
                            float exp = 0;
                            int cookTime = 40;
                            if (subSection.contains("experience")) {
                                exp = Float.parseFloat(subSection.getString("experience"));
                            }
                            if (subSection.contains("cook_time")) {
                                cookTime = DurationTag.valueOf(subSection.getString("cook_time"), new BukkitTagContext(container)).getTicksAsInt();
                            }
                            registerFurnaceRecipe(container, item, subSection.getString("input"), exp, cookTime, type, internalId, group);
                            break;
                        case "smithing":
                            String retain = null;
                            if (subSection.contains("retain")) {
                                retain = subSection.getString("retain");
                            }
                            registerSmithingRecipe(container, item, subSection.getString("base"), subSection.getString("upgrade"), internalId, retain);
                            break;
                    }
                }
            }
            // Old script style
            if (container.contains("RECIPE", List.class)) {
                Deprecations.oldRecipeScript.warn(container);
                registerShapedRecipe(container, container.getCleanReference().getItemStack().clone(), container.getStringList("RECIPE"), getIdFor(container, "old_recipe", 0), "custom");
            }
            if (container.contains("SHAPELESS_RECIPE", String.class)) {
                Deprecations.oldRecipeScript.warn(container);
                registerShapelessRecipe(container, container.getCleanReference().getItemStack().clone(), container.getString("SHAPELESS_RECIPE"), getIdFor(container, "old_shapeless", 0), "custom");
            }
            if (container.contains("FURNACE_RECIPE", String.class)) {
                Deprecations.oldRecipeScript.warn(container);
                registerFurnaceRecipe(container, container.getCleanReference().getItemStack().clone(), container.getString("FURNACE_RECIPE"), 0, 40, "furnace", getIdFor(container, "old_furnace", 0), "custom");
            }
        } catch (Exception ex) {
            Debug.echoError("Error while rebuilding item script recipes for '" + container.getName() + "'...");
            Debug.echoError(ex);
        }
    }
}
Also used : StringHolder(com.denizenscript.denizencore.utilities.text.StringHolder) BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) YamlConfiguration(com.denizenscript.denizencore.utilities.YamlConfiguration)

Aggregations

StringHolder (com.denizenscript.denizencore.utilities.text.StringHolder)18 ObjectTag (com.denizenscript.denizencore.objects.ObjectTag)11 MapTag (com.denizenscript.denizencore.objects.core.MapTag)8 ListTag (com.denizenscript.denizencore.objects.core.ListTag)7 ElementTag (com.denizenscript.denizencore.objects.core.ElementTag)6 YamlConfiguration (com.denizenscript.denizencore.utilities.YamlConfiguration)6 ItemTag (com.denizenscript.denizen.objects.ItemTag)4 Map (java.util.Map)4 BukkitTagContext (com.denizenscript.denizen.tags.BukkitTagContext)3 ScriptTag (com.denizenscript.denizencore.objects.core.ScriptTag)3 ArrayList (java.util.ArrayList)3 UUID (java.util.UUID)3 EnchantmentTag (com.denizenscript.denizen.objects.EnchantmentTag)2 NPCTag (com.denizenscript.denizen.objects.NPCTag)2 PlayerTag (com.denizenscript.denizen.objects.PlayerTag)2 AbstractFlagTracker (com.denizenscript.denizencore.flags.AbstractFlagTracker)2 Mechanism (com.denizenscript.denizencore.objects.Mechanism)2 TimeTag (com.denizenscript.denizencore.objects.core.TimeTag)2 ScriptEntry (com.denizenscript.denizencore.scripts.ScriptEntry)2 TagContext (com.denizenscript.denizencore.tags.TagContext)2