From b8ec805f1c2a9fe3ae929b913edf2e15030c9c12 Mon Sep 17 00:00:00 2001 From: EpicKnarvik97 Date: Sun, 2 Oct 2022 23:50:07 +0200 Subject: [PATCH] Improves random enchantment level logic --- .../blacksmith/trait/ReforgeSession.java | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/src/main/java/net/knarcraft/blacksmith/trait/ReforgeSession.java b/src/main/java/net/knarcraft/blacksmith/trait/ReforgeSession.java index 91cd94d..583aa0a 100644 --- a/src/main/java/net/knarcraft/blacksmith/trait/ReforgeSession.java +++ b/src/main/java/net/knarcraft/blacksmith/trait/ReforgeSession.java @@ -12,7 +12,9 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; +import java.util.ArrayList; import java.util.Calendar; +import java.util.List; import java.util.Objects; import java.util.Random; import java.util.logging.Level; @@ -119,20 +121,27 @@ public class ReforgeSession implements Runnable { // Abort if randomness isn't on our side, or if max enchantments has been reached return; } - // Choose a random enchantment - Enchantment enchantment; - int maxRetries = 100; - int retries = 0; - do { - // Try to find a working enchantment for the re-forged item up to maxRetries times - enchantment = Enchantment.getByKey(NamespacedKey.fromString(enchantments[random.nextInt(enchantments.length)])); - } while ((enchantment == null || !enchantment.canEnchantItem(itemToReforge)) && (retries++ < maxRetries)); - if (enchantment != null && enchantment.canEnchantItem(itemToReforge)) { - int randomBound = enchantment.getMaxLevel() - enchantment.getStartLevel(); + //Find usable enchantments first + List usableEnchantments = new ArrayList<>(); + for (String enchantmentName : enchantments) { + Enchantment enchantment = Enchantment.getByKey(NamespacedKey.fromString(enchantmentName)); + if (enchantment != null && enchantment.canEnchantItem(itemToReforge)) { + usableEnchantments.add(enchantment); + } + } + + //Choose a random enchantment + Enchantment randomEnchantment = usableEnchantments.get(random.nextInt(usableEnchantments.size())); + if (randomEnchantment != null) { + int randomBound = randomEnchantment.getMaxLevel() + 1; //A workaround for the random method's bound sometimes being negative if (randomBound >= 0) { - itemToReforge.addEnchantment(enchantment, random.nextInt(randomBound) + enchantment.getStartLevel()); + int existingLevel = itemToReforge.getEnchantmentLevel(randomEnchantment); + /* Add a random enchantment whose level is no lower than the start level, and no lower than the + existing level (to prevent making the item worse) */ + itemToReforge.addEnchantment(randomEnchantment, Math.max(Math.max(random.nextInt(randomBound), + randomEnchantment.getStartLevel()), existingLevel)); } } }