Search in sources :

Example 26 with PlayerTag

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

the class LegacySavesUpdater method updateLegacySaves.

public static void updateLegacySaves() {
    Debug.log("==== UPDATING LEGACY SAVES TO NEW FLAG ENGINE ====");
    File savesFile = new File(Denizen.getInstance().getDataFolder(), "saves.yml");
    if (!savesFile.exists()) {
        Debug.echoError("Legacy update went weird: file doesn't exist?");
        return;
    }
    YamlConfiguration saveSection;
    try {
        FileInputStream fis = new FileInputStream(savesFile);
        String saveData = ScriptHelper.convertStreamToString(fis, false);
        fis.close();
        if (saveData.trim().length() == 0) {
            Debug.log("Nothing to update.");
            savesFile.delete();
            return;
        }
        saveSection = YamlConfiguration.load(saveData);
        if (saveSection == null) {
            Debug.echoError("Something went very wrong: legacy saves file failed to load!");
            return;
        }
    } catch (Throwable ex) {
        Debug.echoError(ex);
        return;
    }
    if (!savesFile.renameTo(new File(Denizen.getInstance().getDataFolder(), "saves.yml.bak"))) {
        Debug.echoError("Legacy saves file failed to rename!");
    }
    if (saveSection.contains("Global")) {
        Debug.log("==== Update global data ====");
        YamlConfiguration globalSection = saveSection.getConfigurationSection("Global");
        if (globalSection.contains("Flags")) {
            applyFlags("Server", DenizenCore.serverFlagMap, globalSection.getConfigurationSection("Flags"));
        }
        if (globalSection.contains("Scripts")) {
            YamlConfiguration scriptsSection = globalSection.getConfigurationSection("Scripts");
            for (StringHolder script : scriptsSection.getKeys(false)) {
                YamlConfiguration scriptSection = scriptsSection.getConfigurationSection(script.str);
                if (scriptSection.contains("Cooldown Time")) {
                    long time = Long.parseLong(scriptSection.getString("Cooldown Time"));
                    TimeTag cooldown = new TimeTag(time);
                    DenizenCore.serverFlagMap.setFlag("__interact_cooldown." + script.low, cooldown, cooldown);
                }
            }
        }
    }
    if (saveSection.contains("Players")) {
        Debug.log("==== Update player data ====");
        YamlConfiguration playerSection = saveSection.getConfigurationSection("Players");
        for (StringHolder plPrefix : playerSection.getKeys(false)) {
            YamlConfiguration subSection = playerSection.getConfigurationSection(plPrefix.str);
            for (StringHolder uuidString : subSection.getKeys(false)) {
                if (uuidString.str.length() != 32) {
                    Debug.echoError("Cannot update data for player with non-ID entry listed: " + uuidString);
                    continue;
                }
                try {
                    UUID id = UUID.fromString(uuidString.str.substring(0, 8) + "-" + uuidString.str.substring(8, 12) + "-" + uuidString.str.substring(12, 16) + "-" + uuidString.str.substring(16, 20) + "-" + uuidString.str.substring(20, 32));
                    PlayerTag player = PlayerTag.valueOf(id.toString(), CoreUtilities.errorButNoDebugContext);
                    if (player == null) {
                        Debug.echoError("Cannot update data for player with id: " + uuidString);
                        continue;
                    }
                    YamlConfiguration actual = subSection.getConfigurationSection(uuidString.str);
                    AbstractFlagTracker tracker = player.getFlagTracker();
                    if (actual.contains("Flags")) {
                        applyFlags(player.identify(), tracker, actual.getConfigurationSection("Flags"));
                    }
                    if (actual.contains("Scripts")) {
                        YamlConfiguration scriptsSection = actual.getConfigurationSection("Scripts");
                        for (StringHolder script : scriptsSection.getKeys(false)) {
                            YamlConfiguration scriptSection = scriptsSection.getConfigurationSection(script.str);
                            if (scriptSection.contains("Current Step")) {
                                tracker.setFlag("__interact_step." + script, new ElementTag(scriptSection.getString("Current Step")), null);
                            }
                            if (scriptSection.contains("Cooldown Time")) {
                                long time = Long.parseLong(scriptSection.getString("Cooldown Time"));
                                TimeTag cooldown = new TimeTag(time);
                                tracker.setFlag("__interact_cooldown." + script, cooldown, cooldown);
                            }
                        }
                    }
                    player.reapplyTracker(tracker);
                } catch (Throwable ex) {
                    Debug.echoError("Error updating flags for player with ID " + uuidString.str);
                    Debug.echoError(ex);
                }
            }
        }
    }
    if (saveSection.contains("NPCs")) {
        final YamlConfiguration npcsSection = saveSection.getConfigurationSection("NPCs");
        new BukkitRunnable() {

            @Override
            public void run() {
                Debug.log("==== Late update NPC data ====");
                for (StringHolder npcId : npcsSection.getKeys(false)) {
                    YamlConfiguration actual = npcsSection.getConfigurationSection(npcId.str);
                    NPCTag npc = NPCTag.valueOf(npcId.str, CoreUtilities.errorButNoDebugContext);
                    if (npc == null) {
                        Debug.echoError("Cannot update data for NPC with id: " + npcId.str);
                        continue;
                    }
                    AbstractFlagTracker tracker = npc.getFlagTracker();
                    if (actual.contains("Flags")) {
                        applyFlags(npc.identify(), tracker, actual.getConfigurationSection("Flags"));
                    }
                    npc.reapplyTracker(tracker);
                    Debug.log("==== Done late-updating NPC data ====");
                }
            }
        }.runTaskLater(Denizen.getInstance(), 3);
    }
    Denizen.getInstance().saveSaves(true);
    Debug.log("==== Done updating legacy saves (except NPCs) ====");
}
Also used : PlayerTag(com.denizenscript.denizen.objects.PlayerTag) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) TimeTag(com.denizenscript.denizencore.objects.core.TimeTag) YamlConfiguration(com.denizenscript.denizencore.utilities.YamlConfiguration) FileInputStream(java.io.FileInputStream) StringHolder(com.denizenscript.denizencore.utilities.text.StringHolder) NPCTag(com.denizenscript.denizen.objects.NPCTag) AbstractFlagTracker(com.denizenscript.denizencore.flags.AbstractFlagTracker) ElementTag(com.denizenscript.denizencore.objects.core.ElementTag) UUID(java.util.UUID) File(java.io.File)

