Search in sources :

Example 1 with CastingCost

use of com.elmakers.mine.bukkit.api.spell.CastingCost in project MagicPlugin by elBukkit.

the class BaseSpell method addLore.

@Override
public void addLore(Messages messages, Mage mage, Wand wand, List<String> lore) {
    CostReducer reducer = wand == null ? mage : wand;
    if (reducer == null) {
        reducer = this;
    }
    if (levelDescription != null && levelDescription.length() > 0) {
        String descriptionTemplate = messages.get("spell.level_lore", "");
        if (!descriptionTemplate.isEmpty()) {
            InventoryUtils.wrapText(descriptionTemplate.replace("$level", levelDescription), lore);
        }
    }
    if (description != null && description.length() > 0) {
        String descriptionTemplate = messages.get("spell.description_lore", "");
        if (!descriptionTemplate.isEmpty()) {
            InventoryUtils.wrapText(descriptionTemplate.replace("$description", description), lore);
        }
    }
    if (usage != null && usage.length() > 0) {
        InventoryUtils.wrapText(usage, lore);
    }
    if (category != null) {
        String categoryLore = messages.get("spell.category", "");
        String categoryName = category.getName();
        if (!categoryLore.isEmpty() && !categoryName.isEmpty()) {
            lore.add(categoryLore.replace("$category", categoryName));
        }
    }
    if (quickCast && wand != null && !wand.isQuickCastDisabled() && wand.hasInventory()) {
        String quickCastText = messages.get("spell.quick_cast", "");
        if (!quickCastText.isEmpty()) {
            lore.add(quickCastText);
        }
    }
    String warmupDescription = getWarmupDescription();
    if (warmupDescription != null && !warmupDescription.isEmpty()) {
        lore.add(messages.get("warmup.description").replace("$time", warmupDescription));
    }
    String cooldownDescription = getCooldownDescription(mage, wand);
    if (cooldownDescription != null && !cooldownDescription.isEmpty()) {
        lore.add(messages.get("cooldown.description").replace("$time", cooldownDescription));
    }
    String mageCooldownDescription = getMageCooldownDescription(mage, wand);
    if (mageCooldownDescription != null && !mageCooldownDescription.isEmpty()) {
        lore.add(messages.get("cooldown.mage_description").replace("$time", mageCooldownDescription));
    }
    double range = getRange();
    if (range > 0) {
        lore.add(ChatColor.GRAY + messages.get("wand.range_description").replace("$range", RANGE_FORMATTER.format(range)));
    }
    String effectiveDuration = this.getDurationDescription(messages);
    if (effectiveDuration != null) {
        lore.add(ChatColor.GRAY + effectiveDuration);
    } else if (showUndoable()) {
        if (isUndoable()) {
            String undoableText = messages.get("spell.undoable", "");
            if (!undoableText.isEmpty()) {
                lore.add(undoableText);
            }
        } else {
            String undoableText = messages.get("spell.not_undoable", "");
            if (!undoableText.isEmpty()) {
                lore.add(undoableText);
            }
        }
    }
    if (usesBrush()) {
        String brushText = messages.get("spell.brush");
        if (!brushText.isEmpty()) {
            lore.add(ChatColor.GOLD + brushText);
        }
    }
    if (costs != null) {
        for (CastingCost cost : costs) {
            if (!cost.isEmpty(reducer)) {
                lore.add(ChatColor.YELLOW + messages.get("wand.costs_description").replace("$description", cost.getFullDescription(messages, reducer)));
            }
        }
    }
    if (activeCosts != null) {
        for (CastingCost cost : activeCosts) {
            if (!cost.isEmpty(reducer)) {
                lore.add(ChatColor.YELLOW + messages.get("wand.active_costs_description").replace("$description", cost.getFullDescription(messages, reducer)));
            }
        }
    }
    if (toggle != ToggleType.NONE) {
        String toggleText = messages.get("spell.toggle", "");
        if (!toggleText.isEmpty()) {
            lore.add(toggleText);
        }
    }
    if (earns > 0 && controller.isSPEnabled() && controller.isSPEarnEnabled()) {
        int scaledEarn = earns;
        if (mage != null) {
            scaledEarn = (int) Math.floor(mage.getSPMultiplier() * scaledEarn);
        }
        if (scaledEarn > 0) {
            String earnsText = messages.get("spell.earns").replace("$earns", Integer.toString(scaledEarn));
            if (!earnsText.isEmpty()) {
                lore.add(earnsText);
            }
        }
    }
    if (controller.isSpellProgressionEnabled() && progressDescription != null && progressDescription.length() > 0 && maxLevels > 0 && template != null) {
        InventoryUtils.wrapText(progressDescription.replace("$level", Long.toString(Math.max(0, getProgressLevel()))).replace("$max_level", Long.toString(maxLevels)), lore);
    }
}
Also used : CastingCost(com.elmakers.mine.bukkit.api.spell.CastingCost) CostReducer(com.elmakers.mine.bukkit.api.spell.CostReducer)

