Merge branch 'development'

This commit is contained in:
Brianna 2019-10-08 15:55:41 -04:00
commit 9d525a4f75
209 changed files with 7656 additions and 1393 deletions

View File

@ -4,7 +4,7 @@ stages:
variables:
name: "EpicEnchants"
path: "/builds/$CI_PROJECT_PATH"
version: "1.0.5-ALPHA"
version: "1.0.8"
build:
stage: build

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
Copyright (c) 2019 Brianna OKeefe
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software with minimal restriction, including the rights to use, copy, modify or merge while excluding the rights to publish, (re)distribute, sub-license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The same distribution rights and limitations above shall similarly apply to any and all source code, and other means that can be used to emulate this work.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,124 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>EpicEnchants-Parent</artifactId>
<groupId>com.songoda</groupId>
<version>1.0.5-ALPHA</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>EpicEnchants</artifactId>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
<repository>
<id>aikar</id>
<url>https://repo.aikar.co/content/groups/aikar/</url>
</repository>
<repository>
<id>placeholderapi</id>
<url>http://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
</repositories>
<build>
<defaultGoal>clean package</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<dependencyReducedPomLocation>${project.build.directory}/dependency-reduced-pom.xml</dependencyReducedPomLocation>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.13.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
</dependency>
<dependency>
<groupId>com.github.tr7zw</groupId>
<artifactId>Item-NBT-API</artifactId>
<version>master-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>co.aikar</groupId>
<artifactId>acf-bukkit</artifactId>
<version>0.5.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.songoda</groupId>
<artifactId>UltimateBottles</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.9.2</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,67 +0,0 @@
package com.songoda.epicenchants;
import com.songoda.epicenchants.objects.Placeholder;
import org.bukkit.Effect;
import org.bukkit.Sound;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static com.songoda.epicenchants.utils.single.GeneralUtils.color;
public class Action {
private FileConfiguration config;
public void perform(CommandSender sender, String node, Placeholder... placeholders) {
if (config.isString(node)) {
getMessage(node, placeholders).forEach(sender::sendMessage);
return;
}
if (!config.isConfigurationSection(node)) {
return;
}
ConfigurationSection section = config.getConfigurationSection(node);
if (section.isString("message") || section.isList("message")) {
getMessage(node + ".message", placeholders).forEach(sender::sendMessage);
}
if (!(sender instanceof Player)) {
return;
}
Player player = (Player) sender;
if (section.isString("sound")) {
player.playSound(player.getLocation(), Sound.valueOf(section.getString("sound").toUpperCase()), 1F, 1F);
}
if (section.isString("effect")) {
player.playEffect(player.getEyeLocation(), Effect.valueOf(section.getString("effect")), 10);
}
}
public List<String> getMessage(String node, Placeholder... placeholders) {
List<String> output = config.isList(node) ? config.getStringList(node) : config.getString(node).isEmpty() ? Collections.emptyList() : Collections.singletonList(config.getString(node));
return output.stream().map(s -> {
for (Placeholder placeholder : placeholders) {
s = s.replace(placeholder.getPlaceholder(), placeholder.getToReplace().toString());
}
return color(s);
}).collect(Collectors.toList());
}
public void load(FileConfiguration config) {
this.config = config;
}
}

View File

@ -1,125 +0,0 @@
package com.songoda.epicenchants;
import co.aikar.commands.BukkitCommandManager;
import com.songoda.epicenchants.listeners.ArmorListener;
import com.songoda.epicenchants.listeners.EntityListener;
import com.songoda.epicenchants.listeners.PlayerListener;
import com.songoda.epicenchants.listeners.item.BlackScrollListener;
import com.songoda.epicenchants.listeners.item.BookListener;
import com.songoda.epicenchants.listeners.item.DustListener;
import com.songoda.epicenchants.listeners.item.WhiteScrollListener;
import com.songoda.epicenchants.managers.*;
import com.songoda.epicenchants.objects.Enchant;
import com.songoda.epicenchants.utils.EnchantUtils;
import com.songoda.epicenchants.utils.SpecialItems;
import com.songoda.epicenchants.utils.objects.FastInv;
import com.songoda.epicenchants.utils.single.ItemGroup;
import lombok.Getter;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.HashSet;
import java.util.stream.Collectors;
import static com.songoda.epicenchants.utils.single.GeneralUtils.color;
import static org.bukkit.Bukkit.getConsoleSender;
@Getter
public class EpicEnchants extends JavaPlugin {
private BukkitCommandManager commandManager;
private EnchantManager enchantManager;
private InfoManager infoManager;
private GroupManager groupManager;
private FileManager fileManager;
private HookManager hookManager;
private SpecialItems specialItems;
private Action action;
private Economy economy;
private EnchantUtils enchantUtils;
private ItemGroup itemGroup;
private int version;
@Override
public void onEnable() {
getConsoleSender().sendMessage(color("&a============================="));
getConsoleSender().sendMessage(color("&7" + getDescription().getName() + " " + getDescription().getVersion() + " by &5Songoda <3&7!"));
getConsoleSender().sendMessage(color("&7Action: &aEnabling&7..."));
preload();
this.action = new Action();
this.groupManager = new GroupManager(this);
this.enchantManager = new EnchantManager(this);
this.enchantUtils = new EnchantUtils(this);
this.infoManager = new InfoManager(this);
this.specialItems = new SpecialItems(this);
this.economy = getServer().getServicesManager().getRegistration(Economy.class).getProvider();
this.commandManager = new CommandManager(this);
this.hookManager = new HookManager();
this.itemGroup = new ItemGroup(this);
groupManager.loadGroups();
enchantManager.loadEnchants();
infoManager.loadMenus();
action.load(fileManager.getConfiguration("actions"));
hookManager.setup();
setupListeners();
if (!enchantManager.getValues().isEmpty()) {
getLogger().info("Successfully loaded enchants: " + enchantManager.getValues().stream().map(Enchant::getIdentifier).collect(Collectors.joining(", ")));
}
getConsoleSender().sendMessage(color("&a============================="));
}
private void preload() {
FastInv.init(this);
this.version = Integer.parseInt(Bukkit.getServer().getBukkitVersion().split("\\.")[1]);
this.fileManager = new FileManager(this);
fileManager.loadFiles();
}
@Override
public void onDisable() {
getConsoleSender().sendMessage(color("&a============================="));
getConsoleSender().sendMessage(color("&7" + getDescription().getName() + " " + getDescription().getVersion() + " by &5Songoda <3&7!"));
getConsoleSender().sendMessage(color("&7Action: &cDisabling&7..."));
getConsoleSender().sendMessage(color("&a============================="));
}
private void setupListeners() {
EpicEnchants instance = this;
new HashSet<Listener>() {{
add(new BookListener(instance));
add(new ArmorListener());
add(new PlayerListener(instance));
add(new EntityListener(instance));
add(new WhiteScrollListener(instance));
add(new BlackScrollListener(instance));
add(new DustListener(instance));
}}.forEach(listener -> Bukkit.getPluginManager().registerEvents(listener, this));
}
public void reload() {
reloadConfig();
fileManager.clear();
fileManager.loadFiles();
groupManager.clear();
groupManager.loadGroups();
enchantManager.clear();
enchantManager.loadEnchants();
infoManager.clear();
infoManager.loadMenus();
action.load(fileManager.getConfiguration("actions"));
}
}

View File

@ -1,37 +0,0 @@
package com.songoda.epicenchants.commands;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.annotation.*;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.menus.AlchemistMenu;
import com.songoda.epicenchants.menus.EnchanterMenu;
import com.songoda.epicenchants.menus.TinkererMenu;
import org.bukkit.entity.Player;
public class CustomCommand extends BaseCommand {
@Dependency("instance")
private EpicEnchants instance;
@CommandAlias("%enchanter")
@Description("Opens the Enchanter")
@CommandPermission("epicenchants.enchanter")
public void onEnchanter(Player player) {
new EnchanterMenu(instance, instance.getFileManager().getConfiguration("menus/enchanter-menu"), player).open(player);
}
@CommandAlias("%tinkerer")
@Description("Opens the Tinkerer")
@CommandPermission("epicenchants.tinkerer")
public void onTinkerer(Player player) {
new TinkererMenu(instance, instance.getFileManager().getConfiguration("menus/tinkerer-menu")).open(player);
}
@CommandAlias("%alchemist")
@Description("Opens the Alchemist")
@CommandPermission("epicenchants.alchemist")
public void onAlchemist(Player player) {
new AlchemistMenu(instance, instance.getFileManager().getConfiguration("menus/alchemist-menu")).open(player);
}
}

View File

@ -1,125 +0,0 @@
package com.songoda.epicenchants.commands;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.CommandHelp;
import co.aikar.commands.annotation.*;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.enums.EnchantResult;
import com.songoda.epicenchants.objects.Enchant;
import com.songoda.epicenchants.objects.Group;
import org.apache.commons.lang3.tuple.Pair;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import static com.songoda.epicenchants.enums.EnchantResult.BROKEN_FAILURE;
import static com.songoda.epicenchants.objects.Placeholder.of;
import static com.songoda.epicenchants.utils.single.GeneralUtils.getMessageFromResult;
@CommandAlias("epicenchants|ee")
public class EnchantCommand extends BaseCommand {
@Dependency("instance")
private EpicEnchants instance;
//ee give book [player] [enchant] <level> <success-rate> <destroy-rate>
@Subcommand("give book")
@CommandCompletion("@players @enchants @levels @increment @increment")
@Description("Give enchant books to players")
@CommandPermission("epicenchants.give.book")
public void onGiveBook(CommandSender sender, @Flags("other") Player target, Enchant enchant, @Optional Integer level, @Optional Integer successRate, @Optional Integer destroyRate) {
if (level != null && level > enchant.getMaxLevel()) {
instance.getAction().perform(sender, "command.book.max-level",
of("enchant", enchant.getIdentifier()),
of("max-level", enchant.getMaxLevel()));
return;
}
target.getInventory().addItem(enchant.getBook().get(enchant, level, successRate, destroyRate));
instance.getAction().perform(target, "command.book.received", of("enchant", enchant.getIdentifier()));
instance.getAction().perform(sender, "command.book.gave", of("player", target.getName()), of("enchant", enchant.getIdentifier()));
}
//ee give item dust [player] [group] <type> <percentage>
@Subcommand("give item dust")
@CommandCompletion("@players @groups @dustTypes @nothing")
@CommandPermission("epicenchants.give.item.dust")
public void onGiveDust(CommandSender sender, @Flags("other") Player target, Group group, @Optional String dustType, @Optional Integer percentage) {
target.getInventory().addItem(instance.getSpecialItems().getDust(group, dustType, percentage, true));
instance.getAction().perform(target, "command.dust.received", of("group", group.getIdentifier()));
instance.getAction().perform(sender, "command.dust.gave", of("player", target.getName()), of("group", group.getIdentifier()));
}
//ee give item [giveType] [player] <amount> <success-rate>
@Subcommand("give item")
@CommandCompletion("@giveType @players @nothing @nothing")
@Description("Give enchant books to players")
@CommandPermission("epicenchants.give.item")
public void onGiveItem(CommandSender sender, String giveType, @Flags("other") Player target, @Optional Integer amount, @Optional Integer successRate) {
String messageKey;
switch (giveType.toLowerCase()) {
case "whitescroll":
target.getInventory().addItem(instance.getSpecialItems().getWhiteScroll(amount));
messageKey = "whitescroll";
break;
case "blackscroll":
messageKey = "blackscroll";
target.getInventory().addItem(instance.getSpecialItems().getBlackScroll(amount, successRate));
break;
default:
return;
}
instance.getAction().perform(target, "command." + messageKey + ".received");
instance.getAction().perform(sender, "command." + messageKey + ".gave", of("player", target.getName()));
}
//ee apply [enchant] [level] <success-rate> <destroy-rate>
@Subcommand("apply")
@CommandCompletion("@enchants @nothing")
@Description("Apply enchant to item in hand")
@CommandPermission("epicenchants.apply")
public void onApply(Player player, Enchant enchant, int level, @Optional Integer successRate, @Optional Integer destroyRate) {
if (player.getItemInHand() == null) {
instance.getAction().perform(player, "command.apply.noitem", of("enchant", enchant.getIdentifier()));
return;
}
int slot = player.getInventory().getHeldItemSlot();
ItemStack before = player.getItemInHand();
Pair<ItemStack, EnchantResult> result = instance.getEnchantUtils().apply(before, enchant, level,
successRate == null ? 100 : successRate, destroyRate == null ? 0 : destroyRate);
instance.getAction().perform(player, getMessageFromResult(result.getRight()), of("enchant", enchant.getIdentifier()));
if (result.getRight() == BROKEN_FAILURE) {
player.getInventory().clear(slot);
return;
}
player.getInventory().setItem(slot, result.getLeft());
}
//ee list
@Subcommand("info")
@CommandPermission("epicenchants.info")
@Description("List all enchants with their description")
public void onList(Player player) {
instance.getInfoManager().getMainInfoMenu().open(player);
}
//ee reload [enchantFileName]
@Subcommand("reload")
@Description("Reload all config files.")
@CommandPermission("epicenchants.reload")
public void onReload(CommandSender sender) {
instance.reload();
instance.getAction().perform(sender, "command.reload");
}
@HelpCommand
public void doHelp(CommandSender sender, CommandHelp help) {
help.showHelp();
}
}