Example 27 with PlayerTag

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

the class SchematicCommand method execute.

@Override
public void execute(final ScriptEntry scriptEntry) {
    ElementTag angle = scriptEntry.argForPrefixAsElement("angle", null);
    ElementTag type = scriptEntry.getElement("type");
    ElementTag name = scriptEntry.requiredArgForPrefixAsElement("name");
    ElementTag filename = scriptEntry.argForPrefixAsElement("filename", null);
    boolean noair = scriptEntry.argAsBoolean("noair");
    boolean delayed = scriptEntry.argAsBoolean("delayed") || scriptEntry.shouldWaitFor();
    ElementTag maxDelayMs = scriptEntry.argForPrefixAsElement("max_delay_ms", "50");
    boolean copyEntities = scriptEntry.argAsBoolean("entities");
    boolean flags = scriptEntry.argAsBoolean("flags");
    LocationTag location = scriptEntry.getObjectTag("location");
    ElementTag mask = scriptEntry.argForPrefixAsElement("mask", null);
    List<PlayerTag> fakeTo = scriptEntry.argForPrefixList("fake_to", PlayerTag.class, true);
    DurationTag fakeDuration = scriptEntry.argForPrefix("fake_duration", DurationTag.class, true);
    CuboidTag cuboid = scriptEntry.getObjectTag("cuboid");
    if (scriptEntry.dbCallShouldDebug()) {
        Debug.report(scriptEntry, getName(), type, name, location, filename, cuboid, angle, db("noair", noair), db("delayed", delayed), maxDelayMs, db("flags", flags), db("entities", copyEntities), mask, fakeDuration, db("fake_to", fakeTo));
    }
    CuboidBlockSet set;
    Type ttype = Type.valueOf(type.asString());
    String fname = filename != null ? filename.asString() : name.asString();
    switch(ttype) {
        case CREATE:
            {
                if (schematics.containsKey(name.asString().toUpperCase())) {
                    Debug.echoError(scriptEntry, "Schematic file " + name.asString() + " is already loaded.");
                    scriptEntry.setFinished(true);
                    return;
                }
                if (cuboid == null) {
                    Debug.echoError(scriptEntry, "Missing cuboid argument!");
                    scriptEntry.setFinished(true);
                    return;
                }
                if (location == null) {
                    Debug.echoError(scriptEntry, "Missing origin location argument!");
                    scriptEntry.setFinished(true);
                    return;
                }
                try {
                    if (delayed) {
                        set = new CuboidBlockSet();
                        set.buildDelayed(cuboid, location, () -> {
                            if (copyEntities) {
                                set.buildEntities(cuboid, location);
                            }
                            schematics.put(name.asString().toUpperCase(), set);
                            scriptEntry.setFinished(true);
                        }, maxDelayMs.asLong(), flags);
                    } else {
                        scriptEntry.setFinished(true);
                        set = new CuboidBlockSet(cuboid, location, flags);
                        if (copyEntities) {
                            set.buildEntities(cuboid, location);
                        }
                        schematics.put(name.asString().toUpperCase(), set);
                    }
                } catch (Exception ex) {
                    Debug.echoError(scriptEntry, "Error creating schematic object " + name.asString() + ".");
                    Debug.echoError(scriptEntry, ex);
                    scriptEntry.setFinished(true);
                    return;
                }
                break;
            }
        case LOAD:
            {
                if (schematics.containsKey(name.asString().toUpperCase())) {
                    Debug.echoError(scriptEntry, "Schematic file " + name.asString() + " is already loaded.");
                    scriptEntry.setFinished(true);
                    return;
                }
                String directory = URLDecoder.decode(System.getProperty("user.dir"));
                File f = new File(directory + "/plugins/Denizen/schematics/" + fname + ".schem");
                if (!Utilities.canReadFile(f)) {
                    Debug.echoError("Cannot read from that file path due to security settings in Denizen/config.yml.");
                    scriptEntry.setFinished(true);
                    return;
                }
                if (!f.exists()) {
                    f = new File(directory + "/plugins/Denizen/schematics/" + fname + ".schematic");
                    if (!f.exists()) {
                        Debug.echoError("Schematic file " + fname + " does not exist. Are you sure it's in " + directory + "/plugins/Denizen/schematics/?");
                        scriptEntry.setFinished(true);
                        return;
                    }
                }
                File schemFile = f;
                Runnable loadRunnable = () -> {
                    try {
                        InputStream fs = new FileInputStream(schemFile);
                        CuboidBlockSet newSet;
                        newSet = SpongeSchematicHelper.fromSpongeStream(fs);
                        fs.close();
                        Runnable storeSchem = () -> {
                            schematics.put(name.asString().toUpperCase(), newSet);
                            scriptEntry.setFinished(true);
                        };
                        if (delayed) {
                            Bukkit.getScheduler().runTask(Denizen.getInstance(), storeSchem);
                        } else {
                            storeSchem.run();
                        }
                    } catch (Exception ex) {
                        Runnable showError = () -> {
                            Debug.echoError(scriptEntry, "Error loading schematic file " + name.asString() + ".");
                            Debug.echoError(scriptEntry, ex);
                        };
                        if (delayed) {
                            Bukkit.getScheduler().runTask(Denizen.getInstance(), showError);
                        } else {
                            showError.run();
                        }
                        scriptEntry.setFinished(true);
                        return;
                    }
                };
                if (delayed) {
                    Bukkit.getScheduler().runTaskAsynchronously(Denizen.getInstance(), loadRunnable);
                } else {
                    loadRunnable.run();
                    scriptEntry.setFinished(true);
                }
                break;
            }
        case UNLOAD:
            {
                if (!schematics.containsKey(name.asString().toUpperCase())) {
                    Debug.echoError(scriptEntry, "Schematic file " + name.asString() + " is not loaded.");
                    scriptEntry.setFinished(true);
                    return;
                }
                schematics.remove(name.asString().toUpperCase());
                scriptEntry.setFinished(true);
                break;
            }
        case ROTATE:
            {
                if (!schematics.containsKey(name.asString().toUpperCase())) {
                    Debug.echoError(scriptEntry, "Schematic file " + name.asString() + " is not loaded.");
                    scriptEntry.setFinished(true);
                    return;
                }
                if (angle == null) {
                    Debug.echoError(scriptEntry, "Missing angle argument!");
                    scriptEntry.setFinished(true);
                    return;
                }
                final CuboidBlockSet schematic = schematics.get(name.asString().toUpperCase());
                rotateSchem(schematic, angle.asInt(), delayed, () -> scriptEntry.setFinished(true));
                break;
            }
        case FLIP_X:
            {
                if (!schematics.containsKey(name.asString().toUpperCase())) {
                    Debug.echoError(scriptEntry, "Schematic file " + name.asString() + " is not loaded.");
                    scriptEntry.setFinished(true);
                    return;
                }
                schematics.get(name.asString().toUpperCase()).flipX();
                scriptEntry.setFinished(true);
                break;
            }
        case FLIP_Y:
            {
                if (!schematics.containsKey(name.asString().toUpperCase())) {
                    Debug.echoError(scriptEntry, "Schematic file " + name.asString() + " is not loaded.");
                    scriptEntry.setFinished(true);
                    return;
                }
                schematics.get(name.asString().toUpperCase()).flipY();
                scriptEntry.setFinished(true);
                break;
            }
        case FLIP_Z:
            {
                if (!schematics.containsKey(name.asString().toUpperCase())) {
                    Debug.echoError(scriptEntry, "Schematic file " + name.asString() + " is not loaded.");
                    scriptEntry.setFinished(true);
                    return;
                }
                schematics.get(name.asString().toUpperCase()).flipZ();
                scriptEntry.setFinished(true);
                break;
            }
        case PASTE:
            {
                if (!schematics.containsKey(name.asString().toUpperCase())) {
                    Debug.echoError(scriptEntry, "Schematic file " + name.asString() + " is not loaded.");
                    scriptEntry.setFinished(true);
                    return;
                }
                if (location == null) {
                    Debug.echoError(scriptEntry, "Missing location argument!");
                    scriptEntry.setFinished(true);
                    return;
                }
                try {
                    BlockSet.InputParams input = new BlockSet.InputParams();
                    input.centerLocation = location;
                    input.noAir = noair;
                    input.fakeTo = fakeTo;
                    if (fakeTo != null && copyEntities) {
                        Debug.echoError(scriptEntry, "Cannot fake paste entities currently.");
                        scriptEntry.setFinished(true);
                        return;
                    }
                    if (fakeDuration == null) {
                        fakeDuration = new DurationTag(0);
                    }
                    input.fakeDuration = fakeDuration;
                    if (mask != null) {
                        String maskText = mask.asString();
                        input.mask = new HashSet<>();
                        if (maskText.startsWith("li@")) {
                            // Back-compat: input used to be a list of materials
                            for (MaterialTag material : ListTag.valueOf(maskText, scriptEntry.getContext()).filter(MaterialTag.class, scriptEntry)) {
                                input.mask.add(material.getMaterial());
                            }
                        } else {
                            for (Material material : Material.values()) {
                                if (BukkitScriptEvent.tryMaterial(material, maskText)) {
                                    input.mask.add(material);
                                }
                            }
                        }
                    }
                    set = schematics.get(name.asString().toUpperCase());
                    Consumer<CuboidBlockSet> pasteRunnable = (schematic) -> {
                        if (delayed) {
                            schematic.setBlocksDelayed(() -> {
                                if (copyEntities) {
                                    schematic.pasteEntities(location);
                                }
                                scriptEntry.setFinished(true);
                            }, input, maxDelayMs.asLong());
                        } else {
                            schematic.setBlocks(input);
                            if (copyEntities) {
                                schematic.pasteEntities(location);
                            }
                            scriptEntry.setFinished(true);
                        }
                    };
                    if (angle != null) {
                        final CuboidBlockSet newSet = set.duplicate();
                        rotateSchem(newSet, angle.asInt(), delayed, () -> pasteRunnable.accept(newSet));
                    } else {
                        pasteRunnable.accept(set);
                    }
                } catch (Exception ex) {
                    Debug.echoError(scriptEntry, "Exception pasting schematic file " + name.asString() + ".");
                    Debug.echoError(scriptEntry, ex);
                    scriptEntry.setFinished(true);
                    return;
                }
                break;
            }
        case SAVE:
            {
                if (!schematics.containsKey(name.asString().toUpperCase())) {
                    Debug.echoError(scriptEntry, "Schematic file " + name.asString() + " is not loaded.");
                    return;
                }
                set = schematics.get(name.asString().toUpperCase());
                String directory = URLDecoder.decode(System.getProperty("user.dir"));
                String extension = ".schem";
                File f = new File(directory + "/plugins/Denizen/schematics/" + fname + extension);
                if (!Utilities.canWriteToFile(f)) {
                    Debug.echoError("Cannot write to that file path due to security settings in Denizen/config.yml.");
                    scriptEntry.setFinished(true);
                    return;
                }
                Runnable saveRunnable = () -> {
                    try {
                        f.getParentFile().mkdirs();
                        FileOutputStream fs = new FileOutputStream(f);
                        SpongeSchematicHelper.saveToSpongeStream(set, fs);
                        fs.flush();
                        fs.close();
                        Bukkit.getScheduler().runTask(Denizen.getInstance(), () -> scriptEntry.setFinished(true));
                    } catch (Exception ex) {
                        Bukkit.getScheduler().runTask(Denizen.getInstance(), () -> {
                            Debug.echoError(scriptEntry, "Error saving schematic file " + fname + ".");
                            Debug.echoError(scriptEntry, ex);
                        });
                        scriptEntry.setFinished(true);
                        return;
                    }
                };
                if (delayed) {
                    Bukkit.getScheduler().runTaskAsynchronously(Denizen.getInstance(), saveRunnable);
                } else {
                    scriptEntry.setFinished(true);
                    saveRunnable.run();
                }
                break;
            }
    }
}
Also used : MaterialTag(com.denizenscript.denizen.objects.MaterialTag) PlayerTag(com.denizenscript.denizen.objects.PlayerTag) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Material(org.bukkit.Material) DurationTag(com.denizenscript.denizencore.objects.core.DurationTag) InvalidArgumentsException(com.denizenscript.denizencore.exceptions.InvalidArgumentsException) FileInputStream(java.io.FileInputStream) LocationTag(com.denizenscript.denizen.objects.LocationTag) Consumer(java.util.function.Consumer) CuboidTag(com.denizenscript.denizen.objects.CuboidTag) TagRunnable(com.denizenscript.denizencore.tags.TagRunnable) FileOutputStream(java.io.FileOutputStream) ElementTag(com.denizenscript.denizencore.objects.core.ElementTag) File(java.io.File) HashSet(java.util.HashSet)