Example 2 with CastingCost

use of com.elmakers.mine.bukkit.api.spell.CastingCost 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 CastingCost

use of com.elmakers.mine.bukkit.api.spell.CastingCost in project MagicPlugin by elBukkit.

the class MagicController method getSpellBook.

public ItemStack getSpellBook(com.elmakers.mine.bukkit.api.spell.SpellCategory category, int count) {
    Map<String, List<SpellTemplate>> categories = new HashMap<>();
    Collection<SpellTemplate> spellVariants = spells.values();
    String categoryKey = category == null ? null : category.getKey();
    for (SpellTemplate spell : spellVariants) {
        if (spell.isHidden() || spell.getSpellKey().isVariant())
            continue;
        com.elmakers.mine.bukkit.api.spell.SpellCategory spellCategory = spell.getCategory();
        if (spellCategory == null)
            continue;
        String spellCategoryKey = spellCategory.getKey();
        if (categoryKey == null || spellCategoryKey.equalsIgnoreCase(categoryKey)) {
            List<SpellTemplate> categorySpells = categories.get(spellCategoryKey);
            if (categorySpells == null) {
                categorySpells = new ArrayList<>();
                categories.put(spellCategoryKey, categorySpells);
            }
            categorySpells.add(spell);
        }
    }
    List<String> categoryKeys = new ArrayList<>(categories.keySet());
    Collections.sort(categoryKeys);
    // Hrm? So much Copy+paste! :(
    CostReducer reducer = null;
    ItemStack bookItem = new ItemStack(Material.WRITTEN_BOOK, count);
    BookMeta book = (BookMeta) bookItem.getItemMeta();
    book.setAuthor(messages.get("books.default.author"));
    String title = null;
    if (category != null) {
        title = messages.get("books.default.title").replace("$category", category.getName());
    } else {
        title = messages.get("books.all.title");
    }
    book.setTitle(title);
    List<String> pages = new ArrayList<>();
    Set<String> paths = WandUpgradePath.getPathKeys();
    for (String key : categoryKeys) {
        category = getCategory(key);
        title = messages.get("books.default.title").replace("$category", category.getName());
        String description = "" + ChatColor.BOLD + ChatColor.BLUE + title + "\n\n";
        description += "" + ChatColor.RESET + ChatColor.DARK_BLUE + category.getDescription();
        pages.add(description);
        List<SpellTemplate> categorySpells = categories.get(key);
        Collections.sort(categorySpells);
        for (SpellTemplate spell : categorySpells) {
            List<String> lines = new ArrayList<>();
            lines.add("" + ChatColor.GOLD + ChatColor.BOLD + spell.getName());
            lines.add("" + ChatColor.RESET);
            String spellDescription = spell.getDescription();
            if (spellDescription != null && spellDescription.length() > 0) {
                lines.add("" + ChatColor.BLACK + spellDescription);
                lines.add("");
            }
            String spellCooldownDescription = spell.getCooldownDescription();
            if (spellCooldownDescription != null && spellCooldownDescription.length() > 0) {
                spellCooldownDescription = messages.get("cooldown.description").replace("$time", spellCooldownDescription);
                lines.add("" + ChatColor.DARK_PURPLE + spellCooldownDescription);
            }
            String spellMageCooldownDescription = spell.getMageCooldownDescription();
            if (spellMageCooldownDescription != null && spellMageCooldownDescription.length() > 0) {
                spellMageCooldownDescription = messages.get("cooldown.mage_description").replace("$time", spellMageCooldownDescription);
                lines.add("" + ChatColor.RED + spellMageCooldownDescription);
            }
            Collection<CastingCost> costs = spell.getCosts();
            if (costs != null) {
                for (CastingCost cost : costs) {
                    if (!cost.isEmpty(reducer)) {
                        lines.add(ChatColor.DARK_PURPLE + messages.get("wand.costs_description").replace("$description", cost.getFullDescription(messages, reducer)));
                    }
                }
            }
            Collection<CastingCost> activeCosts = spell.getActiveCosts();
            if (activeCosts != null) {
                for (CastingCost cost : activeCosts) {
                    if (!cost.isEmpty(reducer)) {
                        lines.add(ChatColor.DARK_PURPLE + messages.get("wand.active_costs_description").replace("$description", cost.getFullDescription(messages, reducer)));
                    }
                }
            }
            for (String pathKey : paths) {
                WandUpgradePath checkPath = WandUpgradePath.getPath(pathKey);
                if (!checkPath.isHidden() && (checkPath.hasSpell(spell.getKey()) || checkPath.hasExtraSpell(spell.getKey()))) {
                    lines.add(ChatColor.DARK_BLUE + messages.get("spell.available_path").replace("$path", checkPath.getName()));
                    break;
                }
            }
            for (String pathKey : paths) {
                WandUpgradePath checkPath = WandUpgradePath.getPath(pathKey);
                if (checkPath.requiresSpell(spell.getKey())) {
                    lines.add(ChatColor.DARK_RED + messages.get("spell.required_path").replace("$path", checkPath.getName()));
                    break;
                }
            }
            String duration = spell.getDurationDescription(messages);
            if (duration != null) {
                lines.add(ChatColor.DARK_GREEN + duration);
            } else if (spell.showUndoable()) {
                if (spell.isUndoable()) {
                    String undoable = messages.get("spell.undoable", "");
                    if (undoable != null && !undoable.isEmpty()) {
                        lines.add(undoable);
                    }
                } else {
                    String notUndoable = messages.get("spell.not_undoable", "");
                    if (notUndoable != null && !notUndoable.isEmpty()) {
                        lines.add(notUndoable);
                    }
                }
            }
            if (spell.usesBrush()) {
                lines.add(ChatColor.DARK_GRAY + messages.get("spell.brush"));
            }
            SpellKey baseKey = spell.getSpellKey();
            SpellKey upgradeKey = new SpellKey(baseKey.getBaseKey(), baseKey.getLevel() + 1);
            SpellTemplate upgradeSpell = getSpellTemplate(upgradeKey.getKey());
            int spellLevels = 0;
            while (upgradeSpell != null) {
                spellLevels++;
                upgradeKey = new SpellKey(upgradeKey.getBaseKey(), upgradeKey.getLevel() + 1);
                upgradeSpell = getSpellTemplate(upgradeKey.getKey());
            }
            if (spellLevels > 0) {
                spellLevels++;
                lines.add(ChatColor.DARK_AQUA + messages.get("spell.levels_available").replace("$levels", Integer.toString(spellLevels)));
            }
            String usage = spell.getUsage();
            if (usage != null && usage.length() > 0) {
                lines.add("" + ChatColor.GRAY + ChatColor.ITALIC + usage + ChatColor.RESET);
                lines.add("");
            }
            String spellExtendedDescription = spell.getExtendedDescription();
            if (spellExtendedDescription != null && spellExtendedDescription.length() > 0) {
                lines.add("" + ChatColor.BLACK + spellExtendedDescription);
                lines.add("");
            }
            pages.add(StringUtils.join(lines, "\n"));
        }
    }
    book.setPages(pages);
    bookItem.setItemMeta(book);
    return bookItem;
}
Also used : WandUpgradePath(com.elmakers.mine.bukkit.wand.WandUpgradePath) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SpellKey(com.elmakers.mine.bukkit.api.spell.SpellKey) CastingCost(com.elmakers.mine.bukkit.api.spell.CastingCost) CostReducer(com.elmakers.mine.bukkit.api.spell.CostReducer) ArrayList(java.util.ArrayList) UndoList(com.elmakers.mine.bukkit.api.block.UndoList) List(java.util.List) ItemStack(org.bukkit.inventory.ItemStack) BookMeta(org.bukkit.inventory.meta.BookMeta) SpellTemplate(com.elmakers.mine.bukkit.api.spell.SpellTemplate)

