Updates depreciated code, and fixes code style

This commit is contained in:
Kristian Knarvik 2022-02-01 19:52:41 +01:00
parent 915876f7d2
commit a2155e2654
5 changed files with 508 additions and 582 deletions

15
pom.xml
View File

@ -6,14 +6,13 @@
<groupId>net.apunch</groupId> <groupId>net.apunch</groupId>
<artifactId>blacksmith</artifactId> <artifactId>blacksmith</artifactId>
<version>1.16-SNAPSHOT</version> <version>1.18.1-SNAPSHOT</version>
<name>Blacksmith</name> <name>Blacksmith</name>
<description>Blacksmith Character for the CitizensAPI</description> <description>Blacksmith Character for the CitizensAPI</description>
<!-- Properties --> <!-- Properties -->
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<bukkit.version>1.15.2-R0.1-SNAPSHOT</bukkit.version>
<citizensapi.version>2.0.26-SNAPSHOT</citizensapi.version> <citizensapi.version>2.0.26-SNAPSHOT</citizensapi.version>
<vault.version>1.7.3</vault.version> <vault.version>1.7.3</vault.version>
<hyperconomy.version>0.975.7-SNAPSHOT</hyperconomy.version> <hyperconomy.version>0.975.7-SNAPSHOT</hyperconomy.version>
@ -58,13 +57,7 @@
<dependency> <dependency>
<groupId>org.spigotmc</groupId> <groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId> <artifactId>spigot-api</artifactId>
<version>1.16.5-R0.1-SNAPSHOT</version> <version>1.18.1-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>${bukkit.version}</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -100,8 +93,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version> <version>3.7.0</version>
<configuration> <configuration>
<source>1.6</source> <source>17</source>
<target>1.6</target> <target>17</target>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

View File