View File

@ -1,76 +0,0 @@
package com.songoda.epicenchants.managers;
import co.aikar.commands.BukkitCommandManager;
import co.aikar.commands.InvalidCommandArgument;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.commands.CustomCommand;
import com.songoda.epicenchants.commands.EnchantCommand;
import com.songoda.epicenchants.enums.GiveType;
import com.songoda.epicenchants.objects.Enchant;
import com.songoda.epicenchants.objects.Group;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class CommandManager extends BukkitCommandManager {
public CommandManager(EpicEnchants instance) {
super(instance);
// DEPENDENCIES
registerDependency(EpicEnchants.class, "instance", instance);
// COMPLETIONS
getCommandCompletions().registerCompletion("enchants", c ->
instance.getEnchantManager().getKeys().stream().map(s -> s.replaceAll("\\s", "_")).collect(Collectors.toList()));
getCommandCompletions().registerCompletion("giveType", c ->
Arrays.stream(GiveType.values()).map(s -> s.toString().replace("_", "").toLowerCase()).collect(Collectors.toList()));
getCommandCompletions().registerCompletion("levels", c ->
IntStream.rangeClosed(1, c.getContextValue(Enchant.class).getMaxLevel()).boxed().map(Objects::toString).collect(Collectors.toList()));
getCommandCompletions().registerCompletion("increment", c ->
IntStream.rangeClosed(0, 100).filter(i -> i % 10 == 0).boxed().map(Objects::toString).collect(Collectors.toList()));
getCommandCompletions().registerCompletion("groups", c ->
instance.getGroupManager().getValues().stream().map(Group::getIdentifier).collect(Collectors.toList()));
getCommandCompletions().registerCompletion("dustTypes", c ->
instance.getFileManager().getConfiguration("items/dusts").getConfigurationSection("dusts").getKeys(false));
// CONTEXTS
getCommandContexts().registerContext(Enchant.class, c ->
instance.getEnchantManager().getValue(c.popFirstArg().replaceAll("_", " ")).orElseThrow(() ->
new InvalidCommandArgument("No enchant exists by that name", false)));
getCommandContexts().registerContext(GiveType.class, c -> Arrays.stream(GiveType.values())
.filter(s -> s.toString().toLowerCase().replace("_", "").equalsIgnoreCase(c.popFirstArg()))
.findFirst()
.orElseThrow(() -> new InvalidCommandArgument("No item by that type.", false)));
getCommandContexts().registerContext(Group.class, c -> instance.getGroupManager().getValue(c.popFirstArg().toUpperCase()).orElseThrow(() ->
new InvalidCommandArgument("No group exists by that name", false)));
// REPLACEMENTS
getCommandReplacements().addReplacements(
"enchanter", instance.getFileManager().getConfiguration("config").getString("commands.enchanter"),
"alchemist", instance.getFileManager().getConfiguration("config").getString("commands.alchemist"),
"tinkerer", instance.getFileManager().getConfiguration("config").getString("commands.tinkerer")
);
// API
enableUnstableAPI("help");
// COMMANDS
registerCommand(new EnchantCommand());
registerCommand(new CustomCommand());
}
}

View File