Example 28 with PlayerTag

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

the class WorldBorderCommand method execute.

@Override
public void execute(ScriptEntry scriptEntry) {
    WorldTag world = scriptEntry.getObjectTag("world");
    List<PlayerTag> players = (List<PlayerTag>) scriptEntry.getObject("players");
    LocationTag center = scriptEntry.getObjectTag("center");
    ElementTag size = scriptEntry.getElement("size");
    ElementTag currSize = scriptEntry.getElement("current_size");
    ElementTag damage = scriptEntry.getElement("damage");
    ElementTag damagebuffer = scriptEntry.getElement("damagebuffer");
    DurationTag duration = scriptEntry.getObjectTag("duration");
    ElementTag warningdistance = scriptEntry.getElement("warningdistance");
    DurationTag warningtime = scriptEntry.getObjectTag("warningtime");
    ElementTag reset = scriptEntry.getObjectTag("reset");
    if (scriptEntry.dbCallShouldDebug()) {
        Debug.report(scriptEntry, getName(), world, db("players", players), center, size, currSize, damage, damagebuffer, warningdistance, warningtime, duration, reset);
    }
    if (players != null) {
        if (reset.asBoolean()) {
            for (PlayerTag player : players) {
                NMSHandler.getPacketHelper().resetWorldBorder(player.getPlayerEntity());
            }
            return;
        }
        WorldBorder wb;
        for (PlayerTag player : players) {
            wb = player.getWorld().getWorldBorder();
            NMSHandler.getPacketHelper().setWorldBorder(player.getPlayerEntity(), (center != null ? center : wb.getCenter()), (size != null ? size.asDouble() : wb.getSize()), (currSize != null ? currSize.asDouble() : wb.getSize()), duration.getMillis(), (warningdistance != null ? warningdistance.asInt() : wb.getWarningDistance()), (warningtime != null ? warningtime.getSecondsAsInt() : wb.getWarningTime()));
        }
        return;
    }
    WorldBorder worldborder = world.getWorld().getWorldBorder();
    if (reset.asBoolean()) {
        worldborder.reset();
        return;
    }
    if (center != null) {
        worldborder.setCenter(center);
    }
    if (size != null) {
        if (currSize != null) {
            worldborder.setSize(currSize.asDouble());
        }
        worldborder.setSize(size.asDouble(), duration.getSecondsAsInt());
    }
    if (damage != null) {
        worldborder.setDamageAmount(damage.asDouble());
    }
    if (damagebuffer != null) {
        worldborder.setDamageBuffer(damagebuffer.asDouble());
    }
    if (warningdistance != null) {
        worldborder.setWarningDistance(warningdistance.asInt());
    }
    if (warningtime != null) {
        worldborder.setWarningTime(warningtime.getSecondsAsInt());
    }
}
Also used : LocationTag(com.denizenscript.denizen.objects.LocationTag) PlayerTag(com.denizenscript.denizen.objects.PlayerTag) WorldBorder(org.bukkit.WorldBorder) List(java.util.List) WorldTag(com.denizenscript.denizen.objects.WorldTag) ElementTag(com.denizenscript.denizencore.objects.core.ElementTag) DurationTag(com.denizenscript.denizencore.objects.core.DurationTag)