Example 4 with CastingCost

use of com.elmakers.mine.bukkit.api.spell.CastingCost in project MagicPlugin by elBukkit.

the class HeroesSpellSkill method getDefaultConfig.

@Override
public ConfigurationSection getDefaultConfig() {
    ConfigurationSection node = super.getDefaultConfig();
    // Add in all configured spell parameters
    // Change keys to match heroes-format
    ConfigurationSection spellParameters = spellTemplate.getSpellParameters();
    if (spellParameters != null) {
        Set<String> parameterKeys = spellParameters.getKeys(false);
        for (String parameterKey : parameterKeys) {
            if (!spellParameters.isConfigurationSection(parameterKey) && !spellParameters.isList(parameterKey)) {
                String heroesKey = magicToHeroes(parameterKey);
                Object value = spellParameters.get(parameterKey);
                node.set(heroesKey, value);
                parameters.set(heroesKey, value);
            }
        }
    }
    node.set("icon-url", spellTemplate.getIconURL());
    MaterialAndData icon = spellTemplate.getIcon();
    if (icon != null && icon.getMaterial() != Material.AIR) {
        node.set("icon", icon.getKey());
    }
    MaterialAndData disabledIcon = spellTemplate.getDisabledIcon();
    if (disabledIcon != null && disabledIcon.getMaterial() != Material.AIR) {
        node.set("icon-disabled", disabledIcon.getKey());
    }
    node.set("icon-url", spellTemplate.getIconURL());
    node.set("icon-disabled-url", spellTemplate.getDisabledIconURL());
    node.set("cooldown", spellTemplate.getCooldown());
    node.set("name", spellTemplate.getName());
    Collection<CastingCost> costs = spellTemplate.getCosts();
    if (costs != null) {
        for (CastingCost cost : costs) {
            if (cost.getMana() > 0) {
                node.set(SkillSetting.MANA.node(), cost.getMana());
            }
        // TODO: Reagent costs from item costs
        }
    }
    // Check for an upgrade, set tier if present
    SpellKey upgradeKey = new SpellKey(spellTemplate.getSpellKey().getBaseKey(), 2);
    SpellTemplate upgrade = controller.getSpellTemplate(upgradeKey.getKey());
    if (upgrade != null) {
        int maxUpgrade = 2;
        while (upgrade != null) {
            upgradeKey = new SpellKey(spellTemplate.getSpellKey().getBaseKey(), maxUpgrade + 1);
            upgrade = controller.getSpellTemplate(upgradeKey.getKey());
            if (upgrade != null)
                maxUpgrade++;
        }
        node.set("tier", 1);
        node.set("tier-max", maxUpgrade);
    }
    return node;
}
Also used : CastingCost(com.elmakers.mine.bukkit.api.spell.CastingCost) MaterialAndData(com.elmakers.mine.bukkit.api.block.MaterialAndData) SpellKey(com.elmakers.mine.bukkit.api.spell.SpellKey) ConfigurationSection(org.bukkit.configuration.ConfigurationSection) SpellTemplate(com.elmakers.mine.bukkit.api.spell.SpellTemplate)

