Improves random enchantment level logic

This commit is contained in:
Kristian Knarvik 2022-10-02 23:50:07 +02:00
parent f058f4eec8
commit b8ec805f1c

View File

@ -12,7 +12,9 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Random; import java.util.Random;
import java.util.logging.Level; 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 // Abort if randomness isn't on our side, or if max enchantments has been reached
return; 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)) { //Find usable enchantments first
int randomBound = enchantment.getMaxLevel() - enchantment.getStartLevel(); List<Enchantment> 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 //A workaround for the random method's bound sometimes being negative
if (randomBound >= 0) { 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));
} }
} }
} }