Example 29 with PlayerTag

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

the class ChatTrigger method processSingle.

public void processSingle(String message, Player player, NPCTag npc, Map<String, ObjectTag> context, InteractScriptContainer script, ChatContext returnable) {
    context = new HashMap<>(context);
    PlayerTag denizenPlayer = PlayerTag.mirrorBukkitPlayer(player);
    if (script.shouldDebug()) {
        Debug.report(script, name, ArgumentHelper.debugObj("Player", player.getName()) + ArgumentHelper.debugObj("NPC", npc.toString()) + ArgumentHelper.debugObj("Radius(Max)", npc.getLocation().distance(player.getLocation()) + "(" + npc.getTriggerTrait().getRadius(name) + ")") + ArgumentHelper.debugObj("Trigger text", message) + ArgumentHelper.debugObj("LOS", String.valueOf(player.hasLineOfSight(npc.getEntity()))) + ArgumentHelper.debugObj("Facing", String.valueOf(NMSHandler.getEntityHelper().isFacingEntity(player, npc.getEntity(), 45))));
    }
    String step = InteractScriptHelper.getCurrentStep(denizenPlayer, script.getName());
    if (!script.containsTriggerInStep(step, ChatTrigger.class)) {
        if (!Settings.chatGloballyIfNoChatTriggers()) {
            Debug.echoDebug(script, player.getName() + " says to " + npc.getNicknameTrait().getNickname() + ", " + message);
            return;
        } else {
            if (Debug.verbose) {
                Debug.log("No trigger in step, chatting globally");
            }
            return;
        }
    }
    String id = null;
    boolean matched = false;
    String replacementText = null;
    String regexId = null;
    String regexMessage = null;
    String messageLow = CoreUtilities.toLowerCase(message);
    Map<String, String> idMap = script.getIdMapFor(ChatTrigger.class, denizenPlayer);
    if (!idMap.isEmpty()) {
        for (Map.Entry<String, String> entry : idMap.entrySet()) {
            // Check if the chat trigger specified in the specified id's 'trigger:' key
            // matches the text the player has said
            // TODO: script arg?
            String triggerText = TagManager.tag(entry.getValue(), new BukkitTagContext(denizenPlayer, npc, null, false, null));
            Matcher matcher = triggerPattern.matcher(triggerText);
            while (matcher.find()) {
                // TODO: script arg?
                String keyword = TagManager.tag(matcher.group().replace("/", ""), new BukkitTagContext(denizenPlayer, npc, null, false, null));
                String[] split = keyword.split("\\\\\\+REPLACE:", 2);
                String replace = null;
                if (split.length == 2) {
                    keyword = split[0];
                    replace = split[1];
                }
                String keywordLow = CoreUtilities.toLowerCase(keyword);
                // match already (thus using alphabetical priority for triggers)
                if (regexId == null && keywordLow.startsWith("regex:")) {
                    Pattern pattern = Pattern.compile(keyword.substring(6));
                    Matcher m = pattern.matcher(message);
                    if (m.find()) {
                        // REGEX matches are left for last, so save it in case non-REGEX
                        // matches don't exist
                        regexId = entry.getKey();
                        regexMessage = triggerText.replace(matcher.group(), m.group());
                        context.put("keyword", new ElementTag(m.group()));
                        if (replace != null) {
                            regexMessage = replace;
                        }
                    }
                } else if (keyword.contains("|")) {
                    for (String subkeyword : CoreUtilities.split(keyword, '|')) {
                        if (messageLow.contains(CoreUtilities.toLowerCase(subkeyword))) {
                            id = entry.getKey();
                            replacementText = triggerText.replace(matcher.group(), subkeyword);
                            matched = true;
                            context.put("keyword", new ElementTag(subkeyword));
                            if (replace != null) {
                                replacementText = replace;
                            }
                        }
                    }
                } else if (keyword.equals("*")) {
                    id = entry.getKey();
                    replacementText = triggerText.replace("/*/", message);
                    matched = true;
                    if (replace != null) {
                        replacementText = replace;
                    }
                } else if (keywordLow.startsWith("strict:") && messageLow.equals(keywordLow.substring("strict:".length()))) {
                    id = entry.getKey();
                    replacementText = triggerText.replace(matcher.group(), keyword.substring("strict:".length()));
                    matched = true;
                    if (replace != null) {
                        replacementText = replace;
                    }
                } else if (messageLow.contains(keywordLow)) {
                    id = entry.getKey();
                    replacementText = triggerText.replace(matcher.group(), keyword);
                    matched = true;
                    if (replace != null) {
                        replacementText = replace;
                    }
                }
            }
            if (matched) {
                break;
            }
        }
    }
    if (!matched && regexId != null) {
        id = regexId;
        replacementText = regexMessage;
    }
    // If there was a match, the id of the match should have been returned.
    String showNormalChat = script.getString("STEPS." + step + ".CHAT TRIGGER." + id + ".SHOW AS NORMAL CHAT", "false");
    if (id != null) {
        String hideTriggerMessage = script.getString("STEPS." + step + ".CHAT TRIGGER." + id + ".HIDE TRIGGER MESSAGE", "false");
        if (!hideTriggerMessage.equalsIgnoreCase("true")) {
            Utilities.talkToNPC(replacementText, denizenPlayer, npc, Settings.chatToNpcOverhearingRange(), new ScriptTag(script));
        }
        parse(npc, denizenPlayer, script, id, context);
        if (Debug.verbose) {
            Debug.log("chat to NPC");
        }
        if (!showNormalChat.equalsIgnoreCase("true")) {
            returnable.triggered = true;
        }
        return;
    } else {
        if (!Settings.chatGloballyIfFailedChatTriggers()) {
            Utilities.talkToNPC(message, denizenPlayer, npc, Settings.chatToNpcOverhearingRange(), new ScriptTag(script));
            if (Debug.verbose) {
                Debug.log("Chat globally");
            }
            if (!showNormalChat.equalsIgnoreCase("true")) {
                returnable.triggered = true;
            }
            return;
        }
    // No matching chat triggers, and the config.yml says we
    // should just ignore the interaction...
    }
    if (Debug.verbose) {
        Debug.log("Finished calculating");
    }
    returnable.changed_text = message;
}
Also used : Pattern(java.util.regex.Pattern) PlayerTag(com.denizenscript.denizen.objects.PlayerTag) Matcher(java.util.regex.Matcher) BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) ScriptTag(com.denizenscript.denizencore.objects.core.ScriptTag) ElementTag(com.denizenscript.denizencore.objects.core.ElementTag)

