Search in sources :

Example 1 with MemoryConfiguration

use of org.bukkit.configuration.MemoryConfiguration in project Essentials by drtshock.

the class Settings method _getCommandCosts.

private ConfigurationSection _getCommandCosts() {
    if (config.isConfigurationSection("command-costs")) {
        final ConfigurationSection section = config.getConfigurationSection("command-costs");
        final ConfigurationSection newSection = new MemoryConfiguration();
        for (String command : section.getKeys(false)) {
            if (command.charAt(0) == '/') {
                ess.getLogger().warning("Invalid command cost. '" + command + "' should not start with '/'.");
            }
            if (section.isDouble(command)) {
                newSection.set(command.toLowerCase(Locale.ENGLISH), section.getDouble(command));
            } else if (section.isInt(command)) {
                newSection.set(command.toLowerCase(Locale.ENGLISH), (double) section.getInt(command));
            } else if (section.isString(command)) {
                String costString = section.getString(command);
                try {
                    double cost = Double.parseDouble(costString.trim().replace(getCurrencySymbol(), "").replaceAll("\\W", ""));
                    newSection.set(command.toLowerCase(Locale.ENGLISH), cost);
                } catch (NumberFormatException ex) {
                    ess.getLogger().warning("Invalid command cost for: " + command + " (" + costString + ")");
                }
            } else {
                ess.getLogger().warning("Invalid command cost for: " + command);
            }
        }
        return newSection;
    }
    return null;
}
Also used : MemoryConfiguration(org.bukkit.configuration.MemoryConfiguration) ConfigurationSection(org.bukkit.configuration.ConfigurationSection)

Example 2 with MemoryConfiguration

use of org.bukkit.configuration.MemoryConfiguration in project MagicPlugin by elBukkit.

the class BaseSpell method cast.