Example 5 with CastingCost

use of com.elmakers.mine.bukkit.api.spell.CastingCost in project MagicPlugin by elBukkit.

the class WandLevel method randomizeWand.

public boolean randomizeWand(Mage mage, Wand wand, boolean additive, boolean hasUpgrade, boolean addSpells) {
    // Add random spells to the wand
    Mage activeMage = wand.getActiveMage();
    if (mage == null) {
        mage = activeMage;
    }
    wand.setActiveMage(mage);
    boolean addedSpells = false;
    Deque<WeightedPair<String>> remainingSpells = getRemainingSpells(wand);
    if (addSpells) {
        if (remainingSpells.size() > 0) {
            Integer spellCount = RandomUtils.weightedRandom(spellCountProbability);
            for (int i = 0; spellCount != null && i < spellCount; i++) {
                String spellKey = RandomUtils.weightedRandom(remainingSpells);
                boolean added = wand.addSpell(spellKey);
                mage.sendDebugMessage("Trying to add spell: " + spellKey + " ? " + added);
                if (added) {
                    addedSpells = true;
                }
            }
        }
    }
    // Look through all spells for the max mana casting cost
    // Also look for any material-using spells
    boolean needsMaterials = false;
    int maxManaCost = 0;
    Set<String> spells = wand.getSpells();
    for (String spellName : spells) {
        SpellTemplate spell = wand.getController().getSpellTemplate(spellName);
        if (spell != null) {
            needsMaterials = needsMaterials || spell.usesBrush();
            Collection<CastingCost> costs = spell.getCosts();
            if (costs != null) {
                for (CastingCost cost : costs) {
                    maxManaCost = Math.max(maxManaCost, cost.getMana());
                }
            }
        }
    }
    // Add random materials
    boolean addedMaterials = false;
    Deque<WeightedPair<String>> remainingMaterials = getRemainingMaterials(wand);
    if (needsMaterials && remainingMaterials.size() > 0) {
        int currentMaterialCount = wand.getBrushes().size();
        Integer materialCount = RandomUtils.weightedRandom(materialCountProbability);
        // Make sure the wand has at least one material.
        if (materialCount == null) {
            materialCount = 0;
        }
        if (currentMaterialCount == 0) {
            materialCount = Math.max(1, materialCount);
        }
        int retries = 100;
        for (int i = 0; i < materialCount; i++) {
            String materialKey = RandomUtils.weightedRandom(remainingMaterials);
            materialKey = materialKey.replace("|", ":");
            if (!wand.addBrush(materialKey)) {
                // Try again up to a certain number if we picked one the wand already had.
                if (retries-- > 0)
                    i--;
            } else {
                addedMaterials = true;
            }
        }
    }
    // Let them upgrade if they aren't getting any new spells or brushes
    if (hasUpgrade && addSpells && !(addedMaterials && needsMaterials) && !addedSpells && ((getSpellCount() > 0 && spellProbability.size() > 0) || (getMaterialCount() > 0 && materialProbability.size() > 0))) {
        if (mage != null && mage.getDebugLevel() > 0) {
            mage.sendDebugMessage("Has upgrade: " + hasUpgrade);
            mage.sendDebugMessage("Added spells: " + addedSpells + ", should: " + addSpells);
            mage.sendDebugMessage("Spells per enchant: " + getSpellCount());
            mage.sendDebugMessage("Spells in list: " + spellProbability.size());
            mage.sendDebugMessage("Added brushes: " + addedMaterials + ", needed: " + needsMaterials);
        }
        wand.setActiveMage(activeMage);
        return false;
    }
    // Add random wand properties
    boolean addedProperties = false;
    Integer propertyCount = propertyCountProbability.size() == 0 ? Integer.valueOf(0) : RandomUtils.weightedRandom(propertyCountProbability);
    ConfigurationSection wandProperties = new MemoryConfiguration();
    List<String> propertyKeys = new ArrayList<>(propertiesProbability.keySet());
    List<String> propertiesAvailable = new ArrayList<>();
    for (String propertyKey : propertyKeys) {
        double currentValue = wand.getDouble(propertyKey);
        double maxValue = path.getMaxProperty(propertyKey);
        if (currentValue < maxValue) {
            propertiesAvailable.add(propertyKey);
        }
    }
    // Make sure we give them *something* if something is available
    if (propertiesAvailable.size() > 0 && !addedMaterials && !addedSpells && propertyCount == 0) {
        propertyCount = 1;
    }
    while (propertyCount != null && propertyCount-- > 0 && propertiesAvailable.size() > 0) {
        int randomPropertyIndex = (int) (Math.random() * propertiesAvailable.size());
        String randomProperty = propertiesAvailable.get(randomPropertyIndex);
        Deque<WeightedPair<Float>> probabilities = propertiesProbability.get(randomProperty);
        double current = wand.getDouble(randomProperty);
        double maxValue = path.getMaxProperty(randomProperty);
        if (probabilities.size() > 0 && current < maxValue) {
            addedProperties = true;
            current = Math.min(maxValue, current + RandomUtils.weightedRandom(probabilities));
            wandProperties.set(randomProperty, current);
        }
    }
    if (wand.isCostFree()) {
        // Cost-Free wands don't need mana.
        wandProperties.set("mana_regeneration", 0);
        wandProperties.set("mana_max", 0);
        wandProperties.set("mana", 0);
    } else {
        int manaRegeneration = wand.getManaRegeneration();
        if (manaRegenerationProbability.size() > 0 && manaRegeneration < path.getMaxManaRegeneration()) {
            addedProperties = true;
            manaRegeneration = Math.min(path.getMaxManaRegeneration(), manaRegeneration + RandomUtils.weightedRandom(manaRegenerationProbability));
            wandProperties.set("mana_regeneration", manaRegeneration);
        }
        int manaMax = wand.getManaMax();
        if (manaMaxProbability.size() > 0 && manaMax < path.getMaxMaxMana()) {
            manaMax = Math.min(path.getMaxMaxMana(), manaMax + RandomUtils.weightedRandom(manaMaxProbability));
            if (path.getMatchSpellMana()) {
                // Make sure the wand has at least enough mana to cast the highest costing spell it has.
                manaMax = Math.max(maxManaCost, manaMax);
            }
            wandProperties.set("mana_max", manaMax);
            addedProperties = true;
        }
        // Refill the wand's mana, why not
        wandProperties.set("mana", manaMax);
    }
    // Add or set uses to the wand
    if (additive) {
        // Only add uses to a wand if it already has some.
        int wandUses = wand.getRemainingUses();
        if (wandUses > 0 && wandUses < path.getMaxUses() && addUseProbability.size() > 0) {
            wandProperties.set("uses", Math.min(path.getMaxUses(), wandUses + RandomUtils.weightedRandom(addUseProbability)));
            addedProperties = true;
        }
    } else if (useProbability.size() > 0) {
        wandProperties.set("uses", Math.min(path.getMaxUses(), RandomUtils.weightedRandom(useProbability)));
    }
    // Set properties.
    wand.upgrade(wandProperties);
    wand.setActiveMage(activeMage);
    return addedMaterials || addedSpells || addedProperties;
}
Also used : ArrayList(java.util.ArrayList) MemoryConfiguration(org.bukkit.configuration.MemoryConfiguration) CastingCost(com.elmakers.mine.bukkit.api.spell.CastingCost) Mage(com.elmakers.mine.bukkit.api.magic.Mage) WeightedPair(com.elmakers.mine.bukkit.utility.WeightedPair) SpellTemplate(com.elmakers.mine.bukkit.api.spell.SpellTemplate) ConfigurationSection(org.bukkit.configuration.ConfigurationSection)