Example 30 with PlayerTag

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

the class DamageTrigger method damageTrigger.

// <--[language]
// @name Damage Triggers
// @group NPC Interact Scripts
// @description
// Damage Triggers are triggered when when a player left clicks the NPC.
// Despite the name, these do not actually require the NPC take any damage, only that the player left clicks the NPC.
// 
// In scripts, use <context.damage> to measure how much damage was done to the NPC
// (though note that invincible NPCs don't necessarily take any damage even when this is non-zero).
// 
// These are very basic with no extraneous complexity.
// 
// -->
// <--[action]
// @Actions
// no damage trigger
// 
// @Triggers when the NPC is damaged by a player but no damage trigger fires.
// 
// @Context
// None
// 
// -->
// Technically defined in TriggerTrait, but placing here instead.
// <--[action]
// @Actions
// damage
// 
// @Triggers when the NPC is damaged by a player.
// 
// @Context
// <context.damage> returns how much damage was done.
// 
// @Determine
// "cancelled" to cancel the damage event.
// 
// -->
// <--[action]
// @Actions
// damaged
// 
// @Triggers when the NPC is damaged by an entity.
// 
// @Context
// <context.damage> returns how much damage was done.
// <context.damager> returns the entity that did the damage.
// 
// @Determine
// "cancelled" to cancel the damage event.
// 
// -->
@EventHandler
public void damageTrigger(EntityDamageByEntityEvent event) {
    Map<String, ObjectTag> context = new HashMap<>();
    context.put("damage", new ElementTag(event.getDamage()));
    if (CitizensAPI.getNPCRegistry().isNPC(event.getEntity())) {
        NPCTag npc = new NPCTag(CitizensAPI.getNPCRegistry().getNPC(event.getEntity()));
        if (npc == null) {
            return;
        }
        if (npc.getCitizen() == null) {
            return;
        }
        EntityTag damager = new EntityTag(event.getDamager());
        if (damager.isProjectile() && damager.hasShooter()) {
            damager = damager.getShooter();
        }
        context.put("damager", damager.getDenizenObject());
        ListTag determ = npc.action("damaged", null, context);
        if (determ != null && determ.containsCaseInsensitive("cancelled")) {
            event.setCancelled(true);
            return;
        }
        if (!damager.isPlayer()) {
            return;
        }
        PlayerTag dplayer = damager.getDenizenPlayer();
        if (!npc.getCitizen().hasTrait(TriggerTrait.class)) {
            return;
        }
        if (!npc.getTriggerTrait().isEnabled(name)) {
            return;
        }
        TriggerTrait.TriggerContext trigger = npc.getTriggerTrait().trigger(this, dplayer);
        if (!trigger.wasTriggered()) {
            return;
        }
        if (trigger.hasDetermination() && trigger.getDeterminations().containsCaseInsensitive("cancelled")) {
            event.setCancelled(true);
            return;
        }
        List<InteractScriptContainer> scripts = InteractScriptHelper.getInteractScripts(npc, dplayer, true, ClickTrigger.class);
        boolean any = false;
        if (scripts != null) {
            for (InteractScriptContainer script : scripts) {
                String id = null;
                Map<String, String> idMap = script.getIdMapFor(ClickTrigger.class, dplayer);
                if (!idMap.isEmpty()) {
                    for (Map.Entry<String, String> entry : idMap.entrySet()) {
                        String entry_value = TagManager.tag(entry.getValue(), new BukkitTagContext(dplayer, npc, null, false, new ScriptTag(script)));
                        if (ItemTag.valueOf(entry_value, script).comparesTo(dplayer.getPlayerEntity().getEquipment().getItemInMainHand()) >= 0) {
                            id = entry.getKey();
                        }
                    }
                }
                if (parse(npc, dplayer, script, id, context)) {
                    any = true;
                }
            }
        }
        if (!any) {
            npc.action("no damage trigger", dplayer);
        }
    }
}
Also used : TriggerTrait(com.denizenscript.denizen.npc.traits.TriggerTrait) HashMap(java.util.HashMap) PlayerTag(com.denizenscript.denizen.objects.PlayerTag) ListTag(com.denizenscript.denizencore.objects.core.ListTag) ObjectTag(com.denizenscript.denizencore.objects.ObjectTag) BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) NPCTag(com.denizenscript.denizen.objects.NPCTag) ScriptTag(com.denizenscript.denizencore.objects.core.ScriptTag) EntityTag(com.denizenscript.denizen.objects.EntityTag) InteractScriptContainer(com.denizenscript.denizen.scripts.containers.core.InteractScriptContainer) ElementTag(com.denizenscript.denizencore.objects.core.ElementTag) HashMap(java.util.HashMap) Map(java.util.Map) EventHandler(org.bukkit.event.EventHandler)