@Override
public boolean cast(ConfigurationSection extraParameters, Location defaultLocation) {
    if (mage.isPlayer() && mage.getPlayer().getGameMode() == GameMode.SPECTATOR) {
        if (mage.getDebugLevel() > 0 && extraParameters != null) {
            mage.sendDebugMessage("Cannot cast in spectator mode.");
        }
        return false;
    }
    if (toggle != ToggleType.NONE && isActive()) {
        mage.sendDebugMessage(ChatColor.DARK_BLUE + "Deactivating " + ChatColor.GOLD + getName());
        deactivate(true, true);
        processResult(SpellResult.DEACTIVATE, parameters);
        return true;
    }
    if (mage.getDebugLevel() > 5 && extraParameters != null) {
        Collection<String> keys = extraParameters.getKeys(false);
        if (keys.size() > 0) {
            mage.sendDebugMessage(ChatColor.BLUE + "Cast " + ChatColor.GOLD + getName() + " " + ChatColor.GREEN + ConfigurationUtils.getParameters(extraParameters));
        }
    }
    this.reset();
    Location location = mage.getLocation();
    if (location != null) {
        Set<String> overrides = controller.getSpellOverrides(mage, location);
        if (overrides != null && !overrides.isEmpty()) {
            if (extraParameters == null) {
                extraParameters = new MemoryConfiguration();
            }
            for (String entry : overrides) {
                String[] pieces = StringUtils.split(entry, ' ');
                if (pieces.length < 2)
                    continue;
                String fullKey = pieces[0];
                String[] key = StringUtils.split(fullKey, '.');
                if (key.length == 0)
                    continue;
                if (key.length == 2 && !key[0].equals("default") && !key[0].equals(spellKey.getBaseKey()) && !key[0].equals(spellKey.getKey())) {
                    continue;
                }
                fullKey = key.length == 2 ? key[1] : key[0];
                ConfigurationUtils.set(extraParameters, fullKey, pieces[1]);
            }
        }
    }
    if (this.currentCast == null) {
        this.currentCast = new CastContext();
        this.currentCast.setSpell(this);
    }
    this.location = defaultLocation;
    workingParameters = new SpellParameters(this);
    ConfigurationUtils.addConfigurations(workingParameters, this.parameters);
    ConfigurationUtils.addConfigurations(workingParameters, extraParameters);
    processParameters(workingParameters);
    // Check to see if this is allowed to be cast by a command block
    if (!commandBlockAllowed) {
        CommandSender sender = mage.getCommandSender();
        if (sender != null && sender instanceof BlockCommandSender) {
            Block block = mage.getLocation().getBlock();
            if (block.getType() == Material.COMMAND) {
                block.setType(Material.AIR);
            }
            return false;
        }
    }
    // Allow other plugins to cancel this cast
    PreCastEvent preCast = new PreCastEvent(mage, this);
    Bukkit.getPluginManager().callEvent(preCast);
    if (preCast.isCancelled()) {
        processResult(SpellResult.CANCELLED, workingParameters);
        sendCastMessage(SpellResult.CANCELLED, " (no cast)");
        return false;
    }
    // Don't allow casting if the player is confused or weakened
    bypassConfusion = workingParameters.getBoolean("bypass_confusion", bypassConfusion);
    bypassWeakness = workingParameters.getBoolean("bypass_weakness", bypassWeakness);
    LivingEntity livingEntity = mage.getLivingEntity();
    if (livingEntity != null && !mage.isSuperPowered()) {
        if (!bypassConfusion && livingEntity.hasPotionEffect(PotionEffectType.CONFUSION)) {
            processResult(SpellResult.CURSED, workingParameters);
            sendCastMessage(SpellResult.CURSED, " (no cast)");
            return false;
        }
        // Don't allow casting if the player is weakened
        if (!bypassWeakness && livingEntity.hasPotionEffect(PotionEffectType.WEAKNESS)) {
            processResult(SpellResult.CURSED, workingParameters);
            sendCastMessage(SpellResult.CURSED, " (no cast)");
            return false;
        }
    }
    // Don't perform permission check until after processing parameters, in case of overrides
    if (!canCast(getLocation())) {
        processResult(SpellResult.INSUFFICIENT_PERMISSION, workingParameters);
        sendCastMessage(SpellResult.INSUFFICIENT_PERMISSION, " (no cast)");
        if (mage.getDebugLevel() > 1) {
            CommandSender messageTarget = mage.getDebugger();
            if (messageTarget == null) {
                messageTarget = mage.getCommandSender();
            }
            if (messageTarget != null) {
                mage.debugPermissions(messageTarget, this);
            }
        }
        return false;
    }
    this.preCast();
    // PVP override settings
    bypassPvpRestriction = workingParameters.getBoolean("bypass_pvp", false);
    bypassPvpRestriction = workingParameters.getBoolean("bp", bypassPvpRestriction);
    bypassPermissions = workingParameters.getBoolean("bypass_permissions", bypassPermissions);
    bypassFriendlyFire = workingParameters.getBoolean("bypass_friendly_fire", false);
    onlyFriendlyFire = workingParameters.getBoolean("only_friendly", false);
    // Check cooldowns
    cooldown = workingParameters.getInt("cooldown", cooldown);
    cooldown = workingParameters.getInt("cool", cooldown);
    mageCooldown = workingParameters.getInt("cooldown_mage", mageCooldown);
    // Color override
    color = ConfigurationUtils.getColor(workingParameters, "color", color);
    particle = workingParameters.getString("particle", null);
    double cooldownRemaining = getRemainingCooldown() / 1000.0;
    String timeDescription = "";
    if (cooldownRemaining > 0) {
        if (cooldownRemaining > 60 * 60) {
            long hours = (long) Math.ceil(cooldownRemaining / (60 * 60));
            if (hours == 1) {
                timeDescription = controller.getMessages().get("cooldown.wait_hour");
            } else {
                timeDescription = controller.getMessages().get("cooldown.wait_hours").replace("$hours", Long.toString(hours));
            }
        } else if (cooldownRemaining > 60) {
            long minutes = (long) Math.ceil(cooldownRemaining / 60);
            if (minutes == 1) {
                timeDescription = controller.getMessages().get("cooldown.wait_minute");
            } else {
                timeDescription = controller.getMessages().get("cooldown.wait_minutes").replace("$minutes", Long.toString(minutes));
            }
        } else if (cooldownRemaining >= 1) {
            long seconds = (long) Math.ceil(cooldownRemaining);
            if (seconds == 1) {
                timeDescription = controller.getMessages().get("cooldown.wait_second");
            } else {
                timeDescription = controller.getMessages().get("cooldown.wait_seconds").replace("$seconds", Long.toString(seconds));
            }
        } else {
            timeDescription = controller.getMessages().get("cooldown.wait_moment");
            if (timeDescription.contains("$seconds")) {
                timeDescription = timeDescription.replace("$seconds", SECONDS_FORMATTER.format(cooldownRemaining));
            }
        }
        castMessage(getMessage("cooldown").replace("$time", timeDescription));
        processResult(SpellResult.COOLDOWN, workingParameters);
        sendCastMessage(SpellResult.COOLDOWN, " (no cast)");
        return false;
    }
    CastingCost required = getRequiredCost();
    if (required != null) {
        String baseMessage = getMessage("insufficient_resources");
        String costDescription = required.getDescription(controller.getMessages(), mage);
        // Send loud messages when items are required.
        if (required.isItem()) {
            sendMessage(baseMessage.replace("$cost", costDescription));
        } else {
            castMessage(baseMessage.replace("$cost", costDescription));
        }
        processResult(SpellResult.INSUFFICIENT_RESOURCES, workingParameters);
        sendCastMessage(SpellResult.INSUFFICIENT_RESOURCES, " (no cast)");
        return false;
    }
    if (requiredHealth > 0) {
        LivingEntity li = mage.getLivingEntity();
        double healthPercentage = li == null ? 0 : 100 * li.getHealth() / li.getMaxHealth();
        if (healthPercentage < requiredHealth) {
            processResult(SpellResult.INSUFFICIENT_RESOURCES, workingParameters);
            sendCastMessage(SpellResult.INSUFFICIENT_RESOURCES, " (no cast)");
            return false;
        }
    }
    if (controller.isSpellProgressionEnabled()) {
        long progressLevel = getProgressLevel();
        for (Entry<String, EquationTransform> entry : progressLevelEquations.entrySet()) {
            workingParameters.set(entry.getKey(), entry.getValue().get(progressLevel));
        }
    }
    // Check for cancel-on-cast-other spells, after we have determined that this spell can really be cast.
    if (!passive) {
        for (Iterator<Batch> iterator = mage.getPendingBatches().iterator(); iterator.hasNext(); ) {
            Batch batch = iterator.next();
            if (!(batch instanceof SpellBatch))
                continue;
            SpellBatch spellBatch = (SpellBatch) batch;
            Spell spell = spellBatch.getSpell();
            if (spell.cancelOnCastOther()) {
                spell.cancel();
                batch.finish();
                iterator.remove();
            }
        }
    }
    return finalizeCast(workingParameters);
}
Also used : EquationTransform(de.slikey.effectlib.math.EquationTransform) SpellBatch(com.elmakers.mine.bukkit.api.batch.SpellBatch) SpellParameters(com.elmakers.mine.bukkit.magic.SpellParameters) MemoryConfiguration(org.bukkit.configuration.MemoryConfiguration) PreCastEvent(com.elmakers.mine.bukkit.api.event.PreCastEvent) Spell(com.elmakers.mine.bukkit.api.spell.Spell) MageSpell(com.elmakers.mine.bukkit.api.spell.MageSpell) PrerequisiteSpell(com.elmakers.mine.bukkit.api.spell.PrerequisiteSpell) LivingEntity(org.bukkit.entity.LivingEntity) CastingCost(com.elmakers.mine.bukkit.api.spell.CastingCost) CastContext(com.elmakers.mine.bukkit.action.CastContext) Batch(com.elmakers.mine.bukkit.api.batch.Batch) SpellBatch(com.elmakers.mine.bukkit.api.batch.SpellBatch) Block(org.bukkit.block.Block) CommandSender(org.bukkit.command.CommandSender) BlockCommandSender(org.bukkit.command.BlockCommandSender) Location(org.bukkit.Location) BlockCommandSender(org.bukkit.command.BlockCommandSender)

