Files
src
build.gradle
Code
7 1,689
src/main/java/com/mysticenchants/MysticEnchants.java
package com.mysticenchants;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XSound;
import com.cryptomorin.xseries.XAttribute;
import com.cryptomorin.xseries.particles.XParticle;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.NamespacedKey;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.SlimeSplitEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
public final class MysticEnchants extends JavaPlugin implements Listener {
private enum Rareza {
COMUN("Común", "STONE", "§a", 1, 2),
RARO("Raro", "GRANITE", "§9", 1, 3),
EPICO("Épico", "DEEPSLATE", "§5", 2, 4),
LEGENDARIO("Legendario", "ANCIENT_DEBRIS", "§6", 3, 5),
MITICO("Mítico", "NETHERITE_BLOCK", "§4", 4, 5);
final String nombre;
final String material;
final String color;
final int inicial;
final int maximo;
Rareza(String nombre, String material, String color, int inicial, int maximo) {
this.nombre = nombre;
this.material = material;
this.color = color;
this.inicial = inicial;
this.maximo = maximo;
}
}
private static final String MARCADOR = "§0§0MysticEnchants";
private Economy economia;
private NamespacedKey tipo, rareza, nivel, experiencia, encantamiento, mimic;
private final Map<UUID, Integer> compras = new HashMap<>();
final Map<UUID, Long> cooldowns = new HashMap<>();
private final Map<UUID, BukkitRunnable> animaciones = new HashMap<>();
private final ExecutorService archivos = Executors.newSingleThreadExecutor();
private File datos;
private BonificacionesSet bonificacionesSet;
@Override
public void onEnable() {
saveDefaultConfig();
tipo = new NamespacedKey(this, "tipo");
rareza = new NamespacedKey(this, "rareza");
nivel = new NamespacedKey(this, "nivel");
experiencia = new NamespacedKey(this, "experiencia");
encantamiento = new NamespacedKey(this, "encantamiento");
mimic = new NamespacedKey(this, "mimic");
RegisteredServiceProvider<Economy> proveedor = getServer().getServicesManager().getRegistration(Economy.class);
if (proveedor == null || proveedor.getProvider() == null) {
getLogger().severe("Se necesita Vault y un proveedor de economía activo.");
getServer().getPluginManager().disablePlugin(this);
return;
}
economia = proveedor.getProvider();
datos = new File(getDataFolder(), "datos.yml");
YamlConfiguration guardado = YamlConfiguration.loadConfiguration(datos);
if (guardado.isConfigurationSection("compras")) {
for (String id : guardado.getConfigurationSection("compras").getKeys(false)) {
try {
compras.put(UUID.fromString(id), guardado.getInt("compras." + id));
} catch (IllegalArgumentException ex) {
getLogger().warning("UUID inválido en datos.yml: " + id);
}
}
}
if (guardado.isConfigurationSection("segunda-oportunidad")) {
for (String id : guardado.getConfigurationSection("segunda-oportunidad").getKeys(false)) {
try { cooldowns.put(UUID.fromString(id), guardado.getLong("segunda-oportunidad." + id)); }
catch (IllegalArgumentException ex) { getLogger().warning("UUID inválido en datos.yml: " + id); }
}
}
getServer().getPluginManager().registerEvents(this, this);
getServer().getPluginManager().registerEvents(new EfectosMisticos(this), this);
getServer().getPluginManager().registerEvents(new PoderesLeyenda(this), this);
bonificacionesSet = new BonificacionesSet(this);
getServer().getPluginManager().registerEvents(bonificacionesSet, this);
getServer().getScheduler().runTaskTimer(this, this::guardarAsincrono, 1200L, 1200L);
}
@Override
public void onDisable() {
if (bonificacionesSet != null) bonificacionesSet.cerrar();
for (BukkitRunnable tarea : animaciones.values()) tarea.cancel();
animaciones.clear();
if (datos != null) guardarAsincrono();
archivos.shutdown();
try {
if (!archivos.awaitTermination(5, TimeUnit.SECONDS)) getLogger().warning("El guardado de datos sigue pendiente.");
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
private void guardarAsincrono() {
Map<UUID, Integer> copia = new HashMap<>(compras);
Map<UUID, Long> copiaCooldowns = new HashMap<>(cooldowns);
archivos.execute(() -> {
YamlConfiguration yaml = new YamlConfiguration();
copia.forEach((id, cantidad) -> yaml.set("compras." + id, cantidad));
copiaCooldowns.forEach((id, fecha) -> yaml.set("segunda-oportunidad." + id, fecha));
try {
yaml.save(datos);
} catch (IOException ex) {
getLogger().severe("No se pudieron guardar los datos: " + ex.getMessage());
}
});
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player jugador)) {
sender.sendMessage("Solo los jugadores pueden usar este comando.");
return true;
}
if (args.length != 1 || !args[0].equalsIgnoreCase("gacha")) {
jugador.sendMessage("§eUso: /runas gacha");
return true;
}
Menu menu = new Menu();
double precio = precio();
ItemStack icono = crearObjeto("CHEST", "§dBloque misterioso", Arrays.asList(
"§7Precio: §e" + economia.format(precio), "§aComún: 59,5% §8| §9Raro: 25%",
"§5Épico: 10% §8| §6Legendario: 5%", "§4Mítico: 0,5%", "§eHaz clic para comprar."));
menu.inventario.setItem(13, icono);
jugador.openInventory(menu.inventario);
return true;
}
private double precio() {
double valor = getConfig().getDouble("precio-gacha", 1000.0);
return Double.isFinite(valor) && valor >= 0 ? valor : 1000.0;
}
private static final class Menu implements InventoryHolder {
private final Inventory inventario = Bukkit.createInventory(this, 27, "§5Ruleta de runas");
@Override public Inventory getInventory() { return inventario; }
}
@EventHandler
public void alClic(InventoryClickEvent evento) {
if (!(evento.getView().getTopInventory().getHolder() instanceof Menu)) return;
evento.setCancelled(true);
if (evento.getRawSlot() != 13 || !(evento.getWhoClicked() instanceof Player jugador)) return;
if (jugador.getInventory().firstEmpty() == -1) {
jugador.sendMessage("§cNecesitas un espacio libre en el inventario.");
return;
}
EconomyResponse respuesta = economia.withdrawPlayer(jugador, precio());
if (!respuesta.transactionSuccess()) {
jugador.sendMessage("§cNo se pudo completar la compra: " + respuesta.errorMessage);
return;
}
int tirada = ThreadLocalRandom.current().nextInt(1000);