@ -1,44 +1,40 @@
package net.apunch.blacksmith; package net.apunch.blacksmith;
import java.util.ArrayList;
import java.util.logging.Level;
import net.apunch.blacksmith.util.Settings; import net.apunch.blacksmith.util.Settings;
import net.apunch.blacksmith.util.Settings.Setting; import net.apunch.blacksmith.util.Settings.Setting;
import net.citizensnpcs.api.CitizensAPI; import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.util.DataKey; import net.citizensnpcs.api.util.DataKey;
import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.OfflinePlayer; import org.bukkit.NamespacedKey;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import regalowl.hyperconomy.HyperAPI; import regalowl.hyperconomy.HyperAPI;
import regalowl.hyperconomy.HyperConomy; import regalowl.hyperconomy.HyperConomy;
import regalowl.hyperconomy.bukkit.BukkitConnector; import regalowl.hyperconomy.bukkit.BukkitConnector;
import regalowl.hyperconomy.inventory.HItemStack; import regalowl.hyperconomy.inventory.HItemStack;
import regalowl.hyperconomy.tradeobject.TradeObject; import regalowl.hyperconomy.tradeobject.TradeObject;
import java.util.ArrayList;
import java.util.Objects;
import java.util.logging.Level;
public class BlacksmithPlugin extends JavaPlugin { public class BlacksmithPlugin extends JavaPlugin {
public BlacksmithPlugin plugin;
private Settings config; private Settings config;
private Economy economy; private Economy economy;
private HyperAPI hyperAPI; private HyperAPI hyperAPI;
private BukkitConnector bukCon; private BukkitConnector bukCon;
private boolean useHyperAPI = false; private boolean useHyperAPI = false;
//private boolean hasCititrader = false; // CitiTrader dependency outdated and broken
@Override @Override
public void onDisable() { public void onDisable() {
@ -51,36 +47,27 @@ public class BlacksmithPlugin extends JavaPlugin {
public void onEnable() { public void onEnable() {
config = new Settings(this); config = new Settings(this);
config.load(); config.load();
// Setup Hyperconomy (Soft-Depend only, so this is completely optional!) /* Setup Hyperconomy (Soft-Depend only, so this is completely optional!)
// Hyperconomy uses your favorite Vault-compatible economy system Hyperconomy uses your favorite Vault-compatible economy system
// and calculates prices for items based on supply and demand on the fly. and calculates prices for items based on supply and demand on the fly.
// This is only used to get the cost of a repair. This is only used to get the cost of a repair.*/
if (Bukkit.getPluginManager().getPlugin("HyperConomy") != null) { if (Bukkit.getPluginManager().getPlugin("HyperConomy") != null) {
getServer().getLogger().log(Level.INFO, "Found HyperConomy! Using that for calculating prices, base-prices and price-per-durability-point in the Blacksmith config.yml will NOT be used!"); getServer().getLogger().log(Level.INFO, "Found HyperConomy! Using that for calculating prices, base-prices and price-per-durability-point in the Blacksmith config.yml will NOT be used!");
this.useHyperAPI = true; this.useHyperAPI = true;
Plugin hcPlugin = getServer().getPluginManager().getPlugin("HyperConomy"); Plugin hcPlugin = getServer().getPluginManager().getPlugin("HyperConomy");
bukCon = (BukkitConnector)hcPlugin; bukCon = (BukkitConnector) hcPlugin;
HyperConomy hc = bukCon.getHC(); HyperConomy hc = Objects.requireNonNull(bukCon).getHC();
this.hyperAPI = (HyperAPI) hc.getAPI(); this.hyperAPI = (HyperAPI) hc.getAPI();
} }
getLogger().log(Level.INFO, "Setting Up Vault now...."); getLogger().log(Level.INFO, "Setting Up Vault now....");
/* CitiTrader dependency outdated and broken boolean canLoad = SetupVault();
// Check for Cititrader if (!canLoad) {
if(getServer().getPluginManager().getPlugin("CitiTrader") != null) {
hasCititrader = true;
}
*/
boolean canload = SetupVault();
if (!canload)
{
getLogger().log(Level.INFO, "Vault Failed...."); getLogger().log(Level.INFO, "Vault Failed....");
getServer().getPluginManager().disablePlugin(this); getServer().getPluginManager().disablePlugin(this);
return; return;
} }
CitizensAPI.getTraitFactory().registerTrait(net.citizensnpcs.api.trait.TraitInfo.create(BlacksmithTrait.class).withName("blacksmith")); CitizensAPI.getTraitFactory().registerTrait(net.citizensnpcs.api.trait.TraitInfo.create(BlacksmithTrait.class).withName("blacksmith"));
getLogger().log(Level.INFO, " v" + getDescription().getVersion() + " enabled."); getLogger().log(Level.INFO, " v" + getDescription().getVersion() + " enabled.");
} }
@ -88,12 +75,10 @@ public class BlacksmithPlugin extends JavaPlugin {
// Setup Vault // Setup Vault
RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration( RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(
Economy.class); Economy.class);
if (economyProvider != null) if (economyProvider != null) {
{
economy = economyProvider.getProvider(); economy = economyProvider.getProvider();
return true; return true;
} } else {
else {
// Disable if no economy plugin was found // Disable if no economy plugin was found
getServer().getLogger().log(Level.SEVERE, "Failed to load an economy plugin. Disabling..."); getServer().getLogger().log(Level.SEVERE, "Failed to load an economy plugin. Disabling...");
return false; return false;
@ -101,105 +86,28 @@ public class BlacksmithPlugin extends JavaPlugin {
} }
@Override @Override
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { public boolean onCommand(final CommandSender sender, final @NotNull Command command, final @NotNull String label, final String[] args) {
config.load(); config.load();
sender.sendMessage(ChatColor.GREEN + "Blacksmith config reloaded!"); sender.sendMessage(ChatColor.GREEN + "Blacksmith config reloaded!");
return true; return true;
} }
/* CitiTrader dependency outdated and broken
// Return if we have cititrader
public boolean hasCititrader() {
return this.hasCititrader;
}
*/
public BlacksmithTrait getBlacksmith(NPC npc){
if (npc !=null && npc.hasTrait(BlacksmithTrait.class)){
return npc.getTrait(BlacksmithTrait.class);
}
return null;
}
public boolean isTool(ItemStack item) { public boolean isTool(ItemStack item) {
switch (item.getType()) { return switch (item.getType()) {
case WOODEN_PICKAXE: case WOODEN_PICKAXE, WOODEN_SHOVEL, WOODEN_HOE, WOODEN_SWORD, WOODEN_AXE, STONE_PICKAXE, STONE_SHOVEL, STONE_HOE, STONE_SWORD, STONE_AXE, GOLDEN_PICKAXE, GOLDEN_SHOVEL, GOLDEN_HOE, GOLDEN_SWORD, GOLDEN_AXE, IRON_PICKAXE, IRON_SHOVEL, IRON_HOE, IRON_SWORD, IRON_AXE, DIAMOND_PICKAXE, DIAMOND_SHOVEL, DIAMOND_HOE, DIAMOND_SWORD, DIAMOND_AXE, NETHERITE_SWORD, NETHERITE_SHOVEL, NETHERITE_PICKAXE, NETHERITE_AXE, NETHERITE_HOE, BOW, FLINT_AND_STEEL, FISHING_ROD, SHEARS -> true;
case WOODEN_SHOVEL: default -> false;
case WOODEN_HOE: };
case WOODEN_SWORD:
case WOODEN_AXE:
case STONE_PICKAXE:
case STONE_SHOVEL:
case STONE_HOE:
case STONE_SWORD:
case STONE_AXE:
case GOLDEN_PICKAXE:
case GOLDEN_SHOVEL:
case GOLDEN_HOE:
case GOLDEN_SWORD:
case GOLDEN_AXE:
case IRON_PICKAXE:
case IRON_SHOVEL:
case IRON_HOE:
case IRON_SWORD:
case IRON_AXE:
case DIAMOND_PICKAXE:
case DIAMOND_SHOVEL:
case DIAMOND_HOE:
case DIAMOND_SWORD:
case DIAMOND_AXE:
case NETHERITE_SWORD:
case NETHERITE_SHOVEL:
case NETHERITE_PICKAXE:
case NETHERITE_AXE:
case NETHERITE_HOE:
case BOW:
case FLINT_AND_STEEL:
case FISHING_ROD:
case SHEARS:
return true;
default:
return false;
}
} }
public boolean isArmor(ItemStack item) { public boolean isArmor(ItemStack item) {
switch (item.getType()) { return switch (item.getType()) {
case LEATHER_HELMET: case LEATHER_HELMET, LEATHER_CHESTPLATE, LEATHER_LEGGINGS, LEATHER_BOOTS, CHAINMAIL_HELMET, CHAINMAIL_CHESTPLATE, CHAINMAIL_LEGGINGS, CHAINMAIL_BOOTS, GOLDEN_HELMET, GOLDEN_CHESTPLATE, GOLDEN_LEGGINGS, GOLDEN_BOOTS, IRON_HELMET, IRON_CHESTPLATE, IRON_LEGGINGS, IRON_BOOTS, DIAMOND_HELMET, DIAMOND_CHESTPLATE, DIAMOND_LEGGINGS, DIAMOND_BOOTS, NETHERITE_HELMET, NETHERITE_CHESTPLATE, NETHERITE_LEGGINGS, NETHERITE_BOOTS -> true;
case LEATHER_CHESTPLATE: default -> false;
case LEATHER_LEGGINGS: };
case LEATHER_BOOTS:
case CHAINMAIL_HELMET:
case CHAINMAIL_CHESTPLATE:
case CHAINMAIL_LEGGINGS:
case CHAINMAIL_BOOTS:
case GOLDEN_HELMET:
case GOLDEN_CHESTPLATE:
case GOLDEN_LEGGINGS:
case GOLDEN_BOOTS:
case IRON_HELMET:
case IRON_CHESTPLATE:
case IRON_LEGGINGS:
case IRON_BOOTS:
case DIAMOND_HELMET:
case DIAMOND_CHESTPLATE:
case DIAMOND_LEGGINGS:
case DIAMOND_BOOTS:
case NETHERITE_HELMET:
case NETHERITE_CHESTPLATE:
case NETHERITE_LEGGINGS:
case NETHERITE_BOOTS:
return true;
default:
return false;
}
} }
public boolean doesPlayerHaveEnough(Player player) { public boolean doesPlayerHaveEnough(Player player) {
return economy.getBalance((OfflinePlayer) player) - getCost(player.getInventory().getItemInMainHand(), player) >= 0; return economy.getBalance(player) - getCost(player.getInventory().getItemInMainHand(), player) >= 0;
} }
public String formatCost(Player player) { public String formatCost(Player player) {
@ -208,23 +116,15 @@ public class BlacksmithPlugin extends JavaPlugin {
} }
public void withdraw(Player player) { public void withdraw(Player player) {
economy.withdrawPlayer(((OfflinePlayer) player), getCost(player.getInventory().getItemInMainHand(), player)); economy.withdrawPlayer(player, getCost(player.getInventory().getItemInMainHand(), player));
} }
/* CitiTrader dependency outdated and broken.
public void deposit(NPC npc, Player player) {
// if(hasCititrader) {
// if(npc.hasTrait(WalletTrait.class)) {
// npc.getTrait(WalletTrait.class).deposit(getCost(player.getItemInHand()));
// }
// }
}
*/
private double getCost(ItemStack item, Player player) { private double getCost(ItemStack item, Player player) {
DataKey root = config.getConfig().getKey(""); DataKey root = config.getConfig().getKey("");
double price = Setting.BASE_PRICE.asDouble(); double price = Setting.BASE_PRICE.asDouble();
if (root.keyExists("base-prices." + item.getType().name().toLowerCase().replace('_', '-'))) if (root.keyExists("base-prices." + item.getType().name().toLowerCase().replace('_', '-'))) {
price = root.getDouble("base-prices." + item.getType().name().toLowerCase().replace('_', '-')); price = root.getDouble("base-prices." + item.getType().name().toLowerCase().replace('_', '-'));
}
// Adjust price based on durability and enchantments // Adjust price based on durability and enchantments
if (this.useHyperAPI) { if (this.useHyperAPI) {
@ -237,58 +137,61 @@ public class BlacksmithPlugin extends JavaPlugin {
for (TradeObject enchant : hyperAPI.getEnchantmentHyperObjects(hi, player.getName())) { for (TradeObject enchant : hyperAPI.getEnchantmentHyperObjects(hi, player.getName())) {
hyperPrice = hyperPrice + enchant.getBuyPrice(1); hyperPrice = hyperPrice + enchant.getBuyPrice(1);
item2.removeEnchantment(Enchantment.getByName(enchant.getEnchantment().getEnchantmentName ())); Enchantment enchantment = Enchantment.getByKey(NamespacedKey.minecraft(enchant.getEnchantment().getEnchantmentName()));
item2.removeEnchantment(Objects.requireNonNull(enchantment));
} }
ArrayList<Material> leathers = new ArrayList<Material>(); ArrayList<Material> leathers = new ArrayList<>();
leathers.add(Material.LEATHER_BOOTS); leathers.add(Material.LEATHER_BOOTS);
leathers.add(Material.LEATHER_CHESTPLATE); leathers.add(Material.LEATHER_CHESTPLATE);
leathers.add(Material.LEATHER_HELMET); leathers.add(Material.LEATHER_HELMET);
leathers.add(Material.LEATHER_LEGGINGS); leathers.add(Material.LEATHER_LEGGINGS);
HItemStack hi3 = null; HItemStack hi3 = null;
if (leathers.contains(player.getInventory().getItemInMainHand().getType())){ if (leathers.contains(player.getInventory().getItemInMainHand().getType())) {
hi3 = bukCon.getBukkitCommon().getSerializableItemStack(new ItemStack(player.getInventory().getItemInMainHand().getType())); hi3 = bukCon.getBukkitCommon().getSerializableItemStack(new ItemStack(player.getInventory().getItemInMainHand().getType()));
} }
TradeObject to = this.hyperAPI.getHyperObject(hi, "default"); TradeObject to = this.hyperAPI.getHyperObject(hi, "default");
if (to==null) { if (to == null) {
to = hyperAPI.getHyperObject(hi3, "default"); to = hyperAPI.getHyperObject(hi3, "default");
if (to==null) { if (to == null) {
HItemStack hi4 = bukCon.getBukkitCommon().getSerializableItemStack(new ItemStack(player.getInventory().getItemInMainHand().getType())); HItemStack hi4 = bukCon.getBukkitCommon().getSerializableItemStack(new ItemStack(player.getInventory().getItemInMainHand().getType()));
to = this.hyperAPI.getHyperObject(hi4, "default"); to = this.hyperAPI.getHyperObject(hi4, "default");
} }
hyperPrice = hyperPrice+to.getSellPrice(1); hyperPrice = hyperPrice + to.getSellPrice(1);
} else { } else {
hyperPrice = to.getSellPrice(1); hyperPrice = to.getSellPrice(1);
} }
double hyperPricePerDurability = hyperPrice / item.getType().getMaxDurability(); double hyperPricePerDurability = hyperPrice / item.getType().getMaxDurability();
price += (item.getDurability() * hyperPricePerDurability); price += (((Damageable) item).getDamage() * hyperPricePerDurability);
double enchantmentModifier = Setting.ENCHANTMENT_MODIFIER.asDouble(); double enchantmentModifier = Setting.ENCHANTMENT_MODIFIER.asDouble();
for (Enchantment enchantment : item2.getEnchantments().keySet()) { for (Enchantment enchantment : item2.getEnchantments().keySet()) {
if (root.keyExists("enchantment-modifiers." + enchantment.getName().toLowerCase().replace('_', '-'))) if (root.keyExists("enchantment-modifiers." + enchantment.getKey().asString().toLowerCase().replace('_', '-'))) {
enchantmentModifier = root.getDouble("enchantment-modifiers." enchantmentModifier = root.getDouble("enchantment-modifiers."
+ enchantment.getName().toLowerCase().replace('_', '-')); + enchantment.getKey().asString().toLowerCase().replace('_', '-'));
}
price += enchantmentModifier * item2.getEnchantmentLevel(enchantment); price += enchantmentModifier * item2.getEnchantmentLevel(enchantment);
} }
return price; return price;
} else {
if (root.keyExists("price-per-durability-point." + item.getType().name().toLowerCase().replace('_', '-'))) {
price += ((Damageable) item).getDamage() * root.getDouble("price-per-durability-point." + item.getType().name().toLowerCase().replace('_', '-'));
} else {
price += (((Damageable) item).getDamage() * Setting.PRICE_PER_DURABILITY_POINT.asDouble());
} }
else {
if (root.keyExists("price-per-durability-point." + item.getType().name().toLowerCase().replace('_', '-')))
price += item.getDurability() * root.getDouble("price-per-durability-point." + item.getType().name().toLowerCase().replace('_', '-'));
else price += (item.getDurability() * Setting.PRICE_PER_DURABILITY_POINT.asDouble());
} }
double enchantmentModifier = Setting.ENCHANTMENT_MODIFIER.asDouble(); double enchantmentModifier = Setting.ENCHANTMENT_MODIFIER.asDouble();
for (Enchantment enchantment : item.getEnchantments().keySet()) { for (Enchantment enchantment : item.getEnchantments().keySet()) {
if (root.keyExists("enchantment-modifiers." + enchantment.getName().toLowerCase().replace('_', '-'))) if (root.keyExists("enchantment-modifiers." + enchantment.getKey().asString().toLowerCase().replace('_', '-'))) {
enchantmentModifier = root.getDouble("enchantment-modifiers." enchantmentModifier = root.getDouble("enchantment-modifiers."
+ enchantment.getName().toLowerCase().replace('_', '-')); + enchantment.getKey().asString().toLowerCase().replace('_', '-'));
}
price += enchantmentModifier * item.getEnchantmentLevel(enchantment); price += enchantmentModifier * item.getEnchantmentLevel(enchantment);
} }
return price; return price;

View File

@ -1,32 +1,33 @@
package net.apunch.blacksmith; package net.apunch.blacksmith;
import net.apunch.blacksmith.util.Settings.Setting;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.trait.Trait;
import net.citizensnpcs.api.util.DataKey;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Random; import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.inventory.ItemStack;
import net.apunch.blacksmith.util.Settings.Setting;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.trait.Trait;
import net.citizensnpcs.api.util.DataKey;
public class BlacksmithTrait extends Trait { public class BlacksmithTrait extends Trait {
private static final String[] enchantments = new String[Enchantment.values().length]; private static final String[] enchantments = new String[Enchantment.values().length];
private final BlacksmithPlugin plugin; private final BlacksmithPlugin plugin;
private final List<Material> reforgeableItems = new ArrayList<Material>(); private final List<Material> reforgeAbleItems = new ArrayList<>();
private final Map<String, Calendar> cooldowns = new HashMap<String, Calendar>(); private final Map<String, Calendar> coolDowns = new HashMap<>();
private ReforgeSession session; private ReforgeSession session;
// Defaults // Defaults
@ -38,99 +39,123 @@ public class BlacksmithTrait extends Trait {
private String successMsg = Setting.SUCCESS_MESSAGE.asString(); private String successMsg = Setting.SUCCESS_MESSAGE.asString();
private String failMsg = Setting.FAIL_MESSAGE.asString(); private String failMsg = Setting.FAIL_MESSAGE.asString();
private String insufficientFundsMsg = Setting.INSUFFICIENT_FUNDS_MESSAGE.asString(); private String insufficientFundsMsg = Setting.INSUFFICIENT_FUNDS_MESSAGE.asString();
private String cooldownUnexpiredMsg = Setting.COOLDOWN_UNEXPIRED_MESSAGE.asString(); private String coolDownUnexpiredMessage = Setting.COOLDOWN_UNEXPIRED_MESSAGE.asString();
private String itemChangedMsg = Setting.ITEM_UNEXPECTEDLY_CHANGED_MESSAGE.asString(); private String itemChangedMsg = Setting.ITEM_UNEXPECTEDLY_CHANGED_MESSAGE.asString();
private int minReforgeDelay = Setting.MIN_REFORGE_DELAY.asInt(); private int minReforgeDelay = Setting.MIN_REFORGE_DELAY.asInt();
private int maxReforgeDelay = Setting.MAX_REFORGE_DELAY.asInt(); private int maxReforgeDelay = Setting.MAX_REFORGE_DELAY.asInt();
private int reforgeCooldown = Setting.REFORGE_COOLDOWN.asInt(); private int reforgeCoolDown = Setting.REFORGE_COOLDOWN.asInt();
private int failChance = Setting.FAIL_CHANCE.asInt(); private int failChance = Setting.FAIL_CHANCE.asInt();
private int extraEnchantmentChance = Setting.EXTRA_ENCHANTMENT_CHANCE.asInt(); private int extraEnchantmentChance = Setting.EXTRA_ENCHANTMENT_CHANCE.asInt();
private int maxEnchantments = Setting.MAX_ENCHANTMENTS.asInt(); private int maxEnchantments = Setting.MAX_ENCHANTMENTS.asInt();
private boolean dropItem = Setting.DROP_ITEM.asBoolean(); private boolean dropItem = Setting.DROP_ITEM.asBoolean();
private boolean disablecooldown = Setting.DISABLE_COOLDOWN.asBoolean(); private boolean disableCoolDown = Setting.DISABLE_COOLDOWN.asBoolean();
private boolean disabledelay = Setting.DISABLE_DELAY.asBoolean(); private boolean disableDelay = Setting.DISABLE_DELAY.asBoolean();
public BlacksmithTrait() { public BlacksmithTrait() {
super("blacksmith"); super("blacksmith");
plugin = (BlacksmithPlugin) Bukkit.getServer().getPluginManager().getPlugin("Blacksmith"); plugin = (BlacksmithPlugin) Bukkit.getServer().getPluginManager().getPlugin("Blacksmith");
int i = 0; int i = 0;
for (Enchantment enchantment : Enchantment.values()) for (Enchantment enchantment : Enchantment.values()) {
enchantments[i++] = enchantment.getName(); enchantments[i++] = enchantment.getKey().asString();
}
} }
@Override @Override
public void load(DataKey key) { public void load(DataKey key) {
for (DataKey sub : key.getRelative("reforgeable-items").getIntegerSubKeys()) for (DataKey sub : key.getRelative("reforgeable-items").getIntegerSubKeys()) {
if (Material.getMaterial(sub.getString("").toUpperCase().replace('-', '_')) != null) if (Material.getMaterial(sub.getString("").toUpperCase().replace('-', '_')) != null) {
reforgeableItems.add(Material.getMaterial(sub.getString("").toUpperCase().replace('-', '_'))); reforgeAbleItems.add(Material.getMaterial(sub.getString("").toUpperCase().replace('-', '_')));
}
}
// Override defaults if they exist // Override defaults if they exist
if (key.keyExists("messages.busy-with-player")) if (key.keyExists("messages.busy-with-player")) {
busyWithPlayerMsg = key.getString("messages.busy-with-player"); busyWithPlayerMsg = key.getString("messages.busy-with-player");
if (key.keyExists("messages.busy-with-reforge")) }
if (key.keyExists("messages.busy-with-reforge")) {
busyReforgingMsg = key.getString("messages.busy-with-reforge"); busyReforgingMsg = key.getString("messages.busy-with-reforge");
if (key.keyExists("messages.cost")) }
if (key.keyExists("messages.cost")) {
costMsg = key.getString("messages.cost"); costMsg = key.getString("messages.cost");
if (key.keyExists("messages.invalid-item")) }
if (key.keyExists("messages.invalid-item")) {
invalidItemMsg = key.getString("messages.invalid-item"); invalidItemMsg = key.getString("messages.invalid-item");
if (key.keyExists("messages.start-reforge")) }
if (key.keyExists("messages.start-reforge")) {
startReforgeMsg = key.getString("messages.start-reforge"); startReforgeMsg = key.getString("messages.start-reforge");
if (key.keyExists("messages.successful-reforge")) }
if (key.keyExists("messages.successful-reforge")) {
successMsg = key.getString("messages.successful-reforge"); successMsg = key.getString("messages.successful-reforge");
if (key.keyExists("messages.fail-reforge")) }
if (key.keyExists("messages.fail-reforge")) {
failMsg = key.getString("messages.fail-reforge"); failMsg = key.getString("messages.fail-reforge");
if (key.keyExists("messages.insufficient-funds")) }
if (key.keyExists("messages.insufficient-funds")) {
insufficientFundsMsg = key.getString("messages.insufficient-funds"); insufficientFundsMsg = key.getString("messages.insufficient-funds");
if (key.keyExists("messages.cooldown-not-expired")) }
cooldownUnexpiredMsg = key.getString("messages.cooldown-not-expired"); if (key.keyExists("messages.cooldown-not-expired")) {
if (key.keyExists("messages.item-changed-during-reforge")) coolDownUnexpiredMessage = key.getString("messages.cooldown-not-expired");
}
if (key.keyExists("messages.item-changed-during-reforge")) {
itemChangedMsg = key.getString("messages.item-changed-during-reforge"); itemChangedMsg = key.getString("messages.item-changed-during-reforge");
if (key.keyExists("delays-in-seconds.minimum")) }
if (key.keyExists("delays-in-seconds.minimum")) {
minReforgeDelay = key.getInt("delays-in-seconds.minimum"); minReforgeDelay = key.getInt("delays-in-seconds.minimum");
if (key.keyExists("delays-in-seconds.maximum")) }
if (key.keyExists("delays-in-seconds.maximum")) {
maxReforgeDelay = key.getInt("delays-in-seconds.maximum"); maxReforgeDelay = key.getInt("delays-in-seconds.maximum");
if (key.keyExists("delays-in-seconds.reforge-cooldown")) }
reforgeCooldown = key.getInt("delays-in-seconds.reforge-cooldown"); if (key.keyExists("delays-in-seconds.reforge-cooldown")) {
if (key.keyExists("percent-chance-to-fail-reforge")) reforgeCoolDown = key.getInt("delays-in-seconds.reforge-cooldown");
}
if (key.keyExists("percent-chance-to-fail-reforge")) {
failChance = key.getInt("percent-chance-to-fail-reforge"); failChance = key.getInt("percent-chance-to-fail-reforge");
if (key.keyExists("maximum-enchantments")) }
if (key.keyExists("maximum-enchantments")) {
maxEnchantments = key.getInt("maximum-enchantments"); maxEnchantments = key.getInt("maximum-enchantments");
if (key.keyExists("extra-enchantments-chance")) }
if (key.keyExists("extra-enchantments-chance")) {
extraEnchantmentChance = key.getInt("extra-enchantment-chance"); extraEnchantmentChance = key.getInt("extra-enchantment-chance");
if (key.keyExists("dropitem")) }
if (key.keyExists("dropitem")) {
dropItem = key.getBoolean("dropitem"); dropItem = key.getBoolean("dropitem");
if (key.keyExists("disable-cooldown")) }
disablecooldown = key.getBoolean("disable-cooldown"); if (key.keyExists("disable-cooldown")) {
if (key.keyExists("disable-delay")) disableCoolDown = key.getBoolean("disable-cooldown");
disabledelay = key.getBoolean("disable-delay"); }
if (key.keyExists("disable-delay")) {
disableDelay = key.getBoolean("disable-delay");
}
} }
@EventHandler @EventHandler
public void onRightClick(net.citizensnpcs.api.event.NPCRightClickEvent event) { public void onRightClick(net.citizensnpcs.api.event.NPCRightClickEvent event) {
if(this.npc!=event.getNPC()) return; if (this.npc != event.getNPC()) {
return;
}
Player player = event.getClicker(); Player player = event.getClicker();
if ((disablecooldown & (cooldowns.get(player.getName()) != (null)))) if ((disableCoolDown & (coolDowns.get(player.getName()) != (null)))) {
{ coolDowns.remove(player.getName());
cooldowns.remove(player.getName());
} }
if (!player.hasPermission("blacksmith.reforge")) if (!player.hasPermission("blacksmith.reforge")) {
return; return;
}
if (cooldowns.get(player.getName()) != null) { if (coolDowns.get(player.getName()) != null) {
if (!Calendar.getInstance().after(cooldowns.get(player.getName()))) { if (!Calendar.getInstance().after(coolDowns.get(player.getName()))) {
player.sendMessage(cooldownUnexpiredMsg); player.sendMessage(coolDownUnexpiredMessage);
return; return;
} }
cooldowns.remove(player.getName()); coolDowns.remove(player.getName());
} }
ItemStack hand = player.getInventory().getItemInMainHand(); ItemStack hand = player.getInventory().getItemInMainHand();
if(session!=null){ if (session != null) {
//timeout //timeout
if ( System.currentTimeMillis() > _sessionstart + 10*1000 || this.npc.getEntity().getLocation().distance(session.player.getLocation()) > 20 ){ if (System.currentTimeMillis() > _sessionstart + 10 * 1000 || this.npc.getEntity().getLocation().distance(session.player.getLocation()) > 20) {
session = null; session = null;
} }
} }
@ -139,23 +164,24 @@ public class BlacksmithTrait extends Trait {
if (session != null) { if (session != null) {
if (!session.isInSession(player)) { if (!session.isInSession(player)) {
player.sendMessage( busyWithPlayerMsg); player.sendMessage(busyWithPlayerMsg);
return; return;
} }
if (session.isRunning()) { if (session.isRunning()) {
player.sendMessage( busyReforgingMsg); player.sendMessage(busyReforgingMsg);
return; return;
} }
if (session.handleClick()) if (session.handleClick()) {
session = null; session = null;
else } else {
reforge(npc, player); reforge(npc, player);
}
} else { } else {
if ((!plugin.isTool(hand) && !plugin.isArmor(hand)) if ((!plugin.isTool(hand) && !plugin.isArmor(hand))
|| (!reforgeableItems.isEmpty() && !reforgeableItems.contains(hand.getType()))) { || (!reforgeAbleItems.isEmpty() && !reforgeAbleItems.contains(hand.getType()))) {
player.sendMessage( invalidItemMsg); player.sendMessage(invalidItemMsg);
return; return;
} }
@ -173,9 +199,10 @@ public class BlacksmithTrait extends Trait {
@Override @Override
public void save(DataKey key) { public void save(DataKey key) {
for (int i = 0; i < reforgeableItems.size(); i++) for (int i = 0; i < reforgeAbleItems.size(); i++) {
key.getRelative("reforgeable-items").setString(String.valueOf(i), key.getRelative("reforgeable-items").setString(String.valueOf(i),
reforgeableItems.get(i).name().toLowerCase().replace('_', '-')); reforgeAbleItems.get(i).name().toLowerCase().replace('_', '-'));
}
key.setString("messages.busy-with-player", busyWithPlayerMsg); key.setString("messages.busy-with-player", busyWithPlayerMsg);
key.setString("messages.busy-with-reforge", busyReforgingMsg); key.setString("messages.busy-with-reforge", busyReforgingMsg);
@ -185,30 +212,31 @@ public class BlacksmithTrait extends Trait {
key.setString("messages.successful-reforge", successMsg); key.setString("messages.successful-reforge", successMsg);
key.setString("messages.fail-reforge", failMsg); key.setString("messages.fail-reforge", failMsg);
key.setString("messages.insufficient-funds", insufficientFundsMsg); key.setString("messages.insufficient-funds", insufficientFundsMsg);
key.setString("messages.cooldown-not-expired", cooldownUnexpiredMsg); key.setString("messages.cooldown-not-expired", coolDownUnexpiredMessage);
key.setString("messages.item-changed-during-reforge", itemChangedMsg); key.setString("messages.item-changed-during-reforge", itemChangedMsg);
key.setInt("delays-in-seconds.minimum", minReforgeDelay); key.setInt("delays-in-seconds.minimum", minReforgeDelay);
key.setInt("delays-in-seconds.maximum", maxReforgeDelay); key.setInt("delays-in-seconds.maximum", maxReforgeDelay);
key.setInt("delays-in-seconds.reforge-cooldown", reforgeCooldown); key.setInt("delays-in-seconds.reforge-cooldown", reforgeCoolDown);
key.setInt("percent-chance-to-fail-reforge", failChance); key.setInt("percent-chance-to-fail-reforge", failChance);
key.setInt("percent-chance-for-extra-enchantment", extraEnchantmentChance); key.setInt("percent-chance-for-extra-enchantment", extraEnchantmentChance);
key.setInt("maximum-enchantments", maxEnchantments); key.setInt("maximum-enchantments", maxEnchantments);
key.setBoolean("drop-item", dropItem); key.setBoolean("drop-item", dropItem);
key.setBoolean("disable-delay", disabledelay); key.setBoolean("disable-delay", disableDelay);
key.setBoolean("disable-cooldown", disablecooldown); key.setBoolean("disable-cooldown", disableCoolDown);
} }
private void reforge(NPC npc, Player player) { private void reforge(NPC npc, Player player) {
player.sendMessage( startReforgeMsg); player.sendMessage(startReforgeMsg);
//plugin.deposit(npc, player); // CitiTrader dependency outdated and broken //plugin.deposit(npc, player); // CitiTrader dependency outdated and broken
plugin.withdraw(player); plugin.withdraw(player);
session.beginReforge(); session.beginReforge();
if (npc.getEntity() instanceof Player) if (npc.getEntity() instanceof Player) {
((Player) npc.getEntity()).getInventory().setItemInMainHand(player.getInventory().getItemInMainHand()); ((Player) npc.getEntity()).getInventory().setItemInMainHand(player.getInventory().getItemInMainHand());
else } else {
((LivingEntity) npc.getEntity()).getEquipment().setItemInMainHand(player.getInventory().getItemInMainHand()); Objects.requireNonNull(((LivingEntity) npc.getEntity()).getEquipment()).setItemInMainHand(player.getInventory().getItemInMainHand());
}
player.getInventory().setItemInMainHand(null); player.getInventory().setItemInMainHand(null);
} }
@ -226,33 +254,26 @@ public class BlacksmithTrait extends Trait {
@Override @Override
public void run() { public void run() {
player.sendMessage( reforgeItemInHand() ? successMsg : failMsg); player.sendMessage(reforgeItemInHand() ? successMsg : failMsg);
if (npc.getEntity() instanceof Player) if (npc.getEntity() instanceof Player) {
((Player) npc.getEntity()).getInventory().setItemInMainHand(null); ((Player) npc.getEntity()).getInventory().setItemInMainHand(null);
else } else {
((LivingEntity) npc.getEntity()).getEquipment().setItemInMainHand(null); Objects.requireNonNull(((LivingEntity) npc.getEntity()).getEquipment()).setItemInMainHand(null);
if (!disabledelay) }
{ if (!disableDelay) {
if (dropItem) if (dropItem) {
player.getWorld().dropItemNaturally(npc.getEntity().getLocation(), reforge); player.getWorld().dropItemNaturally(npc.getEntity().getLocation(), reforge);
else { } else {
player.getInventory().addItem(reforge); player.getInventory().addItem(reforge);
/*
oldmethode ?
for (ItemStack stack : player.getInventory().addItem(reforge).values())
player.getWorld().dropItemNaturally(npc.getEntity().getLocation(), stack);
*/
} }
} } else {
else
{
player.getInventory().setItemInMainHand(reforge); player.getInventory().setItemInMainHand(reforge);
} }
session = null; session = null;
// Start cooldown // Start cooldown
Calendar wait = Calendar.getInstance(); Calendar wait = Calendar.getInstance();
wait.add(Calendar.SECOND, reforgeCooldown); wait.add(Calendar.SECOND, reforgeCoolDown);
cooldowns.put(player.getName(), wait); coolDowns.put(player.getName(), wait);
} }
private boolean reforgeItemInHand() { private boolean reforgeItemInHand() {
@ -260,9 +281,9 @@ public class BlacksmithTrait extends Trait {
if (random.nextInt(100) < failChance) { if (random.nextInt(100) < failChance) {
for (Enchantment enchantment : reforge.getEnchantments().keySet()) { for (Enchantment enchantment : reforge.getEnchantments().keySet()) {
// Remove or downgrade enchantments // Remove or downgrade enchantments
if (random.nextBoolean()) if (random.nextBoolean()) {
reforge.removeEnchantment(enchantment); reforge.removeEnchantment(enchantment);
else { } else {
if (reforge.getEnchantmentLevel(enchantment) > 1) { if (reforge.getEnchantmentLevel(enchantment) > 1) {
reforge.removeEnchantment(enchantment); reforge.removeEnchantment(enchantment);
reforge.addEnchantment(enchantment, 1); reforge.addEnchantment(enchantment, 1);
@ -270,17 +291,19 @@ public class BlacksmithTrait extends Trait {
} }
} }
// Damage the item // Damage the item
short durability = (short) (reforge.getDurability() + reforge.getDurability() * random.nextInt(8)); short durability = (short) (((Damageable) reforge).getDamage() + ((Damageable) reforge).getDamage() *
random.nextInt(8));
short maxDurability = reforge.getType().getMaxDurability(); short maxDurability = reforge.getType().getMaxDurability();
if (durability <= 0) if (durability <= 0) {
durability = (short) (maxDurability / 3); durability = (short) (maxDurability / 3);
else if (reforge.getDurability() + durability > maxDurability) } else if (((Damageable) reforge).getDamage() + durability > maxDurability) {
durability = (short) (maxDurability - random.nextInt(maxDurability - 25)); durability = (short) (maxDurability - random.nextInt(maxDurability - 25));
reforge.setDurability(durability); }
((Damageable) reforge).setDamage(durability);
return false; return false;
} }
reforge.setDurability((short) 0); ((Damageable) reforge).setDamage((short) 0);
// Add random enchantments // Add random enchantments
@ -291,10 +314,12 @@ public class BlacksmithTrait extends Trait {
else */ else */
int roll = random.nextInt(100); int roll = random.nextInt(100);
if (roll < extraEnchantmentChance && reforge.getEnchantments().keySet().size() < maxEnchantments){ if (roll < extraEnchantmentChance && reforge.getEnchantments().keySet().size() < maxEnchantments) {
Enchantment enchantment = Enchantment.getByName(enchantments[random.nextInt(enchantments.length)]); Enchantment enchantment = Enchantment.getByKey(NamespacedKey.fromString(enchantments[random.nextInt(enchantments.length)]));
if (enchantment.canEnchantItem(reforge)) reforge.addEnchantment(enchantment, random.nextInt(enchantment.getMaxLevel() - enchantment.getStartLevel()) + enchantment.getStartLevel()); if (Objects.requireNonNull(enchantment).canEnchantItem(reforge)) {
reforge.addEnchantment(enchantment, random.nextInt(enchantment.getMaxLevel() - enchantment.getStartLevel()) + enchantment.getStartLevel());
}
} }
@ -305,11 +330,11 @@ public class BlacksmithTrait extends Trait {
private boolean handleClick() { private boolean handleClick() {
// Prevent player from switching items during session // Prevent player from switching items during session
if (!reforge.equals(player.getInventory().getItemInMainHand())) { if (!reforge.equals(player.getInventory().getItemInMainHand())) {
player.sendMessage( itemChangedMsg); player.sendMessage(itemChangedMsg);
return true; return true;
} }
if (!plugin.doesPlayerHaveEnough(player)) { if (!plugin.doesPlayerHaveEnough(player)) {
player.sendMessage( insufficientFundsMsg); player.sendMessage(insufficientFundsMsg);
return true; return true;
} }
return false; return false;
@ -324,20 +349,17 @@ public class BlacksmithTrait extends Trait {
} }
private void beginReforge() { private void beginReforge() {
if (!disablecooldown) if (!disableCoolDown) {
{
taskId = plugin taskId = plugin
.getServer() .getServer()
.getScheduler() .getScheduler()
.scheduleSyncDelayedTask(plugin, this, .scheduleSyncDelayedTask(plugin, this,
(new Random().nextInt(maxReforgeDelay) + minReforgeDelay) * 20); (new Random().nextInt(maxReforgeDelay) + minReforgeDelay) * 20L);
} } else {
else
{
taskId = plugin taskId = plugin
.getServer() .getServer()
.getScheduler() .getScheduler()
.scheduleSyncDelayedTask(plugin, this,0); .scheduleSyncDelayedTask(plugin, this, 0);
} }
} }
} }

View File

@ -1,12 +1,11 @@
package net.apunch.blacksmith.util; package net.apunch.blacksmith.util;
import java.io.File;
import net.apunch.blacksmith.BlacksmithPlugin; import net.apunch.blacksmith.BlacksmithPlugin;
import net.citizensnpcs.api.util.DataKey; import net.citizensnpcs.api.util.DataKey;
import net.citizensnpcs.api.util.YamlStorage; import net.citizensnpcs.api.util.YamlStorage;
import java.io.File;
public class Settings { public class Settings {
private final YamlStorage config; private final YamlStorage config;
@ -17,11 +16,13 @@ public class Settings {
public void load() { public void load() {
config.load(); config.load();
DataKey root = config.getKey(""); DataKey root = config.getKey("");
for (Setting setting : Setting.values()) for (Setting setting : Setting.values()) {
if (!root.keyExists(setting.path)) if (!root.keyExists(setting.path)) {
root.setRaw(setting.path, setting.get()); root.setRaw(setting.path, setting.get());
else } else {
setting.set(root.getRaw(setting.path)); setting.set(root.getRaw(setting.path));
}
}
config.save(); config.save();
} }
@ -62,7 +63,7 @@ public class Settings {
START_REFORGE_MESSAGE("defaults.messages.start-reforge", "§eOk, let's see what I can do..."), START_REFORGE_MESSAGE("defaults.messages.start-reforge", "§eOk, let's see what I can do..."),
SUCCESS_MESSAGE("defaults.messages.successful-reforge", "There you go! All better!"); SUCCESS_MESSAGE("defaults.messages.successful-reforge", "There you go! All better!");
private String path; private final String path;
private Object value; private Object value;
Setting(String path, Object value) { Setting(String path, Object value) {
@ -75,10 +76,12 @@ public class Settings {
} }
public double asDouble() { public double asDouble() {
if (value instanceof String) if (value instanceof String) {
return Double.valueOf((String) value); return Double.parseDouble((String) value);
if (value instanceof Integer) }
if (value instanceof Integer) {
return (Integer) value; return (Integer) value;
}
return (Double) value; return (Double) value;
} }

View File

@ -1,13 +1,18 @@
name: Blacksmith name: Blacksmith
author: aPunch, jrbudda, HurricanKai author: EpicKnarvik97, aPunch, jrbudda, HurricanKai
version: 1.16 authors: [ EpicKnarvik97, aPunch, jrbudda, HurricanKai ]
version: 1.18.1
main: net.apunch.blacksmith.BlacksmithPlugin main: net.apunch.blacksmith.BlacksmithPlugin
depend: [Citizens, Vault] depend: [ Citizens, Vault ]
softdepend: [HyperConomy] softdepend: [ HyperConomy ]
api-version: 1.16 api-version: 1.18
commands: commands:
blacksmithreload: blacksmithreload:
permission: blacksmith.reload permission: blacksmith.reload
description: reloads the config file for Blacksmith description: reloads the config file for Blacksmith
permissions:
blacksmith.reload:
description: Allows the player to run the /reload command
default: op