Example 3 with MemoryConfiguration

use of org.bukkit.configuration.MemoryConfiguration in project MagicPlugin by elBukkit.

the class PlayerController method onPlayerInteractAtEntity.

@EventHandler
public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) {
    Entity entity = event.getRightClicked();
    EntityData mob = controller.getMobByName(entity.getCustomName());
    if (mob == null)
        return;
    String interactSpell = mob.getInteractSpell();
    if (interactSpell == null || interactSpell.isEmpty())
        return;
    Player player = event.getPlayer();
    Mage mage = controller.getMage(player);
    event.setCancelled(true);
    ConfigurationSection config = new MemoryConfiguration();
    config.set("entity", entity.getUniqueId().toString());
    controller.cast(mage, interactSpell, config, player, player);
}
Also used : Entity(org.bukkit.entity.Entity) Player(org.bukkit.entity.Player) Mage(com.elmakers.mine.bukkit.magic.Mage) EntityData(com.elmakers.mine.bukkit.api.entity.EntityData) MemoryConfiguration(org.bukkit.configuration.MemoryConfiguration) ConfigurationSection(org.bukkit.configuration.ConfigurationSection) EventHandler(org.bukkit.event.EventHandler)

Example 4 with MemoryConfiguration

use of org.bukkit.configuration.MemoryConfiguration in project MagicPlugin by elBukkit.