Aggregations

CastingCost (com.elmakers.mine.bukkit.api.spell.CastingCost)8 SpellTemplate (com.elmakers.mine.bukkit.api.spell.SpellTemplate)3 MaterialAndData (com.elmakers.mine.bukkit.api.block.MaterialAndData)2 UndoList (com.elmakers.mine.bukkit.api.block.UndoList)2 CostReducer (com.elmakers.mine.bukkit.api.spell.CostReducer)2 MageSpell (com.elmakers.mine.bukkit.api.spell.MageSpell)2 Spell (com.elmakers.mine.bukkit.api.spell.Spell)2 SpellKey (com.elmakers.mine.bukkit.api.spell.SpellKey)2 ArrayList (java.util.ArrayList)2 Location (org.bukkit.Location)2 ConfigurationSection (org.bukkit.configuration.ConfigurationSection)2 MemoryConfiguration (org.bukkit.configuration.MemoryConfiguration)2 LivingEntity (org.bukkit.entity.LivingEntity)2 ItemStack (org.bukkit.inventory.ItemStack)2 CastContext (com.elmakers.mine.bukkit.action.CastContext)1 Batch (com.elmakers.mine.bukkit.api.batch.Batch)1 SpellBatch (com.elmakers.mine.bukkit.api.batch.SpellBatch)1 PreCastEvent (com.elmakers.mine.bukkit.api.event.PreCastEvent)1 CastSourceLocation (com.elmakers.mine.bukkit.api.magic.CastSourceLocation)1 CasterProperties (com.elmakers.mine.bukkit.api.magic.CasterProperties)1