@ -1,104 +0,0 @@
package com.songoda.epicenchants.managers;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.utils.objects.FileLocation;
import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.*;
import static com.songoda.epicenchants.utils.objects.FileLocation.of;
import static java.io.File.separator;
import static java.util.Arrays.asList;
public class FileManager extends Manager<String, FileConfiguration> {
private final String directory;
private final LinkedHashSet<FileLocation> files = new LinkedHashSet<>(asList(
of("config.yml", true),
of("menus/main-info-menu.yml", true),
of("menus/enchanter-menu.yml", true, true),
of("menus/tinkerer-menu.yml", true, true),
of("menus/alchemist-menu.yml", true, true),
of("menus/groups/simple-menu.yml", false),
of("menus/groups/unique-menu.yml", false),
of("menus/groups/elite-menu.yml", false),
of("menus/groups/ultimate-menu.yml", false),
of("menus/groups/legendary-menu.yml", false),
of("enchants/example-enchant.yml", false),
of("groups.yml", true),
of("actions.yml", true),
of("items/special-items.yml", true, true),
of("items/dusts.yml", true, true)
));
public FileManager(EpicEnchants instance) {
super(instance);
directory = instance.getVersion() > 12 ? "master" : "legacy";
Bukkit.getConsoleSender().sendMessage("Using the " + directory + " configurations because version is 1." + instance.getVersion());
}
public void loadFiles() {
files.forEach(fileLocation -> {
File file = new File(instance.getDataFolder() + separator + fileLocation.getPath());
if (!file.exists() && (fileLocation.isRequired() || getConfiguration("config").getBoolean("first-load"))) {
file.getParentFile().mkdirs();
Bukkit.getConsoleSender().sendMessage("Creating file: " + fileLocation.getPath());
try {
FileUtils.copyInputStreamToFile(instance.getResource(fileLocation.getResourcePath(directory)), file);
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileLocation.isRequired()) {
FileConfiguration configuration = new YamlConfiguration();
try {
configuration.load(file);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
add(fileLocation.getPath().replace(".yml", ""), configuration);
}
});
getConfiguration("config").set("first-load", false);
try {
getConfiguration("config").save(new File(instance.getDataFolder() + separator + "config.yml"));
} catch (IOException e) {
e.printStackTrace();
}
}
public FileConfiguration getConfiguration(String key) {
return getValueUnsafe(key);
}
public List<File> getYmlFiles(String directory) {
File dir = new File(instance.getDataFolder() + separator + directory + separator);
File[] allFiles = dir.listFiles();
List<File> output = new ArrayList<>();
if (allFiles == null) {
return output;
}
Optional.ofNullable(dir.listFiles((dir1, filename) -> filename.endsWith(".yml"))).ifPresent(list -> {
output.addAll(Arrays.asList(list));
});
Arrays.stream(allFiles)
.filter(File::isDirectory)
.filter(s -> !s.getName().equalsIgnoreCase("old"))
.forEach(f -> output.addAll(getYmlFiles(directory + separator + f.getName())));
return output;
}
}

View File

@ -1,52 +0,0 @@
package com.songoda.epicenchants.objects;
import com.songoda.epicenchants.effect.EffectExecutor;
import com.songoda.epicenchants.enums.EventType;
import com.songoda.epicenchants.enums.TriggerType;
import com.songoda.epicenchants.utils.single.RomanNumber;
import lombok.Builder;
import lombok.Getter;
import org.bukkit.Material;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Set;
import static com.songoda.epicenchants.utils.single.GeneralUtils.color;
@Builder
@Getter
public class Enchant {
private String identifier;
private Group group;
private int maxLevel;
private Set<String> conflict;
private Set<Material> itemWhitelist;
private Set<EffectExecutor> effectExecutors;
private List<String> description;
private String format;
@Nullable private BookItem bookItem;
public void onAction(@NotNull Player user, @Nullable LivingEntity opponent, Event event, int level, TriggerType triggerType, EventType eventType) {
effectExecutors.forEach(effect -> effect.testAndRun(user, opponent, level, triggerType, event, eventType));
}
public BookItem getBook() {
return bookItem != null ? bookItem : group.getBookItem();
}
public String getFormat(int level, boolean roman) {
String output = format.isEmpty() ? group.getFormat() : format;
output = output
.replace("{level}", "" + (roman ? RomanNumber.toRoman(level) : level))
.replace("{enchant}", "" + identifier)
.replace("{group_color}", "" + group.getColor());
return color(output);
}
}

View File

@ -1,19 +0,0 @@
package com.songoda.epicenchants.objects;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class Group {
private String identifier;
private String name;
private String format;
private String color;
private String descriptionColor;
private int slotsUsed;
private BookItem bookItem;
private int destroyRateMin, destroyRateMax, successRateMin, successRateMax;
private int tinkererExp;
private int order;
}

View File

@ -1,23 +0,0 @@
package com.songoda.epicenchants.wrappers;
import com.songoda.epicenchants.objects.LeveledModifier;
import lombok.Builder;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@Builder
public class EnchantmentWrapper {
private LeveledModifier amplifier;
private Enchantment enchantment;
public int getAmplifier(int level, @NotNull Player user, @Nullable LivingEntity opponent) {
return (int) amplifier.get(level, 0, user, opponent);
}
public Enchantment getEnchantment() {
return enchantment;
}
}

View File

@ -1,61 +0,0 @@
general:
no-permission: "&cYou do not have permission to do that."
command:
book:
received: "&7You have been given a &6{enchant} &7book."
gave: "&7You gave {player} a &6{enchant} &7book."
max-level: "&cThe max level for {enchant} is {max-level}."
white-scroll:
received: "&7You have been given a whitescroll."
gave: "&7You gave {player} a whitescroll."
reload: "&6Configuration files reload"
black-scroll:
success: "&aSuccessfully blackscrolled: {group_color}{enchant} {level}&a."
no-enchants: "&cNo enchants to blackscroll."
white-scroll:
already-applied: "&cThis item is already protected!"
applied: "&aThis item is now protected!"
enchanter:
cannot-afford: "&c&l(!) &r&cYou cannot afford this purchase."
success: "&7Purchased {group_color}{group_name} &7book for &f{exp_cost} EXP&7."
tinkerer:
open: "&eTrading with the tinkerer."
cancelled: "&c&l(!) &r&cCancelled."
accepted: "&aAccepted"
no-items: "&c&l(!) &r&cThe tinkerer is not interested in any of your items!"
deposited-all: "&a&l(!) &r&aDeposited {amount} items."
alchemist:
max-two-items: "&c&l(!) &r&cYou may only combine 2 items at once."
not-interested: "&c&l(!) &r&cThe alchemist is not interested in any of your items!"
max-level-book: "&c&l(!) &r&cThe alchemist cannot combine max level books."
max-percentage-dust: "&c&l(!) &r&cThe alchemist cannot combine 100% success rate dusts."
highest-group-dust: "&c&l(!) &r&cThe alchemist can't accept dust of the highest tier."
different-enchantment: "&c&l(!) &r&cThe alchemist can only combine books with the same enchantment."
different-levels: "&c&l(!) &r&cThe alchemist can only combine books of the same level."
different-groups: "&c&l(!) &r&cThe alchemist can only combine dusts of the same group."
cannot-afford: "&c&l(!) You cannot afford this exchange."
success: "&7Exchanged for &f{exp_cost} EXP&7."
enchants:
invalid-material: "&cYou can not apply &6{enchant} &cto that item."
broken-failure: "&6{enchant} &cfailed to apply and broke your item..."
success: "&aYou have success fully applied &6{enchant}."
conflict: "&cYou cannot apply this enchant as it conflicts with another enchant."
maxed-out: "&cYou already have that enchant maxed on this item."
already-applied: "&cYou already have that enchant applied on this item."
protected: "&aYour book would have broken your item, luckily it was protected!"
book:
discover:
- "&l&e(!) &r&eYou examine the {group_color}{group_name} Enchantment Book..."
- "&eand discover &n{enchant_format}!"

View File

@ -1,17 +0,0 @@
#MASTER CONFIG
first-load: true
language: "en_US"
roman-numbers: true
rates:
black-scroll-min: 20
black-scroll-max: 100
commands:
enchanter: "enchanter"
alchemist: "alchemist"
tinkerer: "tinkerer"

View File

@ -1,98 +0,0 @@
# The enchant identifier must be unique.
identifier: ExampleEnchant
# The max level for this enchant.
max-level: 3
# The group of this enchant. Configure the groups in the groups.yml file.
group: SIMPLE
# The item that the enchantment book is.
book-item:
material: BOOK
display-name: "&b&lExampleEnchant {level}"
# The lore on the enchantments books.
lore:
- "&7Drag on to enchant"
- "&a{success_rate}% Success Rate"
- "&c{destroy_rate}% Destroy Rate"
# How the enchant should be formatted on the enchanted item.
applied-format: "&cExampleEnchant {level}"
# What items this enchant can be applied too.
item-whitelist:
- "DIAMOND_HELMET"
- "IRON_HELMET"
- "LEATHER_HELMET"
# This enchantment can not be applied if then enchantment below is already on the item.
conflicting-enchants:
- "someEnchant"
# For a full list of effects, please visit: https://wiki.songoda.com/display/SON/EpicEnchants
effects:
# The "-1" is added because every effect key has to be unique.
POTION-1:
# The trigger that will fire this effect
trigger: DEFENSE_PLAYER_MELEE
# What player should the effect be ran on: WEARER/OPPONENT.
who: WEARER
# Potion Effect that should be applied.
potion-type: SPEED
# Duration of the Potion Effect in seconds.
duration: "10 * {level}"
# Chance that the Effect gets activated.
chance: "20 * {level}"
# Amplifier of 0 = SPEED 1 a Amplifier of 1 = SPEED 2, etc.
amplifier: "{level} - 1"
POTION-2:
trigger: STATIC_EFFECT
who: WEARER
potion-type: INCREASE_DAMAGE
amplifier: "{level} - 1"
# Chance of spawning when damaged by another player.
mobs:
# Type of Mob
ZOMBIE:
# Trigger event that spawns the mob.
trigger: DEFENSE_PLAYER_MELEE
# Max amount mobs that will be spawned.
max-amount: "{level}"
# Chance of trigger the mob spawning.
spawn-percentage: "20 * {level}"
# Drop chance of the mob its equipment upon death.
equipment-drop-chance: "10 * {level}"
# Health of the mob.
health: "3 * {level}"
# Amount of damage the mob deals.
attack-damage: "{level}"
# Display name of the spawned mob
display-name: "&cAngry guy level {level}"
# The equiment that the mob wears
equipment:
helmet:
material: DIAMOND_HELMET
enchants:
- "DURABILITY:{level}"
- "THORNS:{level} - 1"
chestplate:
material: DIAMOND_CHESTPLATE
enchants:
- "DURABILITY:{level}"
- "THORNS:{level} - 1"
leggings:
material: DIAMOND_LEGGINGS
enchants:
- "DURABILITY:{level}"
- "THORNS:{level} - 1"
boots:
material: DIAMOND_BOOTS
enchants:
- "DURABILITY:{level}"
- "THORNS:{level} - 1"
hand-item:
material: DIAMOND_SWORD
enchant:
- "SHARPNESS:{level}"

View File

@ -1,18 +0,0 @@
title: "Elite enchants"
rows: 1
#Slots that you want enchants to be displayed on
slots: "ALL_SLOTS"
#The group of the enchants to be displayed
group: ELITE
enchant-item:
description-color: "&f"
material: "PAPER"
display-name: "{group_color}{enchant}"
lore:
- "&7Max level: &f{max_level}"
- "&7Applicable to: &f{applicable_to}"
- "&7Description:"
- "{description}"

View File

@ -1,18 +0,0 @@
title: "Legendary enchants"
rows: 1
#Slots that you want enchants to be displayed on
slots: "ALL_SLOTS"
#The group of the enchants to be displayed
group: LEGENDARY
enchant-item:
description-color: "&f"
material: "PAPER"
display-name: "{group_color}{enchant}"
lore:
- "&7Max level: &f{max_level}"
- "&7Applicable to: &f{applicable_to}"
- "&7Description:"
- "{description}"

View File

@ -1,18 +0,0 @@
title: "Simple enchants"
rows: 1
#Slots that you want enchants to be displayed on
slots: "ALL_SLOTS"
#The group of the enchants to be displayed
group: SIMPLE
enchant-item:
description-color: "&f"
material: "PAPER"
display-name: "{group_color}{enchant}"
lore:
- "&7Max level: &f{max_level}"
- "&7Applicable to: &f{applicable_to}"
- "&7Description:"
- "{description}"

View File

@ -1,18 +0,0 @@
title: "Ultimate enchants"
rows: 1
#Slots that you want enchants to be displayed on
slots: "ALL_SLOTS"
#The group of the enchants to be displayed
group: ULTIMATE
enchant-item:
description-color: "&f"
material: "PAPER"
display-name: "{group_color}{enchant}"
lore:
- "&7Max level: &f{max_level}"
- "&7Applicable to: &f{applicable_to}"
- "&7Description:"
- "{description}"

View File

@ -1,18 +0,0 @@
title: "Unique enchants"
rows: 1
#Slots that you want enchants to be displayed on
slots: "ALL_SLOTS"
#The group of the enchants to be displayed
group: UNIQUE
enchant-item:
description-color: "&f"
material: "PAPER"
display-name: "{group_color}{enchant}"
lore:
- "&7Max level: &f{max_level}"
- "&7Applicable to: &f{applicable_to}"
- "&7Description:"
- "{description}"

View File

@ -1,29 +0,0 @@
title: "Main info menu"
rows: 1
contents:
1:
material: "PAPER"
display-name: "&f&lSimple Enchantments"
group: SIMPLE
slot: 2
2:
material: "PAPER"
display-name: "&a&lUnique Enchantments"
group: UNIQUE
slot: 3
3:
material: "PAPER"
display-name: "&b&lElite Enchantments"
group: ELITE
slot: 4
4:
material: "PAPER"
display-name: "&e&lUltimate Enchantments"
group: ULTIMATE
slot: 5
5:
material: "PAPER"
display-name: "&6&lLegendary Enchantments"
group: LEGENDARY
slot: 6

View File

@ -1,8 +0,0 @@
name: EpicEnchants
version: ${project.version}
main: com.songoda.epicenchants.EpicEnchants
authors: [GB6]
website: https://songoda.com/
depend: [Vault]
softdepend: [UltimateBottles, PlaceholderAPI]
api-version: 1.13

View File

@ -1,41 +0,0 @@
title: "Tinkerer"
rows: 6
player-slots: "1,2,3,9,10,11,12,18,19,20,21,27,28,29,30,36,37,38,39,45,46,47,48"
tinkerer-slots: "5,6,7,14,15,16,17,23,24,25,26,32,33,34,35,41,42,43,44,50,51,52,53"
slots: "(1,5) (2,6) (3,7) (9,14)
(10,15) (11,16) (12,17) (18,23)
(19,24) (20,25) (21,26) (27,32)
(28,33) (29,34) (30,35) (36,41)
(37,42) (38,43) (39,44) (45,50)
(46,51) (47,52) (48,53)"
contents:
1:
material: "STAINED_GLASS_PANE"
display-name: " "
slot: "4,13,22,31,40"
accept-left:
material: "STAINED_GLASS_PANE"
data: 4
display-name: "&eClick to accept trade"
slot: 0
accept-right:
material: "STAINED_GLASS_PANE"
data: 4
display-name: "&eClick to accept trade"
slot: 8
deposit-all:
material: "STAINED_GLASS_PANE"
data: 4
display-name: "&l&eDeposit All"
lore:
- "&7Click to deposit all tinkerable items."
slot: "49"
exp-table-per-level:
DEFAULT: 10
DEPTH_STRIDER: 20
ExampleEnchant: 50

View File

@ -1,38 +0,0 @@
title: "Tinkerer"
rows: 6
player-slots: "1,2,3,9,10,11,12,18,19,20,21,27,28,29,30,36,37,38,39,45,46,47,48"
tinkerer-slots: "5,6,7,14,15,16,17,23,24,25,26,32,33,34,35,41,42,43,44,50,51,52,53"
slots: "(1,5) (2,6) (3,7) (9,14)
(10,15) (11,16) (12,17) (18,23)
(19,24) (20,25) (21,26) (27,32)
(28,33) (29,34) (30,35) (36,41)
(37,42) (38,43) (39,44) (45,50)
(46,51) (47,52) (48,53)"
contents:
1:
material: "WHITE_STAINED_GLASS_PANE"
display-name: " "
slot: "4,13,22,31,40"
accept-left:
material: "LIME_STAINED_GLASS_PANE"
display-name: "&eClick to accept trade"
slot: 0
accept-right:
material: "LIME_STAINED_GLASS_PANE"
display-name: "&eClick to accept trade"
slot: 8
deposit-all:
material: "LIME_STAINED_GLASS_PANE"
display-name: "&l&eDeposit All"
lore:
- "&7Click to deposit all tinkerable items."
slot: "49"
exp-table-per-level:
DEFAULT: 10
DEPTH_STRIDER: 20
ExampleEnchant: 50

129
pom.xml
View File

@ -1,41 +1,116 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<groupId>com.songoda</groupId>
<artifactId>EpicEnchants-Parent</artifactId>
<packaging>pom</packaging>
<version>1.0.5-ALPHA</version>
<modules>
<module>core</module>
</modules>
<repositories>
<repository>
<id>private</id>
<url>http://repo.songoda.com/repository/private/</url>
</repository>
</repositories>
<artifactId>EpicEnchants</artifactId>
<modelVersion>4.0.0</modelVersion>
<version>maven-version-number</version>
<build>
<defaultGoal>clean install</defaultGoal>
<finalName>EpicEnchants-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>shaded</id>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>false</shadedArtifactAttached>
<createDependencyReducedPom>false</createDependencyReducedPom>
<artifactSet>
<includes>
<include>com.songoda:songodaupdater</include>
<include>fr.mymicky:FastInv</include>
</includes>
</artifactSet>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<repositories>
<repository>
<id>private</id>
<url>http://repo.songoda.com/artifactory/private/</url>
</repository>
<repository>
<id>reserve-repo</id>
<url>https://dl.bintray.com/theneweconomy/java/</url>
</repository>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.14.4</version>
</dependency>
<dependency>
<groupId>fr.mrmicky</groupId>
<artifactId>FastInv</artifactId>
<version>3.0.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.songoda</groupId>
<artifactId>songodaupdater</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>net.tnemc</groupId>
<artifactId>Reserve</artifactId>
<version>0.1.3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.black_ixx</groupId>
<artifactId>playerpoints</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>net.milkbowl</groupId>
<artifactId>vault</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>com.songoda</groupId>
<artifactId>UltimateBottles</artifactId>
<version>1_0</version>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.9.2</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,15 @@
package com.songoda.epicenchants;
import com.songoda.epicenchants.utils.Methods;
import org.bukkit.command.CommandSender;
public class CommandCommons {
public static boolean isInt(String number, CommandSender sender) {
if (!Methods.isInt(number)) {
EpicEnchants.getInstance().getLocale().newMessage("Not a number.").sendPrefixedMessage(sender);
return false;
}
return true;
}
}

View File

@ -0,0 +1,226 @@
package com.songoda.epicenchants;
import com.songoda.epicenchants.command.CommandManager;
import com.songoda.epicenchants.economy.Economy;
import com.songoda.epicenchants.economy.PlayerPointsEconomy;
import com.songoda.epicenchants.economy.ReserveEconomy;
import com.songoda.epicenchants.economy.VaultEconomy;
import com.songoda.epicenchants.listeners.ArmorListener;
import com.songoda.epicenchants.listeners.EntityListener;
import com.songoda.epicenchants.listeners.PlayerListener;
import com.songoda.epicenchants.listeners.item.BlackScrollListener;
import com.songoda.epicenchants.listeners.item.BookListener;
import com.songoda.epicenchants.listeners.item.DustListener;
import com.songoda.epicenchants.listeners.item.WhiteScrollListener;
import com.songoda.epicenchants.managers.*;
import com.songoda.epicenchants.objects.Enchant;
import com.songoda.epicenchants.utils.EnchantUtils;
import com.songoda.epicenchants.utils.Metrics;
import com.songoda.epicenchants.utils.ServerVersion;
import com.songoda.epicenchants.utils.SpecialItems;
import com.songoda.epicenchants.utils.locale.Locale;
import com.songoda.epicenchants.utils.objects.FastInv;
import com.songoda.epicenchants.utils.settings.Setting;
import com.songoda.epicenchants.utils.settings.SettingsManager;
import com.songoda.epicenchants.utils.single.ItemGroup;
import com.songoda.epicenchants.utils.updateModules.LocaleModule;
import com.songoda.update.Plugin;
import com.songoda.update.SongodaUpdate;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.Bukkit;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.stream.Collectors;
import static com.songoda.epicenchants.utils.single.GeneralUtils.color;
import static org.bukkit.Bukkit.getConsoleSender;
public class EpicEnchants extends JavaPlugin {
private static EpicEnchants INSTANCE;
private EnchantManager enchantManager;
private InfoManager infoManager;
private GroupManager groupManager;
private FileManager fileManager;
private HookManager hookManager;
private SettingsManager settingsManager;
private CommandManager commandManager;
private Locale locale;
private ServerVersion serverVersion = ServerVersion.fromPackageName(Bukkit.getServer().getClass().getPackage().getName());
private SpecialItems specialItems;
private Economy economy;
private EnchantUtils enchantUtils;
private ItemGroup itemGroup;
public static EpicEnchants getInstance() {
return INSTANCE;
}
@Override
public void onEnable() {
INSTANCE = this;
getConsoleSender().sendMessage(color("&a============================="));
getConsoleSender().sendMessage(color("&7" + getDescription().getName() + " " + getDescription().getVersion() + " by &5Songoda <3&7!"));
getConsoleSender().sendMessage(color("&7Action: &aEnabling&7..."));
// Setup Setting Manager
this.settingsManager = new SettingsManager(this);
this.settingsManager.setupConfig();
// Setup Language
new Locale(this, "en_US");
this.locale = Locale.getLocale(getConfig().getString("System.Language Mode"));
// Running Songoda Updater
Plugin plugin = new Plugin(this, 67);
plugin.addModule(new LocaleModule());
SongodaUpdate.load(plugin);
preload();
this.groupManager = new GroupManager(this);
this.enchantManager = new EnchantManager(this);
this.enchantUtils = new EnchantUtils(this);
this.infoManager = new InfoManager(this);
this.specialItems = new SpecialItems(this);
this.commandManager = new CommandManager(this);
this.hookManager = new HookManager();
this.itemGroup = new ItemGroup(this);
groupManager.loadGroups();
enchantManager.loadEnchants();
infoManager.loadMenus();
hookManager.setup();
PluginManager pluginManager = Bukkit.getPluginManager();
// Listeners
pluginManager.registerEvents(new BookListener(this), this);
pluginManager.registerEvents(new ArmorListener(), this);
pluginManager.registerEvents(new PlayerListener(this), this);
pluginManager.registerEvents(new EntityListener(this), this);
pluginManager.registerEvents(new WhiteScrollListener(this), this);
pluginManager.registerEvents(new BlackScrollListener(this), this);
pluginManager.registerEvents(new DustListener(this), this);
// Setup Economy
if (Setting.VAULT_ECONOMY.getBoolean() && pluginManager.isPluginEnabled("Vault"))
this.economy = new VaultEconomy();
else if (Setting.RESERVE_ECONOMY.getBoolean() && pluginManager.isPluginEnabled("Reserve"))
this.economy = new ReserveEconomy();
else if (Setting.PLAYER_POINTS_ECONOMY.getBoolean() && pluginManager.isPluginEnabled("PlayerPoints"))
this.economy = new PlayerPointsEconomy();
// Start Metrics
new Metrics(this);
if (!enchantManager.getValues().isEmpty()) {
getLogger().info("Successfully loaded enchants: " + enchantManager.getValues().stream().map(Enchant::getIdentifier).collect(Collectors.joining(", ")));
}
getConsoleSender().sendMessage(color("&a============================="));
}
private void preload() {
FastInv.init(this);
this.fileManager = new FileManager(this);
fileManager.loadFiles();
}
@Override
public void onDisable() {
getConsoleSender().sendMessage(color("&a============================="));
getConsoleSender().sendMessage(color("&7" + getDescription().getName() + " " + getDescription().getVersion() + " by &5Songoda <3&7!"));
getConsoleSender().sendMessage(color("&7Action: &cDisabling&7..."));
getConsoleSender().sendMessage(color("&a============================="));
}
public void reload() {
reloadConfig();
fileManager.clear();
fileManager.loadFiles();
groupManager.clear();
groupManager.loadGroups();
enchantManager.clear();
enchantManager.loadEnchants();
infoManager.clear();
infoManager.loadMenus();
this.locale = Locale.getLocale(getConfig().getString("System.Language Mode"));
this.locale.reloadMessages();
}
public ServerVersion getServerVersion() {
return serverVersion;
}
public boolean isServerVersion(ServerVersion version) {
return serverVersion == version;
}
public boolean isServerVersion(ServerVersion... versions) {
return ArrayUtils.contains(versions, serverVersion);
}
public boolean isServerVersionAtLeast(ServerVersion version) {
return serverVersion.ordinal() >= version.ordinal();
}
public EnchantManager getEnchantManager() {
return this.enchantManager;
}
public InfoManager getInfoManager() {
return this.infoManager;
}
public GroupManager getGroupManager() {
return this.groupManager;
}
public FileManager getFileManager() {
return this.fileManager;
}
public HookManager getHookManager() {
return this.hookManager;
}
public SpecialItems getSpecialItems() {
return this.specialItems;
}
public Economy getEconomy() {
return this.economy;
}
public EnchantUtils getEnchantUtils() {
return this.enchantUtils;
}
public ItemGroup getItemGroup() {
return this.itemGroup;
}
public Locale getLocale() {
return locale;
}
public CommandManager getCommandManager() {
return commandManager;
}
public SettingsManager getSettingsManager() {
return settingsManager;
}
}

View File

@ -0,0 +1,71 @@
package com.songoda.epicenchants.command;
import com.songoda.epicenchants.EpicEnchants;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public abstract class AbstractCommand {
private final boolean noConsole;
private AbstractCommand parent = null;
private boolean hasArgs = false;
private String command;
private List<String> subCommand = new ArrayList<>();
protected AbstractCommand(AbstractCommand parent, boolean noConsole, String... command) {
if (parent != null) {
this.subCommand = Arrays.asList(command);
} else {
this.command = Arrays.asList(command).get(0);
}
this.parent = parent;
this.noConsole = noConsole;
}
protected AbstractCommand(boolean noConsole, boolean hasArgs, String... command) {
this.command = Arrays.asList(command).get(0);
this.hasArgs = hasArgs;
this.noConsole = noConsole;
}
public AbstractCommand getParent() {
return parent;
}
public String getCommand() {
return command;
}
public List<String> getSubCommand() {
return subCommand;
}
public void addSubCommand(String command) {
subCommand.add(command);
}
protected abstract ReturnType runCommand(EpicEnchants instance, CommandSender sender, String... args);
protected abstract List<String> onTab(EpicEnchants instance, CommandSender sender, String... args);
public abstract String getPermissionNode();
public abstract String getSyntax();
public abstract String getDescription();
public boolean hasArgs() {
return hasArgs;
}
public boolean isNoConsole() {
return noConsole;
}
public enum ReturnType {SUCCESS, FAILURE, SYNTAX_ERROR}
}

View File

@ -0,0 +1,93 @@
package com.songoda.epicenchants.command;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.command.commands.*;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CommandManager implements CommandExecutor {
private static final List<AbstractCommand> commands = new ArrayList<>();
private EpicEnchants plugin;
private TabManager tabManager;
public CommandManager(EpicEnchants plugin) {
this.plugin = plugin;
this.tabManager = new TabManager(this);
plugin.getCommand("EpicEnchants").setExecutor(this);
AbstractCommand commandEpicEnchants = addCommand(new CommandEpicEnchants());
addCommand(new CommandSettings(commandEpicEnchants));
addCommand(new CommandReload(commandEpicEnchants));
addCommand(new CommandApply(commandEpicEnchants));
addCommand(new CommandList(commandEpicEnchants));
addCommand(new CommandGiveBook(commandEpicEnchants));
addCommand(new CommandGiveRandomBook(commandEpicEnchants));
addCommand(new CommandGiveItemDust(commandEpicEnchants));
addCommand(new CommandGiveScroll(commandEpicEnchants));
addCommand(new CommandAlchemist(commandEpicEnchants));
addCommand(new CommandEnchanter(commandEpicEnchants));
addCommand(new CommandTinkerer(commandEpicEnchants));
for (AbstractCommand abstractCommand : commands) {
if (abstractCommand.getParent() != null) continue;
plugin.getCommand(abstractCommand.getCommand()).setTabCompleter(tabManager);
}
}
private AbstractCommand addCommand(AbstractCommand abstractCommand) {
commands.add(abstractCommand);
return abstractCommand;
}
@Override
public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) {
for (AbstractCommand abstractCommand : commands) {
if (abstractCommand.getCommand() != null && abstractCommand.getCommand().equalsIgnoreCase(command.getName().toLowerCase())) {
if (strings.length == 0 || abstractCommand.hasArgs()) {
processRequirements(abstractCommand, commandSender, strings);
return true;
}
} else if (strings.length != 0 && abstractCommand.getParent() != null && abstractCommand.getParent().getCommand().equalsIgnoreCase(command.getName())) {
String cmd = strings[0];
String cmd2 = strings.length >= 2 ? String.join(" ", strings[0], strings[1]) : null;
for (String cmds : abstractCommand.getSubCommand()) {
if (cmd.equalsIgnoreCase(cmds) || (cmd2 != null && cmd2.equalsIgnoreCase(cmds))) {
processRequirements(abstractCommand, commandSender, strings);
return true;
}
}
}
}
plugin.getLocale().newMessage("&7The command you entered does not exist or is spelt incorrectly.").sendPrefixedMessage(commandSender);
return true;
}
private void processRequirements(AbstractCommand command, CommandSender sender, String[] strings) {
if (!(sender instanceof Player) && command.isNoConsole()) {
sender.sendMessage("You must be a player to use this commands.");
return;
}
if (command.getPermissionNode() == null || sender.hasPermission(command.getPermissionNode())) {
AbstractCommand.ReturnType returnType = command.runCommand(plugin, sender, strings);
if (returnType == AbstractCommand.ReturnType.SYNTAX_ERROR) {
plugin.getLocale().newMessage("&cInvalid Syntax!").sendPrefixedMessage(sender);
plugin.getLocale().newMessage("&7The valid syntax is: &6" + command.getSyntax() + "&7.").sendPrefixedMessage(sender);
}
return;
}
plugin.getLocale().getMessage("event.general.nopermission").sendPrefixedMessage(sender);
}
public List<AbstractCommand> getCommands() {
return Collections.unmodifiableList(commands);
}
}

View File

@ -0,0 +1,52 @@
package com.songoda.epicenchants.command;
import com.songoda.epicenchants.EpicEnchants;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import java.util.ArrayList;
import java.util.List;
public class TabManager implements TabCompleter {
private final CommandManager commandManager;
TabManager(CommandManager commandManager) {
this.commandManager = commandManager;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] strings) {
for (AbstractCommand abstractCommand : commandManager.getCommands()) {
if (abstractCommand.getCommand() != null && abstractCommand.getCommand().equalsIgnoreCase(command.getName().toLowerCase())) {
if (strings.length == 1) {
List<String> subs = new ArrayList<>();
for (AbstractCommand ac : commandManager.getCommands()) {
if (ac.getSubCommand() == null) continue;
subs.addAll(ac.getSubCommand());
}
subs.removeIf(s -> !s.toLowerCase().startsWith(strings[0].toLowerCase()));
return subs;
}
} else if (strings.length != 0 && abstractCommand.getParent() != null && abstractCommand.getParent().getCommand().equalsIgnoreCase(command.getName().toLowerCase())) {
String cmd = strings[0];
String cmd2 = strings.length >= 2 ? String.join(" ", strings[0], strings[1]) : null;
for (String cmds : abstractCommand.getSubCommand()) {
if (cmd.equalsIgnoreCase(cmds) || (cmd2 != null && cmd2.equalsIgnoreCase(cmds))) {
List<String> list = abstractCommand.onTab(EpicEnchants.getInstance(), sender, strings);
String str = strings[strings.length - 1];
if (list != null && str != null && str.length() >= 1) {
try {
list.removeIf(s -> !s.toLowerCase().startsWith(str.toLowerCase()));
} catch (UnsupportedOperationException ignored) {
}
}
return list;
}
}
}
}
return null;
}
}