Aggregations

PlayerTag (com.denizenscript.denizen.objects.PlayerTag)81 ElementTag (com.denizenscript.denizencore.objects.core.ElementTag)41 Player (org.bukkit.entity.Player)26 List (java.util.List)23 NPCTag (com.denizenscript.denizen.objects.NPCTag)22 EntityTag (com.denizenscript.denizen.objects.EntityTag)16 DurationTag (com.denizenscript.denizencore.objects.core.DurationTag)15 ListTag (com.denizenscript.denizencore.objects.core.ListTag)15 LocationTag (com.denizenscript.denizen.objects.LocationTag)14 ItemTag (com.denizenscript.denizen.objects.ItemTag)12 InvalidArgumentsException (com.denizenscript.denizencore.exceptions.InvalidArgumentsException)11 EventHandler (org.bukkit.event.EventHandler)11 BukkitTagContext (com.denizenscript.denizen.tags.BukkitTagContext)8 ScriptTag (com.denizenscript.denizencore.objects.core.ScriptTag)8 ScriptEntry (com.denizenscript.denizencore.scripts.ScriptEntry)8 MaterialTag (com.denizenscript.denizen.objects.MaterialTag)7 BukkitScriptEntryData (com.denizenscript.denizen.utilities.implementation.BukkitScriptEntryData)7 ObjectTag (com.denizenscript.denizencore.objects.ObjectTag)7 FakeEntity (com.denizenscript.denizen.utilities.entity.FakeEntity)6 Argument (com.denizenscript.denizencore.objects.Argument)6