the class AnimateSpell method onCast.

@Override
public SpellResult onCast(ConfigurationSection parameters) {
    if (parameters.getString("animate", null) != null) {
        return super.onCast(parameters);
    }
    final Block targetBlock = getTargetBlock();
    if (targetBlock == null) {
        return SpellResult.NO_TARGET;
    }
    if (!hasBuildPermission(targetBlock)) {
        return SpellResult.INSUFFICIENT_PERMISSION;
    }
    int seedRadius = parameters.getInt("seed_radius", 0);
    MaterialAndData targetMaterial = new MaterialAndData(targetBlock);
    List<String> materials = ConfigurationUtils.getStringList(parameters, "materials");
    if (seedRadius > 0 && materials != null && !materials.isEmpty()) {
        targetMaterial = new MaterialAndData(RandomUtils.getRandom(materials));
    } else if (parameters.contains("material")) {
        targetMaterial = ConfigurationUtils.getMaterialAndData(parameters, "material", targetMaterial);
        if (targetMaterial.isValid()) {
            addDestructible(targetMaterial);
        }
    }
    if (!mage.isSuperPowered() && seedRadius == 0) {
        MaterialSetManager materialSets = controller.getMaterialSetManager();
        MaterialSet restricted = materialSets.getMaterialSet("restricted");
        if (restricted != null && restricted.testMaterialAndData(targetMaterial)) {
            return SpellResult.FAIL;
        }
        if (parameters.contains("restricted")) {
            String customRestricted = parameters.getString("restricted");
            if (customRestricted != null && !customRestricted.equals("restricted")) {
                restricted = materialSets.fromConfigEmpty(customRestricted);
                if (restricted.testMaterialAndData(targetMaterial)) {
                    return SpellResult.FAIL;
                }
            }
        }
    }
    if (!isDestructible(targetBlock)) {
        return SpellResult.INSUFFICIENT_PERMISSION;
    }
    registerForUndo(targetBlock);
    if (seedRadius > 0) {
        for (int dx = -seedRadius; dx < seedRadius; dx++) {
            for (int dz = -seedRadius; dz < seedRadius; dz++) {
                for (int dy = -seedRadius; dy < seedRadius; dy++) {
                    Block seedBlock = targetBlock.getRelative(dx, dy, dz);
                    if (isDestructible(seedBlock)) {
                        registerForUndo(seedBlock);
                        targetMaterial.modify(seedBlock);
                    }
                }
            }
        }
    }
    // Look for randomized levels
    int level = 0;
    if (parameters.contains("level")) {
        level = parameters.getInt("level", level);
    } else if (levelWeights != null) {
        level = RandomUtils.weightedRandom(levelWeights);
    }
    boolean simCheckDestructible = parameters.getBoolean("sim_check_destructible", true);
    simCheckDestructible = parameters.getBoolean("scd", simCheckDestructible);
    final ConfigurationSection automataParameters = new MemoryConfiguration();
    automataParameters.set("target", "self");
    automataParameters.set("cooldown", 0);
    automataParameters.set("m", targetMaterial.getKey());
    automataParameters.set("cd", (simCheckDestructible ? true : false));
    automataParameters.set("level", level);
    String automataName = parameters.getString("name", "Automata");
    Messages messages = controller.getMessages();
    String automataType = parameters.getString("message_type", "evil");
    List<String> prefixes = messages.getAll("automata." + automataType + ".prefixes");
    List<String> suffixes = messages.getAll("automata." + automataType + ".suffixes");
    automataName = prefixes.get(random.nextInt(prefixes.size())) + " " + automataName + " " + suffixes.get(random.nextInt(suffixes.size()));
    if (level > 1) {
        automataName += " " + escapeLevel(messages, "automata.level", level);
    }
    String message = getMessage("cast_broadcast").replace("$name", automataName);
    if (message.length() > 0) {
        controller.sendToMages(message, targetBlock.getLocation());
    }
    automataParameters.set("animate", automataName);
    String automataId = UUID.randomUUID().toString();
    final Mage mage = controller.getAutomaton(automataId, automataName);
    mage.setLocation(targetBlock.getLocation());
    mage.setQuiet(true);
    mage.addTag(getKey());
    final Spell spell = mage.getSpell(getKey());
    Bukkit.getScheduler().runTaskLater(controller.getPlugin(), new Runnable() {

        @Override
        public void run() {
            spell.cast(automataParameters);
        }
    }, 1);
    registerForUndo();
    return SpellResult.CAST;
}
Also used : Messages(com.elmakers.mine.bukkit.api.magic.Messages) MaterialSet(com.elmakers.mine.bukkit.api.magic.MaterialSet) MemoryConfiguration(org.bukkit.configuration.MemoryConfiguration) Spell(com.elmakers.mine.bukkit.api.spell.Spell) Mage(com.elmakers.mine.bukkit.api.magic.Mage) MaterialAndData(com.elmakers.mine.bukkit.block.MaterialAndData) Block(org.bukkit.block.Block) MaterialSetManager(com.elmakers.mine.bukkit.api.magic.MaterialSetManager) ConfigurationSection(org.bukkit.configuration.ConfigurationSection)