View File

@ -0,0 +1,44 @@
package com.songoda.epicenchants.command.commands;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.command.AbstractCommand;
import com.songoda.epicenchants.menus.AlchemistMenu;
import com.songoda.epicenchants.menus.TinkererMenu;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class CommandAlchemist extends AbstractCommand {
public CommandAlchemist(AbstractCommand parent) {
super(parent, true, "alchemist");
}
@Override
protected ReturnType runCommand(EpicEnchants instance, CommandSender sender, String... args) {
Player player = (Player)sender;
new AlchemistMenu(instance, instance.getFileManager().getConfiguration("menus/alchemist-menu")).open(player);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(EpicEnchants instance, CommandSender sender, String... args) {
return null;
}
@Override
public String getPermissionNode() {
return "epicenchants.alchemist";
}
@Override
public String getSyntax() {
return "/ee alchemist";
}
@Override
public String getDescription() {
return "Opens the Alchemist.";
}
}

View File

@ -0,0 +1,125 @@
package com.songoda.epicenchants.command.commands;
import com.songoda.epicenchants.CommandCommons;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.command.AbstractCommand;
import com.songoda.epicenchants.enums.EnchantResult;
import com.songoda.epicenchants.objects.Enchant;
import com.songoda.epicenchants.utils.Tuple;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.songoda.epicenchants.enums.EnchantResult.BROKEN_FAILURE;
import static com.songoda.epicenchants.utils.single.GeneralUtils.getMessageFromResult;
public class CommandApply extends AbstractCommand {
public CommandApply(AbstractCommand parent) {
super(parent, true, "apply");
}
//ee apply [enchant] [level] <success-rate> <destroy-rate>
@Override
protected ReturnType runCommand(EpicEnchants instance, CommandSender sender, String... args) {
if (args.length < 3 || args.length > 5)
return ReturnType.SYNTAX_ERROR;
Optional<Enchant> optionalEnchant = instance.getEnchantManager().getValue(args[1].replaceAll("_", " "));
if (!optionalEnchant.isPresent()) {
instance.getLocale().newMessage("&cNo enchants exist with that name...").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
if (!CommandCommons.isInt(args[2], sender))
return ReturnType.FAILURE;
int successRate = 100;
int destroyRate = 0;
if (args.length > 3) {
if (!CommandCommons.isInt(args[3], sender))
return ReturnType.FAILURE;
successRate = Integer.parseInt(args[3]);
}
if (args.length > 4) {
if (!CommandCommons.isInt(args[4], sender))
return ReturnType.FAILURE;
destroyRate = Integer.parseInt(args[4]);
}
Enchant enchant = optionalEnchant.get();
int level = Integer.parseInt(args[2]);
Player player = (Player) sender;
if (!enchant.getItemWhitelist().contains(player.getItemInHand().getType())) {
System.out.println("List = " + enchant.getItemWhitelist());
instance.getLocale().getMessage("command.apply.invaliditem")
.processPlaceholder("enchant", enchant.getIdentifier())
.sendPrefixedMessage(player);
return ReturnType.FAILURE;
}
int slot = player.getInventory().getHeldItemSlot();
ItemStack before = player.getItemInHand();
Tuple<ItemStack, EnchantResult> result = instance.getEnchantUtils().apply(before, enchant, level,
successRate, destroyRate);
instance.getLocale().getMessage(getMessageFromResult(result.getRight()))
.processPlaceholder("enchant", enchant.getIdentifier())
.sendPrefixedMessage(player);
if (result.getRight() == BROKEN_FAILURE) {
player.getInventory().clear(slot);
return ReturnType.FAILURE;
}
player.getInventory().setItem(slot, result.getLeft());
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(EpicEnchants instance, CommandSender sender, String... args) {
if (args.length == 2) {
return instance.getEnchantManager().getValues()
.stream().map(Enchant::getIdentifier).collect(Collectors.toList());
} else if (args.length == 3) {
Enchant enchant = instance.getEnchantManager().getValues()
.stream().findFirst().orElse(null);
List<String> levels = new ArrayList<>();
if (enchant != null) {
for (int i = 1; i <= enchant.getMaxLevel(); i ++)
levels.add(String.valueOf(i));
}
return levels;
} else if (args.length == 4 || args.length == 5) {
List<String> rates = new ArrayList<>();
for (int i = 1; i <= 100; i ++)
rates.add(String.valueOf(i));
return rates;
}
return null;
}
@Override
public String getPermissionNode() {
return "epicenchants.apply";
}
@Override
public String getSyntax() {
return "/ee apply <enchant> <level> [success-rate] [destroy-rate]";
}
@Override
public String getDescription() {
return "Apply an enchant to the item in hand.";
}
}

View File

@ -0,0 +1,43 @@
package com.songoda.epicenchants.command.commands;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.command.AbstractCommand;
import com.songoda.epicenchants.menus.EnchanterMenu;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class CommandEnchanter extends AbstractCommand {
public CommandEnchanter(AbstractCommand parent) {
super(parent, true, "enchanter");
}
@Override
protected ReturnType runCommand(EpicEnchants instance, CommandSender sender, String... args) {
Player player = (Player)sender;
new EnchanterMenu(instance, instance.getFileManager().getConfiguration("menus/enchanter-menu"), player).open(player);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(EpicEnchants instance, CommandSender sender, String... args) {
return null;
}
@Override
public String getPermissionNode() {
return "epicenchants.enchanter";
}
@Override
public String getSyntax() {
return "/ee enchanter";
}
@Override
public String getDescription() {
return "Opens the Enchanter.";
}
}

View File

@ -0,0 +1,51 @@
package com.songoda.epicenchants.command.commands;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.command.AbstractCommand;
import com.songoda.epicenchants.utils.Methods;
import org.bukkit.command.CommandSender;
import java.util.List;
public class CommandEpicEnchants extends AbstractCommand {
public CommandEpicEnchants() {
super(null, false, "EpicEnchants");
}
@Override
protected AbstractCommand.ReturnType runCommand(EpicEnchants instance, CommandSender sender, String... args) {
sender.sendMessage("");
instance.getLocale().newMessage("&7Version " + instance.getDescription().getVersion()
+ " Created with <3 by &5&l&oSongoda").sendPrefixedMessage(sender);
for (AbstractCommand command : instance.getCommandManager().getCommands()) {
if (command.getPermissionNode() == null || sender.hasPermission(command.getPermissionNode())) {
sender.sendMessage(Methods.formatText("&8 - &a" + command.getSyntax() + "&7 - " + command.getDescription()));
}
}
sender.sendMessage("");
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(EpicEnchants instance, CommandSender sender, String... args) {
return null;
}
@Override
public String getPermissionNode() {
return null;
}
@Override
public String getSyntax() {
return "/EpicEnchants";
}
@Override
public String getDescription() {
return "Displays this page.";
}
}

View File

@ -0,0 +1,124 @@
package com.songoda.epicenchants.command.commands;
import com.songoda.epicenchants.CommandCommons;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.command.AbstractCommand;
import com.songoda.epicenchants.objects.Enchant;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class CommandGiveBook extends AbstractCommand {
public CommandGiveBook(AbstractCommand parent) {
super(parent, false, "givebook");
}
//ee givebook <player> <enchant> [level] [success-rate] [destroy-rate]
@Override
protected ReturnType runCommand(EpicEnchants instance, CommandSender sender, String... args) {
if (args.length < 3 || args.length > 6)
return ReturnType.SYNTAX_ERROR;
OfflinePlayer target = Bukkit.getPlayer(args[1]);
if (target == null) {
instance.getLocale().newMessage("&cThis player does not exist...").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
Optional<Enchant> optionalEnchant = instance.getEnchantManager().getValue(args[2].replaceAll("_", " "));
if (!optionalEnchant.isPresent()) {
instance.getLocale().newMessage("&cNo enchants exist with that name...").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
Enchant enchant = optionalEnchant.get();
int level = -1;
int successRate = -1;
int destroyRate = -1;
if (args.length > 3) {
if (!CommandCommons.isInt(args[3], sender))
return ReturnType.FAILURE;
level = Integer.parseInt(args[3]);
}
if (args.length > 4) {
if (!CommandCommons.isInt(args[4], sender))
return ReturnType.FAILURE;
successRate = Integer.parseInt(args[4]);
}
if (args.length > 5) {
if (!CommandCommons.isInt(args[5], sender))
return ReturnType.FAILURE;
destroyRate = Integer.parseInt(args[5]);
}
if (level != -1 && (level > enchant.getMaxLevel() || level < 1)) {
instance.getLocale().getMessage("command.book." + (level > enchant.getMaxLevel() ? "maxlevel" : "minlevel"))
.processPlaceholder("enchant", enchant.getIdentifier())
.processPlaceholder("max_level", enchant.getMaxLevel())
.sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
}
target.getPlayer().getInventory().addItem(enchant.getBook().get(enchant, level, successRate, destroyRate));
instance.getLocale().getMessage("command.book.received")
.processPlaceholder("enchant", enchant.getIdentifier())
.sendPrefixedMessage(target.getPlayer());
instance.getLocale().getMessage("command.book.gave")
.processPlaceholder("player", target.getPlayer().getName())
.processPlaceholder("enchant", enchant.getIdentifier())
.sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(EpicEnchants instance, CommandSender sender, String... args) {
if (args.length == 2) {
return Bukkit.getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList());
} else if (args.length == 3) {
return instance.getEnchantManager().getValues()
.stream().map(Enchant::getIdentifier).collect(Collectors.toList());
} else if (args.length == 4) {
Enchant enchant = instance.getEnchantManager().getValues()
.stream().findFirst().orElse(null);
List<String> levels = new ArrayList<>();
if (enchant != null) {
for (int i = 1; i <= enchant.getMaxLevel(); i ++)
levels.add(String.valueOf(i));
}
return levels;
} else if (args.length == 5 || args.length == 6) {
List<String> rates = new ArrayList<>();
for (int i = 1; i <= 100; i ++)
rates.add(String.valueOf(i));
return rates;
}
return null;
}
@Override
public String getPermissionNode() {
return "epicenchants.givebook";
}
@Override
public String getSyntax() {
return "/ee givebook <player> <enchant> [level] [success-rate] [destroy-rate]";
}
@Override
public String getDescription() {
return "Give enchant books to players.";
}
}

View File

@ -0,0 +1,108 @@
package com.songoda.epicenchants.command.commands;
import com.songoda.epicenchants.CommandCommons;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.command.AbstractCommand;
import com.songoda.epicenchants.objects.Enchant;
import com.songoda.epicenchants.objects.Group;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class CommandGiveItemDust extends AbstractCommand {
public CommandGiveItemDust(AbstractCommand parent) {
super(parent, false, "giveitemdust");
}
//ee giveitemdust <player> <group> [type] [percentage]
@Override
protected ReturnType runCommand(EpicEnchants instance, CommandSender sender, String... args) {
if (args.length < 3 || args.length > 6)
return ReturnType.SYNTAX_ERROR;
OfflinePlayer target = Bukkit.getPlayer(args[1]);
if (target == null) {
instance.getLocale().newMessage("&cThis player does not exist...").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
List<Group> groups = instance.getGroupManager().getValues().stream()
.filter(group -> group.getIdentifier().equalsIgnoreCase(args[2])).collect(Collectors.toList());
if (groups.isEmpty()) {
instance.getLocale().newMessage("&cThe group you entered was no found...").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
Group group = groups.get(0);
String dustType = null;
int percentage = -1;
if (args.length > 3) {
dustType = args[3];
}
if (args.length > 4) {
if (!CommandCommons.isInt(args[4], sender))
return ReturnType.FAILURE;
percentage = Integer.parseInt(args[4]);
}
target.getPlayer().getInventory().addItem(instance.getSpecialItems().getDust(group, dustType, percentage, true));
instance.getLocale().getMessage("command.dust.received")
.processPlaceholder("group", group.getIdentifier())
.sendPrefixedMessage(target.getPlayer());
instance.getLocale().getMessage("command.dust.gave")
.processPlaceholder("player", target.getPlayer().getName())
.processPlaceholder("group", group.getIdentifier())
.sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(EpicEnchants instance, CommandSender sender, String... args) {
if (args.length == 2) {
return Bukkit.getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList());
} else if (args.length == 3) {
return instance.getGroupManager().getValues().stream()
.map(Group::getIdentifier).collect(Collectors.toList());
} else if (args.length == 4) {
List<String> dusts = new ArrayList<>();
FileConfiguration dustConfig = instance.getFileManager().getConfiguration("items/dusts");
dusts.addAll(dustConfig.getConfigurationSection("dusts").getKeys(false));
return dusts;
} else if (args.length == 5) {
List<String> rates = new ArrayList<>();
for (int i = 1; i <= 100; i ++)
rates.add(String.valueOf(i));
return rates;
}
return null;
}
@Override
public String getPermissionNode() {
return "epicenchants.giveitemdust";
}
@Override
public String getSyntax() {
return "/ee giveitemdust <player> <group> [type] [percentage]";
}
@Override
public String getDescription() {
return "Give item dust.";
}
}

View File

@ -0,0 +1,78 @@
package com.songoda.epicenchants.command.commands;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.command.AbstractCommand;
import com.songoda.epicenchants.objects.Group;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
import java.util.stream.Collectors;
public class CommandGiveRandomBook extends AbstractCommand {
public CommandGiveRandomBook(AbstractCommand parent) {
super(parent, false, "giverandombook");
}
//ee giverandombook <player> <group>
@Override
protected ReturnType runCommand(EpicEnchants instance, CommandSender sender, String... args) {
if (args.length < 3 || args.length > 6)
return ReturnType.SYNTAX_ERROR;
OfflinePlayer target = Bukkit.getPlayer(args[1]);
if (target == null) {
instance.getLocale().newMessage("&cThis player does not exist...").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
List<Group> groups = instance.getGroupManager().getValues().stream()
.filter(group -> group.getIdentifier().equalsIgnoreCase(args[2])).collect(Collectors.toList());
if (groups.isEmpty()) {
instance.getLocale().newMessage("&cThe group you entered was no found...").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
Group group = groups.get(0);
target.getPlayer().getInventory().addItem(instance.getSpecialItems().getMysteryBook(group));
instance.getLocale().getMessage("command.randombook.received")
.sendPrefixedMessage(target.getPlayer());
instance.getLocale().getMessage("command.randombook.gave")
.processPlaceholder("player", target.getPlayer().getName())
.sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(EpicEnchants instance, CommandSender sender, String... args) {
if (args.length == 2) {
return Bukkit.getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList());
} else if (args.length == 3) {
return instance.getGroupManager().getValues().stream()
.map(Group::getIdentifier).collect(Collectors.toList());
}
return null;
}
@Override
public String getPermissionNode() {
return "epicenchants.giverandombook";
}
@Override
public String getSyntax() {
return "/ee giverandombook <player> <group>";
}
@Override
public String getDescription() {
return "Give random enchant books to players.";
}
}

View File

@ -0,0 +1,107 @@
package com.songoda.epicenchants.command.commands;
import com.songoda.epicenchants.CommandCommons;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.command.AbstractCommand;
import com.songoda.epicenchants.objects.Enchant;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CommandGiveScroll extends AbstractCommand {
public CommandGiveScroll(AbstractCommand parent) {
super(parent, false, "givescroll");
}
//ee givescroll <giveType> <player> [amount] [success-rate]
@Override
protected ReturnType runCommand(EpicEnchants instance, CommandSender sender, String... args) {
if (args.length < 3 || args.length > 6)
return ReturnType.SYNTAX_ERROR;
String giveType = args[1];
OfflinePlayer target = Bukkit.getPlayer(args[2]);
if (target == null) {
instance.getLocale().newMessage("&cThis player does not exist...").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
int amount = 1;
int successRate = -1;
if (args.length > 3) {
if (!CommandCommons.isInt(args[3], sender))
return ReturnType.FAILURE;
amount = Integer.parseInt(args[3]);
}
if (args.length > 4) {
if (!CommandCommons.isInt(args[4], sender))
return ReturnType.FAILURE;
successRate = Integer.parseInt(args[4]);
}
String messageKey;
switch (giveType.toLowerCase()) {
case "whitescroll":
target.getPlayer().getInventory().addItem(instance.getSpecialItems().getWhiteScroll(amount));
messageKey = "whitescroll";
break;
case "blackscroll":
messageKey = "blackscroll";
target.getPlayer().getInventory().addItem(instance.getSpecialItems().getBlackScroll(amount, successRate));
break;
default:
instance.getLocale().getMessage("command.giveunknown")
.processPlaceholder("unknown", giveType)
.sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
instance.getLocale().getMessage("command." + messageKey + ".received")
.sendPrefixedMessage(target.getPlayer());
instance.getLocale().getMessage("command." + messageKey + ".gave")
.processPlaceholder("player", target.getName())
.sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(EpicEnchants instance, CommandSender sender, String... args) {
if (args.length == 2) {
return Arrays.asList("whitescroll", "blackscroll");
} else if (args.length == 3) {
return Bukkit.getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList());
} else if (args.length == 4 || args.length == 5) {
List<String> rates = new ArrayList<>();
for (int i = 1; i <= (args.length == 4 ? 10 : 100); i ++)
rates.add(String.valueOf(i));
return rates;
}
return null;
}
@Override
public String getPermissionNode() {
return "epicenchants.givescroll";
}
@Override
public String getSyntax() {
return "/ee givescroll <whitescroll/blackscroll> <player> [amount] [success-rate]";
}
@Override
public String getDescription() {
return "Give enchant scrolls to players.";
}
}

View File

@ -0,0 +1,59 @@
package com.songoda.epicenchants.command.commands;
import com.songoda.epicenchants.CommandCommons;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.command.AbstractCommand;
import com.songoda.epicenchants.enums.EnchantResult;
import com.songoda.epicenchants.objects.Enchant;
import com.songoda.epicenchants.utils.Tuple;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.songoda.epicenchants.enums.EnchantResult.BROKEN_FAILURE;
import static com.songoda.epicenchants.utils.single.GeneralUtils.getMessageFromResult;
public class CommandList extends AbstractCommand {
public CommandList(AbstractCommand parent) {
super(parent, true, "list");
}
@Override
protected ReturnType runCommand(EpicEnchants instance, CommandSender sender, String... args) {
if (args.length > 1 && args[1].equalsIgnoreCase("chat")) {
instance.getLocale().newMessage(instance.getEnchantManager().getValues().stream()
.sorted(Comparator.comparing(enchant -> enchant.getGroup().getOrder()))
.map(enchant -> enchant.getColoredIdentifier(true)).collect(Collectors.joining("&7, ")))
.sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
}
instance.getInfoManager().getMainInfoMenu().open((Player)sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(EpicEnchants instance, CommandSender sender, String... args) {
return null;
}
@Override
public String getPermissionNode() {
return "epicenchants.list";
}
@Override
public String getSyntax() {
return "/ee list [chat]";
}
@Override
public String getDescription() {
return "List all enchants with their description.";
}
}

View File

@ -0,0 +1,41 @@
package com.songoda.epicenchants.command.commands;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.command.AbstractCommand;
import org.bukkit.command.CommandSender;
import java.util.List;
public class CommandReload extends AbstractCommand {
public CommandReload(AbstractCommand parent) {
super(parent, false, "reload");
}
@Override
protected AbstractCommand.ReturnType runCommand(EpicEnchants instance, CommandSender sender, String... args) {
instance.reload();
instance.getLocale().getMessage("command.reload").sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(EpicEnchants instance, CommandSender sender, String... args) {
return null;
}
@Override
public String getPermissionNode() {
return "epicenchants.reload";
}
@Override
public String getSyntax() {
return "/ee reload";
}
@Override
public String getDescription() {
return "Reload the Configuration files.";
}
}

View File

@ -0,0 +1,41 @@
package com.songoda.epicenchants.command.commands;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.command.AbstractCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class CommandSettings extends AbstractCommand {
public CommandSettings(AbstractCommand parent) {
super(parent, true, "Settings");
}
@Override
protected ReturnType runCommand(EpicEnchants instance, CommandSender sender, String... args) {
instance.getSettingsManager().openSettingsManager((Player) sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(EpicEnchants instance, CommandSender sender, String... args) {
return null;
}
@Override
public String getPermissionNode() {
return "epicenchants.admin";
}
@Override
public String getSyntax() {
return "/ee settings";
}
@Override
public String getDescription() {
return "Edit the EpicEnchants Settings.";
}
}

View File

@ -0,0 +1,44 @@
package com.songoda.epicenchants.command.commands;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.command.AbstractCommand;
import com.songoda.epicenchants.menus.EnchanterMenu;
import com.songoda.epicenchants.menus.TinkererMenu;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class CommandTinkerer extends AbstractCommand {
public CommandTinkerer(AbstractCommand parent) {
super(parent, true, "tinkerer");
}
@Override
protected ReturnType runCommand(EpicEnchants instance, CommandSender sender, String... args) {
Player player = (Player)sender;
new TinkererMenu(instance, instance.getFileManager().getConfiguration("menus/tinkerer-menu")).open(player);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(EpicEnchants instance, CommandSender sender, String... args) {
return null;
}
@Override
public String getPermissionNode() {
return "epicenchants.tinkerer";
}
@Override
public String getSyntax() {
return "/ee tinkerer";
}
@Override
public String getDescription() {
return "Opens the Tinkerer.";
}
}

View File

@ -0,0 +1,15 @@
package com.songoda.epicenchants.economy;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public interface Economy {
boolean hasBalance(OfflinePlayer player, double cost);
double getBalance(Player player);
boolean withdrawBalance(OfflinePlayer player, double cost);
boolean deposit(OfflinePlayer player, double amount);
}

View File

@ -0,0 +1,44 @@
package com.songoda.epicenchants.economy;
import org.black_ixx.playerpoints.PlayerPoints;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public class PlayerPointsEconomy implements Economy {
private final PlayerPoints playerPoints;
public PlayerPointsEconomy() {
this.playerPoints = (PlayerPoints) Bukkit.getServer().getPluginManager().getPlugin("PlayerPoints");
}
private int convertAmount(double amount) {
return (int) Math.ceil(amount);
}
@Override
public boolean hasBalance(OfflinePlayer player, double cost) {
int amount = convertAmount(cost);
return playerPoints.getAPI().look(player.getUniqueId()) >= amount;
}
@Override
public double getBalance(Player player) {
return playerPoints.getAPI().look(player.getUniqueId());
}
@Override
public boolean withdrawBalance(OfflinePlayer player, double cost) {
int amount = convertAmount(cost);
return playerPoints.getAPI().take(player.getUniqueId(), amount);
}
@Override
public boolean deposit(OfflinePlayer player, double amount) {
int amt = convertAmount(amount);
return playerPoints.getAPI().give(player.getUniqueId(), amt);
}
}

View File

@ -0,0 +1,38 @@
package com.songoda.epicenchants.economy;
import net.tnemc.core.Reserve;
import net.tnemc.core.economy.EconomyAPI;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import java.math.BigDecimal;
public class ReserveEconomy implements Economy {
EconomyAPI economyAPI;
public ReserveEconomy() {
if (Reserve.instance().economyProvided())
economyAPI = Reserve.instance().economy();
}
@Override
public boolean hasBalance(OfflinePlayer player, double cost) {
return economyAPI.hasHoldings(player.getUniqueId(), new BigDecimal(cost));
}
@Override
public double getBalance(Player player) {
return economyAPI.getHoldings(player.getUniqueId()).doubleValue();
}
@Override
public boolean withdrawBalance(OfflinePlayer player, double cost) {
return economyAPI.removeHoldings(player.getUniqueId(), new BigDecimal(cost));
}
@Override
public boolean deposit(OfflinePlayer player, double amount) {
return economyAPI.addHoldings(player.getUniqueId(), new BigDecimal(amount));
}
}

View File

@ -0,0 +1,34 @@
package com.songoda.epicenchants.economy;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public class VaultEconomy implements Economy {
private final net.milkbowl.vault.economy.Economy vault;
public VaultEconomy() {
this.vault = Bukkit.getServicesManager().
getRegistration(net.milkbowl.vault.economy.Economy.class).getProvider();
}
@Override
public boolean hasBalance(OfflinePlayer player, double cost) {
return vault.has(player, cost);
}
@Override
public double getBalance(Player player) {
return vault.getBalance(player);
}
@Override
public boolean withdrawBalance(OfflinePlayer player, double cost) {
return vault.withdrawPlayer(player, cost).transactionSuccess();
}
@Override
public boolean deposit(OfflinePlayer player, double amount) {
return vault.depositPlayer(player, amount).transactionSuccess();
}
}

View File

@ -5,7 +5,6 @@ import com.songoda.epicenchants.enums.TriggerType;
import com.songoda.epicenchants.objects.Condition;
import com.songoda.epicenchants.objects.LeveledModifier;
import com.songoda.epicenchants.utils.single.GeneralUtils;
import lombok.Getter;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
@ -19,11 +18,12 @@ import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static com.songoda.epicenchants.effect.EffectExecutor.Who.*;
import static com.songoda.epicenchants.effect.EffectExecutor.Who.OPPONENT;
import static com.songoda.epicenchants.effect.EffectExecutor.Who.USER;
public abstract class EffectExecutor {
@Getter private final ConfigurationSection section;
@Getter private final Set<TriggerType> triggerTypes;
private final ConfigurationSection section;
private final Set<TriggerType> triggerTypes;
private final Set<EffectExecutor> simultaneous;
private final Condition condition;
@ -96,6 +96,14 @@ public abstract class EffectExecutor {
}
}
public ConfigurationSection getSection() {
return this.section;
}
public Set<TriggerType> getTriggerTypes() {
return this.triggerTypes;
}
public enum Who {
USER, OPPONENT
}

View File

@ -7,7 +7,8 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;
import static com.google.common.base.CaseFormat.*;
import static com.google.common.base.CaseFormat.UPPER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;
public class EffectManager {

View File

@ -0,0 +1,29 @@
package com.songoda.epicenchants.effect.effects;
import com.songoda.epicenchants.effect.EffectExecutor;
import com.songoda.epicenchants.enums.EventType;
import com.songoda.epicenchants.utils.objects.ItemBuilder;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class DropHeld extends EffectExecutor {
public DropHeld(ConfigurationSection section) {
super(section);
}
@Override
public void execute(@NotNull Player user, @Nullable LivingEntity opponent, int level, EventType eventType) {
consume(entity -> {
Player player = ((Player) entity);
if (player.getItemInHand().getType() != Material.AIR) {
entity.getLocation().getWorld().dropItemNaturally(entity.getLocation(), new ItemBuilder(player
.getItemInHand()).build());
player.setItemInHand(null);
}
}, user, opponent);
}
}

View File

@ -10,7 +10,8 @@ import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import static com.songoda.epicenchants.effect.EffectExecutor.Who.OPPONENT;
import static com.songoda.epicenchants.enums.EventType.*;
import static com.songoda.epicenchants.enums.EventType.NONE;
import static com.songoda.epicenchants.enums.EventType.ON;
public class PlayerCommand extends EffectExecutor {
public PlayerCommand(ConfigurationSection section) {

View File

@ -3,11 +3,11 @@ package com.songoda.epicenchants.effect.effects;
import com.songoda.epicenchants.effect.EffectExecutor;
import com.songoda.epicenchants.enums.EventType;
import com.songoda.epicenchants.objects.LeveledModifier;
import com.songoda.epicenchants.utils.itemnbtapi.NBTEntity;
import com.songoda.epicenchants.utils.itemnbtapi.NBTList;
import com.songoda.epicenchants.utils.itemnbtapi.NBTListCompound;
import com.songoda.epicenchants.utils.itemnbtapi.NBTType;
import com.songoda.epicenchants.utils.objects.ItemBuilder;
import de.tr7zw.itemnbtapi.NBTEntity;
import de.tr7zw.itemnbtapi.NBTList;
import de.tr7zw.itemnbtapi.NBTListCompound;
import de.tr7zw.itemnbtapi.NBTType;
import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.*;

View File

@ -8,7 +8,8 @@ import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.songoda.epicenchants.utils.single.Experience.*;
import static com.songoda.epicenchants.utils.single.Experience.changeExp;
import static com.songoda.epicenchants.utils.single.Experience.getExp;
public class StealExp extends EffectExecutor {
public StealExp(ConfigurationSection section) {

View File

@ -0,0 +1,37 @@
package com.songoda.epicenchants.effect.effects;
import com.songoda.epicenchants.effect.EffectExecutor;
import com.songoda.epicenchants.enums.EventType;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class StealFood extends EffectExecutor {
public StealFood(ConfigurationSection section) {
super(section);
}
@Override
public void execute(@NotNull Player user, LivingEntity opponent, int level, EventType eventType) {
int amount = (int)Math.floor(getAmount().get(level, 0, user, opponent));
if (!(opponent instanceof Player)) {
return;
}
Player opponentPlayer = ((Player) opponent);
int opponentFood = opponentPlayer.getFoodLevel() - amount;
int userFood = user.getFoodLevel() + amount;
if (opponentFood <= 0) {
opponentPlayer.setFoodLevel(0);
} else opponentPlayer.setFoodLevel(Math.min(opponentFood, 20));
if (userFood <= 0) {
user.setFoodLevel(0);
} else user.setFoodLevel(Math.min(userFood, 20));
}
}

View File

@ -29,7 +29,8 @@ public class Throw extends EffectExecutor {
Vector vector;
double magnitude = LeveledModifier.of(getSection().getString("magnitude")).get(level, 0.1, user, opponent);
LivingEntity livingEntity = who() == USER ? user : opponent;
LivingEntity relative = getSection().getString("relative-to").equalsIgnoreCase("opponent") ? opponent : user;
String relativeToStr = getSection().getString("relative-to");
LivingEntity relative = relativeToStr == null || relativeToStr.equalsIgnoreCase("user") ? user : opponent;
switch (getSection().getString("direction").toLowerCase()) {
case "up":

View File

@ -20,13 +20,18 @@ public enum TriggerType {
EXPLOSION_DAMAGE,
FALL_DAMAGE,
FIRE_DAMAGE,
LAVA_DAMAGE,
POISON_DAMAGE,
HELD_ITEM,
STATIC_EFFECT,
BLOCK_BREAK,
REPEATING,
EXPERIENCE_BLOCK_BREAK,
RIGHT_CLICK_BLOCK,
LEFT_CLICK_BLOCK,
REPEATING, //TODO: Figure out what this is.
RIGHT_CLICK,
LEFT_CLICK
}

View File

@ -1,13 +1,11 @@
package com.songoda.epicenchants.events;
import com.songoda.epicenchants.objects.Enchant;
import lombok.Getter;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack;
@Getter
public class EnchantApplyEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final ItemStack toEnchant;
@ -43,4 +41,24 @@ public class EnchantApplyEvent extends Event implements Cancellable {
public HandlerList getHandlers() {
return handlers;
}
public ItemStack getToEnchant() {
return this.toEnchant;
}
public Enchant getEnchant() {
return this.enchant;
}
public int getLevel() {
return this.level;
}
public int getSuccessRate() {
return this.successRate;
}
public int getDestroyRate() {
return this.destroyRate;
}
}

View File

@ -2,7 +2,7 @@ package com.songoda.epicenchants.listeners;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.enums.TriggerType;
import de.tr7zw.itemnbtapi.NBTEntity;
import com.songoda.epicenchants.utils.itemnbtapi.NBTEntity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
@ -103,6 +103,9 @@ public class EntityListener implements Listener {
case FIRE_TICK:
instance.getEnchantUtils().handlePlayer(((Player) event.getEntity()), null, event, FIRE_DAMAGE);
break;
case LAVA:
instance.getEnchantUtils().handlePlayer(((Player) event.getEntity()), null, event, LAVA_DAMAGE);
break;
case BLOCK_EXPLOSION:
case ENTITY_EXPLOSION:
instance.getEnchantUtils().handlePlayer(((Player) event.getEntity()), null, event, EXPLOSION_DAMAGE);
@ -127,7 +130,7 @@ public class EntityListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onEntityExplode(EntityExplodeEvent event) {
if (event.getEntity().getCustomName().equals("ee")) {
if (event.getEntity().getCustomName() != null && event.getEntity().getCustomName().equals("ee")) {
event.blockList().clear();
}
}

View File

@ -16,7 +16,8 @@ import org.bukkit.event.player.PlayerJoinEvent;
import java.util.Arrays;
import java.util.Map;
import static com.songoda.epicenchants.enums.EventType.*;
import static com.songoda.epicenchants.enums.EventType.OFF;
import static com.songoda.epicenchants.enums.EventType.ON;
import static com.songoda.epicenchants.enums.TriggerType.*;
public class PlayerListener implements Listener {
@ -56,16 +57,24 @@ public class PlayerListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (event.getAction() == Action.RIGHT_CLICK_AIR) {
instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, RIGHT_CLICK);
} else if (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) {
} else if (event.getAction() == Action.LEFT_CLICK_AIR) {
instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, LEFT_CLICK);
}
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, RIGHT_CLICK_BLOCK);
} else if (event.getAction() == Action.LEFT_CLICK_BLOCK) {
instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, LEFT_CLICK_BLOCK);
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onBlockBreak(BlockBreakEvent event) {
instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, BLOCK_BREAK);
if (event.getExpToDrop() != 0)
instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, EXPERIENCE_BLOCK_BREAK);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)

View File

@ -2,13 +2,12 @@ package com.songoda.epicenchants.listeners.item;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.objects.Enchant;
import com.songoda.epicenchants.utils.itemnbtapi.NBTCompound;
import com.songoda.epicenchants.utils.itemnbtapi.NBTItem;
import com.songoda.epicenchants.utils.single.RomanNumber;
import de.tr7zw.itemnbtapi.NBTCompound;
import de.tr7zw.itemnbtapi.NBTItem;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import static com.songoda.epicenchants.objects.Placeholder.of;
import static com.songoda.epicenchants.utils.single.GeneralUtils.getRandomElement;
public class BlackScrollListener extends ItemListener {
@ -26,7 +25,8 @@ public class BlackScrollListener extends ItemListener {
NBTCompound compound = current.getCompound("enchants");
if (compound == null || compound.getKeys().isEmpty()) {
instance.getAction().perform(event.getWhoClicked(), "black-scroll.no-enchants");
instance.getLocale().getMessage("blackscroll.noenchants")
.sendPrefixedMessage(event.getWhoClicked());
return;
}
@ -38,11 +38,12 @@ public class BlackScrollListener extends ItemListener {
event.getWhoClicked().getInventory().addItem(enchant.getBook().get(enchant, level, cursor.getInteger("success-rate"), 100));
event.setCurrentItem(toSet);
instance.getAction().perform(event.getWhoClicked(), "black-scroll.success",
of("enchant", enchant.getIdentifier()),
of("group_color", enchant.getGroup().getColor()),
of("group_name", enchant.getGroup().getName()),
of("level", RomanNumber.toRoman(level)));
instance.getLocale().getMessage("blackscroll.success")
.processPlaceholder("enchant", enchant.getIdentifier())
.processPlaceholder("group_color", enchant.getGroup().getColor())
.processPlaceholder("group_name", enchant.getGroup().getName())
.processPlaceholder("level", RomanNumber.toRoman(level))
.sendPrefixedMessage(event.getWhoClicked());
useItem(event);
}

View File

@ -5,9 +5,9 @@ import com.songoda.epicenchants.enums.EnchantResult;
import com.songoda.epicenchants.events.EnchantApplyEvent;
import com.songoda.epicenchants.objects.Enchant;
import com.songoda.epicenchants.objects.Group;
import com.songoda.epicenchants.utils.Tuple;
import com.songoda.epicenchants.utils.itemnbtapi.NBTItem;
import com.songoda.epicenchants.utils.single.GeneralUtils;
import de.tr7zw.itemnbtapi.NBTItem;
import org.apache.commons.lang3.tuple.Pair;
import org.bukkit.Bukkit;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;
@ -16,7 +16,6 @@ import org.bukkit.inventory.ItemStack;
import java.util.Optional;
import static com.songoda.epicenchants.enums.EnchantResult.*;
import static com.songoda.epicenchants.objects.Placeholder.of;
public class BookListener extends ItemListener {
public BookListener(EpicEnchants instance) {
@ -49,10 +48,11 @@ public class BookListener extends ItemListener {
return;
}
Pair<ItemStack, EnchantResult> result = instance.getEnchantUtils().apply(toApply, enchant, enchantEvent.getLevel(), enchantEvent.getSuccessRate(), enchantEvent.getDestroyRate());
Tuple<ItemStack, EnchantResult> result = instance.getEnchantUtils().apply(toApply, enchant, enchantEvent.getLevel(), enchantEvent.getSuccessRate(), enchantEvent.getDestroyRate());
instance.getAction().perform(event.getWhoClicked(), GeneralUtils.getMessageFromResult(result.getRight()),
of("enchant", enchant.getIdentifier()));
instance.getLocale().getMessage(GeneralUtils.getMessageFromResult(result.getRight()))
.processPlaceholder("enchant", enchant.getIdentifier())
.sendPrefixedMessage(event.getWhoClicked());
if (result.getRight() == BROKEN_FAILURE) {
event.getClickedInventory().clear(event.getSlot());
@ -88,10 +88,10 @@ public class BookListener extends ItemListener {
useItem(event);
event.getPlayer().getInventory().addItem(enchant.get().getBook().get(enchant.get()));
instance.getAction().perform(event.getPlayer(), "book.discover",
of("group_name", group.getName()),
of("group_color", group.getColor()),
of("enchant_format", enchant.get().getFormat())
);
instance.getLocale().getMessage("book.discover")
.processPlaceholder("group_name", group.getName())
.processPlaceholder("group_color", group.getColor())
.processPlaceholder("enchant_format", enchant.get().getFormat())
.sendPrefixedMessage(event.getPlayer());
}
}

View File

@ -3,7 +3,7 @@ package com.songoda.epicenchants.listeners.item;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.objects.Enchant;
import com.songoda.epicenchants.objects.Group;
import de.tr7zw.itemnbtapi.NBTItem;
import com.songoda.epicenchants.utils.itemnbtapi.NBTItem;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;

View File

@ -1,7 +1,7 @@
package com.songoda.epicenchants.listeners.item;
import com.songoda.epicenchants.EpicEnchants;
import de.tr7zw.itemnbtapi.NBTItem;
import com.songoda.epicenchants.utils.itemnbtapi.NBTItem;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;

View File

@ -1,8 +1,8 @@
package com.songoda.epicenchants.listeners.item;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.utils.itemnbtapi.NBTItem;
import com.songoda.epicenchants.utils.objects.ItemBuilder;
import de.tr7zw.itemnbtapi.NBTItem;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
@ -21,12 +21,13 @@ public class WhiteScrollListener extends ItemListener {
event.setCancelled(true);
if (current.hasKey("protected")) {
instance.getAction().perform(event.getWhoClicked(), "white-scroll.already-applied");
instance.getLocale().getMessage("whitescroll.alreadyapplied")
.sendPrefixedMessage(event.getWhoClicked());
return;
}
current.setBoolean("protected", true);
instance.getAction().perform(event.getWhoClicked(), "white-scroll.applied");
instance.getLocale().getMessage("whitescrollapplied").sendPrefixedMessage(event.getWhoClicked());
ItemStack toSet = new ItemBuilder(current.getItem()).addLore(instance.getSpecialItems().getWhiteScrollLore()).build();

View File

@ -0,0 +1,157 @@
package com.songoda.epicenchants.managers;
import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.utils.ServerVersion;
import com.songoda.epicenchants.utils.objects.FileLocation;
import com.songoda.epicenchants.utils.settings.Setting;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
import static com.songoda.epicenchants.utils.objects.FileLocation.of;
import static java.io.File.separator;
import static java.util.Arrays.asList;
public class FileManager extends Manager<String, FileConfiguration> {
private final String directory;
private final LinkedHashSet<FileLocation> files = new LinkedHashSet<>(asList(
of("menus/main-info-menu.yml", true, true),
of("menus/enchanter-menu.yml", true, true),
of("menus/tinkerer-menu.yml", true, true),
of("menus/alchemist-menu.yml", true, true),
of("menus/groups/simple-menu.yml", true, true),
of("menus/groups/unique-menu.yml", true, true),
of("menus/groups/elite-menu.yml", true, true),
of("menus/groups/ultimate-menu.yml", true, true),
of("menus/groups/legendary-menu.yml", true, true),
of("enchants/elite/AntiGravity.yml", false),
of("enchants/elite/Frozen.yml", false),
of("enchants/elite/Poison.yml", false),
of("enchants/elite/RocketEscape.yml", false),
of("enchants/elite/Shockwave.yml", false),
of("enchants/elite/Wither.yml", false),
of("enchants/legendary/DeathBringer.yml", false),
of("enchants/legendary/DeathGod.yml", false),
of("enchants/legendary/Enlightened.yml", false),
of("enchants/legendary/Gears.yml", false),
of("enchants/legendary/LifeSteal.yml", false),
of("enchants/legendary/Overload.yml", false),
of("enchants/legendary/Resist.yml", false),
of("enchants/legendary/SkillSwipe.yml", false),
of("enchants/simple/Aquatic.yml", false),
of("enchants/simple/Confusion.yml", false),
of("enchants/simple/Experience.yml", false),
of("enchants/simple/Glowing.yml", false),
of("enchants/simple/Haste.yml", false),
of("enchants/simple/Insomnia.yml", false),
of("enchants/simple/Lightning.yml", false),
of("enchants/simple/Obliterate.yml", false),
of("enchants/simple/Oxygenate.yml", false),
of("enchants/ultimate/Blind.yml", false),
of("enchants/ultimate/Dodge.yml", false),
of("enchants/ultimate/Fly.yml", false),
of("enchants/ultimate/FoodSteal.yml", false),
of("enchants/ultimate/IceAspect.yml", false),
of("enchants/ultimate/StormFall.yml", false),
of("enchants/unique/Berserk.yml", false),
of("enchants/unique/Decapitation.yml", false),
of("enchants/unique/Explosive.yml", false),
of("enchants/unique/FeatherWeight.yml", false),
of("enchants/unique/Inquisitive.yml", false),
of("enchants/unique/ObsidianDestroyer.yml", false),
of("enchants/unique/PlagueCarrier.yml", false),
of("enchants/unique/Ragdoll.yml", false),
of("enchants/unique/SelfDestruct.yml", false),
of("groups.yml", true),
of("items/special-items.yml", true, true),
of("items/dusts.yml", true, true)
));
public FileManager(EpicEnchants instance) {
super(instance);
directory = instance.isServerVersionAtLeast(ServerVersion.V1_13) ? "master" : "legacy";
Bukkit.getConsoleSender().sendMessage("Using the " + directory + " configurations because version is " + instance.getServerVersion().name());
}
public void loadFiles() {
files.forEach(fileLocation -> {
File file = new File(instance.getDataFolder() + separator + fileLocation.getPath());
if (!file.exists() && (fileLocation.isRequired() || Setting.FIRST_LOAD.getBoolean())) {
file.getParentFile().mkdirs();
Bukkit.getConsoleSender().sendMessage("Creating file: " + fileLocation.getPath());
try {
// System.out.println(fileLocation.getResourcePath(directory) + " : " + file.toPath());
copy(instance.getResource(fileLocation.getResourcePath(directory)), Files.newOutputStream(file.toPath()));
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileLocation.isRequired()) {
FileConfiguration configuration = new YamlConfiguration();
try {
configuration.load(file);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
add(fileLocation.getPath().replace(".yml", ""), configuration);
}
});
instance.getConfig().set("System.First Load", false);
instance.saveConfig();
instance.getSettingsManager().reloadConfig();
}
public FileConfiguration getConfiguration(String key) {
return getValueUnsafe(key);
}
public List<File> getYmlFiles(String directory) {
File dir = new File(instance.getDataFolder() + separator + directory + separator);
File[] allFiles = dir.listFiles();
List<File> output = new ArrayList<>();
if (allFiles == null) {
return output;
}
Optional.ofNullable(dir.listFiles((dir1, filename) -> filename.endsWith(".yml"))).ifPresent(list -> {
output.addAll(Arrays.asList(list));
});
Arrays.stream(allFiles)
.filter(File::isDirectory)
.filter(s -> !s.getName().equalsIgnoreCase("old"))
.forEach(f -> output.addAll(getYmlFiles(directory + separator + f.getName())));
return output;
}
private static void copy(InputStream input, OutputStream output) {
int n;
byte[] buffer = new byte[1024 * 4];
try {
while ((n = input.read(buffer)) != -1) {
output.write(buffer, 0, n);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -1,12 +1,10 @@
package com.songoda.epicenchants.managers;
import com.songoda.ultimatebottles.UltimateBottles;
import lombok.Getter;
import org.bukkit.Bukkit;
import java.util.Optional;
@Getter
public class HookManager {
private UltimateBottles ultimateBottles;

View File

@ -4,7 +4,6 @@ import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.menus.InfoMenu;
import com.songoda.epicenchants.menus.MainInfoMenu;
import com.songoda.epicenchants.objects.Group;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
@ -12,7 +11,7 @@ import java.util.Optional;
public class InfoManager extends Manager<Group, InfoMenu> {
private final EpicEnchants instance;
@Getter private MainInfoMenu mainInfoMenu;
private MainInfoMenu mainInfoMenu;
public InfoManager(EpicEnchants instance) {
super(instance);
@ -38,4 +37,7 @@ public class InfoManager extends Manager<Group, InfoMenu> {
});
}
public MainInfoMenu getMainInfoMenu() {
return this.mainInfoMenu;
}
}

View File

@ -15,7 +15,11 @@ public abstract class Manager<K, V> {
}
public Optional<V> getValue(K key) {
return Optional.ofNullable(map.get(key));
for (Object k : map.keySet()) {
if (k.toString().equalsIgnoreCase(key.toString()))
return Optional.ofNullable(map.get(k));
}
return Optional.empty();
}
public void add(K key, V value) {

View File

@ -4,10 +4,10 @@ import com.songoda.epicenchants.EpicEnchants;
import com.songoda.epicenchants.objects.Enchant;
import com.songoda.epicenchants.objects.Group;
import com.songoda.epicenchants.objects.Placeholder;
import com.songoda.epicenchants.utils.itemnbtapi.NBTItem;
import com.songoda.epicenchants.utils.objects.FastInv;
import com.songoda.epicenchants.utils.objects.ItemBuilder;
import com.songoda.epicenchants.utils.single.GeneralUtils;
import de.tr7zw.itemnbtapi.NBTItem;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
@ -56,7 +56,7 @@ public class AlchemistMenu extends FastInv {
.filter(s -> !filter.contains(s))
.map(s -> "contents." + s)
.map(config::getConfigurationSection)
.forEach(section -> addItem(getSlots(config.getString("slot")), new ItemBuilder(section).build()));
.forEach(section -> addItem(getSlots(section.getString("slot")), new ItemBuilder(section).build()));
clear(RIGHT_SLOT);
clear(LEFT_SLOT);
@ -122,13 +122,13 @@ public class AlchemistMenu extends FastInv {
NBTItem nbtItem = new NBTItem(toHandle);
if (!nbtItem.hasKey("book-item") && !nbtItem.hasKey("dust")) {
instance.getAction().perform(player, "alchemist.not-interested");
instance.getLocale().getMessage("alchemist.notinterested").sendPrefixedMessage(player);
return false;
}
// Both slots occupied
if (getInventory().getItem(LEFT_SLOT) != null && getInventory().getItem(RIGHT_SLOT) != null) {
instance.getAction().perform(player, "alchemist.max-two-items");
instance.getLocale().getMessage("alchemist.maxtwoitems").sendPrefixedMessage(player);
return false;
}
@ -141,14 +141,16 @@ public class AlchemistMenu extends FastInv {
int level = nbtItem.getInteger("level");
if (enchant.getMaxLevel() == level) {
instance.getAction().perform(player, "alchemist.max-level-book");
instance.getLocale().getMessage("alchemist.maxlevelbook")
.sendPrefixedMessage(player);
return false;
}
} else {
Group group = instance.getGroupManager().getValue(nbtItem.getString("group")).orElseThrow(() -> new IllegalStateException("Dust without group!"));
if (group.getOrder() == instance.getGroupManager().getValues().stream().mapToInt(Group::getOrder).max().orElse(0) || successRate == 100) {
instance.getAction().perform(player, "alchemist." + (successRate == 100 ? "max-percentage-dust" : "highest-group-dust"));
instance.getLocale().getMessage("alchemist." + (successRate == 100 ? "maxpercentagedust" : "highestgroupdust"))
.sendPrefixedMessage(player);
return false;
}
}
@ -162,22 +164,22 @@ public class AlchemistMenu extends FastInv {
if (other.hasKey("book-item")) {
if (!nbtItem.getString("enchant").equals(other.getString("enchant"))) {
instance.getAction().perform(player, "alchemist.different-enchantment");
instance.getLocale().getMessage("alchemist.differentenchantment").sendPrefixedMessage(player);
return false;
}
if (!nbtItem.getInteger("level").equals(other.getInteger("level"))) {
instance.getAction().perform(player, "alchemist.different-levels");
instance.getLocale().getMessage("alchemist.differentlevels").sendPrefixedMessage(player);
return false;
}
} else {
if (!nbtItem.getString("group").equals(other.getString("group"))) {
instance.getAction().perform(player, "alchemist.different-groups");
instance.getLocale().getMessage("alchemist.differentgroups").sendPrefixedMessage(player);
return false;
}
if (successRate == 100) {
instance.getAction().perform(player, "alchemist.max-percentage-dust");
if (successRate >= 100) {
instance.getLocale().getMessage("alchemist.maxpercentagedust").sendPrefixedMessage(player);
return false;
}
}
@ -261,14 +263,17 @@ public class AlchemistMenu extends FastInv {
of("eco_cost", ecoCost),
of("exp_cost", expCost)
).build(), event -> {
if (!instance.getEconomy().has(event.getPlayer(), ecoCost) || getExp(event.getPlayer()) < expCost) {
instance.getAction().perform(event.getPlayer(), "alchemist.cannot-afford");
if (!instance.getEconomy().hasBalance(event.getPlayer(), ecoCost) || getExp(event.getPlayer()) < expCost) {
instance.getLocale().getMessage("alchemist.cannotafford").sendPrefixedMessage(event.getPlayer());
return;
}
instance.getEconomy().withdrawPlayer(event.getPlayer(), ecoCost);
instance.getEconomy().withdrawBalance(event.getPlayer(), ecoCost);
changeExp(event.getPlayer(), -expCost);
instance.getAction().perform(event.getPlayer(), "alchemist.success", of("eco_cost", ecoCost), of("exp_cost", expCost));
instance.getLocale().getMessage("alchemist.success")
.processPlaceholder("eco_cost", ecoCost)
.processPlaceholder("exp_cost", expCost)
.sendPrefixedMessage(event.getPlayer());
event.getPlayer().getInventory().addItem(getInventory().getItem(PREVIEW_SLOT));
clear(RIGHT_SLOT);
@ -283,6 +288,6 @@ public class AlchemistMenu extends FastInv {
for (Placeholder placeholder : placeholders)
toTest = toTest.replace(placeholder.getPlaceholder(), placeholder.getToReplace().toString());
return (int) GeneralUtils.parseJS(toTest, "alchemist expression", 0);
return (int) Double.parseDouble(GeneralUtils.parseJS(toTest, "alchemist expression", 0).toString());
}
}

View File

@ -8,11 +8,17 @@ import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static com.songoda.epicenchants.objects.Placeholder.of;
import static com.songoda.epicenchants.utils.single.Experience.*;
import static com.songoda.epicenchants.utils.single.GeneralUtils.*;
public class EnchanterMenu extends FastInv {
private final Map<UUID, Long> DELAY = new HashMap<>();
public EnchanterMenu(EpicEnchants instance, FileConfiguration config, Player player) {
super(config.getInt("rows") * 9, color(config.getString("title")));
@ -24,11 +30,14 @@ public class EnchanterMenu extends FastInv {
.stream()
.map(s -> "contents." + s)
.map(config::getConfigurationSection)
.filter(s -> s.get("group") != null)
.forEach(section -> {
int expCost = section.getInt("exp-cost");
int ecoCost = section.getInt("eco-cost");
int xpLeft = expCost - player.getLevel() < 0 ? 0 : expCost - player.getLevel();
double ecoLeft = ecoCost - instance.getEconomy().getBalance(player) < 0 ? 0 : ecoCost - instance.getEconomy().getBalance(player);
int xpLeft = Math.max(expCost - player.getLevel(), 0);
double ecoLeft = 0.0d;
if (instance.getEconomy() != null)
ecoLeft = ecoCost - instance.getEconomy().getBalance(player) < 0 ? 0 : ecoCost - instance.getEconomy().getBalance(player);
Group group = instance.getGroupManager().getValue(section.getString("group").toUpperCase())
.orElseThrow(() -> new IllegalArgumentException("Invalid group set in enchanter: " + section.getString("group")));
ItemStack itemStack = new ItemBuilder(section,
@ -38,22 +47,38 @@ public class EnchanterMenu extends FastInv {
of("eco_left", ecoLeft)).build();
addItem(getSlots(section.getString("slot")), itemStack, event -> {
if (!instance.getEconomy().has((player), ecoCost) || getExp(player) < expCost) {
instance.getAction().perform(player, "enchanter.cannot-afford");
// Todo: wanna change this
if (DELAY.getOrDefault(player.getUniqueId(), 0L) > System.currentTimeMillis()) {
return;
}
instance.getEconomy().withdrawPlayer(player, ecoCost);
instance.getAction().perform(player, "enchanter.success",
of("group_name", group.getName()),
of("group_color", group.getColor()),
of("eco_cost", ecoCost),
of("exp_cost", expCost));
if (instance.getEconomy() != null && !instance.getEconomy().hasBalance((player), ecoCost) || getExp(player) < expCost) {
instance.getLocale().getMessage("enchanter.cannotafford").sendPrefixedMessage(player);
return;
}
if (instance.getEconomy() != null) {
instance.getEconomy().withdrawBalance(player, ecoCost);
instance.getLocale().getMessage("enchanter.success")
.processPlaceholder("group_name", group.getName())
.processPlaceholder("group_color", group.getColor())
.processPlaceholder("eco_cost", ecoCost)
.processPlaceholder("exp_cost", expCost)
.sendPrefixedMessage(player);
}
changeExp(player, -expCost);
player.getInventory().addItem(instance.getSpecialItems().getMysteryBook(group));
DELAY.put(event.getPlayer().getUniqueId(), System.currentTimeMillis() + 120);
});
});
config.getConfigurationSection("contents").getKeys(false)
.stream()
.map(s -> "contents." + s)
.map(config::getConfigurationSection)
.filter(s -> s.get("group") == null)
.forEach(section -> addItem(getSlots(section.getString("slot")), new ItemBuilder(section).build()));
}
}

Some files were not shown because too many files have changed in this diff Show More