Example 5 with MemoryConfiguration

use of org.bukkit.configuration.MemoryConfiguration in project MagicPlugin by elBukkit.

the class MagicController method loadConfigFile.

protected ConfigurationSection loadConfigFile(String fileName, boolean loadDefaults, boolean disableDefaults, boolean filesReplace, ConfigurationSection mainConfiguration) throws IOException, InvalidConfigurationException {
    String configFileName = fileName + ".yml";
    File configFile = new File(configFolder, configFileName);
    if (!configFile.exists()) {
        getLogger().info("Saving template " + configFileName + ", edit to customize configuration.");
        plugin.saveResource(configFileName, false);
    }
    boolean usingExample = exampleDefaults != null && exampleDefaults.length() > 0;
    String examplesFileName = usingExample ? "examples/" + exampleDefaults + "/" + fileName + ".yml" : null;
    String defaultsFileName = "defaults/" + fileName + ".defaults.yml";
    File savedDefaults = new File(configFolder, defaultsFileName);
    if (saveDefaultConfigs) {
        plugin.saveResource(defaultsFileName, true);
    } else if (savedDefaults.exists()) {
        getLogger().info("Deleting defaults file: " + defaultsFileName + ", these have been removed to avoid confusion");
        savedDefaults.delete();
    }
    getLogger().info("Loading " + configFile.getName());
    ConfigurationSection overrides = CompatibilityUtils.loadConfiguration(configFile);
    ConfigurationSection config = new MemoryConfiguration();
    if (loadDefaults) {
        getLogger().info(" Based on defaults " + defaultsFileName);
        ConfigurationSection defaultConfig = CompatibilityUtils.loadConfiguration(plugin.getResource(defaultsFileName));
        if (disableDefaults) {
            Set<String> keys = defaultConfig.getKeys(false);
            for (String key : keys) {
                defaultConfig.getConfigurationSection(key).set("enabled", false);
            }
            enableAll(overrides);
        }
        config = ConfigurationUtils.addConfigurations(config, defaultConfig);
    }
    if (mainConfiguration != null) {
        config = ConfigurationUtils.addConfigurations(config, mainConfiguration);
    }
    if (usingExample) {
        InputStream input = plugin.getResource(examplesFileName);
        if (input != null) {
            ConfigurationSection exampleConfig = CompatibilityUtils.loadConfiguration(input);
            if (disableDefaults) {
                enableAll(exampleConfig);
            }
            config = ConfigurationUtils.addConfigurations(config, exampleConfig);
            getLogger().info(" Using " + examplesFileName);
        }
    }
    if (addExamples != null && addExamples.size() > 0) {
        for (String example : addExamples) {
            examplesFileName = "examples/" + example + "/" + fileName + ".yml";
            InputStream input = plugin.getResource(examplesFileName);
            if (input != null) {
                ConfigurationSection exampleConfig = CompatibilityUtils.loadConfiguration(input);
                if (disableDefaults) {
                    enableAll(exampleConfig);
                }
                config = ConfigurationUtils.addConfigurations(config, exampleConfig, false);
                getLogger().info(" Added " + examplesFileName);
            }
        }
    }
    // Apply overrides after loading defaults and examples
    config = ConfigurationUtils.addConfigurations(config, overrides);
    // Apply file overrides last
    File configSubFolder = new File(configFolder, fileName);
    config = loadConfigFolder(config, configSubFolder, filesReplace, disableDefaults);
    return config;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) ZipInputStream(java.util.zip.ZipInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) MemoryConfiguration(org.bukkit.configuration.MemoryConfiguration) YamlDataFile(com.elmakers.mine.bukkit.data.YamlDataFile) File(java.io.File) ConfigurationSection(org.bukkit.configuration.ConfigurationSection)

Aggregations

MemoryConfiguration (org.bukkit.configuration.MemoryConfiguration)29 ConfigurationSection (org.bukkit.configuration.ConfigurationSection)26 Mage (com.elmakers.mine.bukkit.api.magic.Mage)5 ArrayList (java.util.ArrayList)5 Spell (com.elmakers.mine.bukkit.api.spell.Spell)4 HashMap (java.util.HashMap)4 Entity (org.bukkit.entity.Entity)4 MaterialAndData (com.elmakers.mine.bukkit.block.MaterialAndData)3 EquationTransform (de.slikey.effectlib.math.EquationTransform)3 Map (java.util.Map)3 Location (org.bukkit.Location)3 ItemStack (org.bukkit.inventory.ItemStack)3 CastingCost (com.elmakers.mine.bukkit.api.spell.CastingCost)2 MageSpell (com.elmakers.mine.bukkit.api.spell.MageSpell)2 SpellKey (com.elmakers.mine.bukkit.api.spell.SpellKey)2 File (java.io.File)2 Nullable (javax.annotation.Nullable)2 Block (org.bukkit.block.Block)2 Player (org.bukkit.entity.Player)2 ActionHandler (com.elmakers.mine.bukkit.action.ActionHandler)1