Files
src
build.gradle
README.md
settings.gradle
Code
6 493
src/main/java/com/kodari/custommaces/CustomMaces.java
package com.kodari.custommaces;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XPotion;
import com.cryptomorin.xseries.XSound;
import com.cryptomorin.xseries.particles.XParticle;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Particle;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public final class CustomMaces extends JavaPlugin implements Listener {
private static final List<String> IDS = Arrays.asList("stormbreaker", "blackhole", "hell", "frost", "wind");
private final Map<String, Long> cooldowns = new HashMap<>();
private final Map<UUID, Long> stormGuards = new HashMap<>();
private final Map<UUID, Long> frostGuards = new HashMap<>();
private final Map<UUID, Long> safeFalls = new HashMap<>();
private NamespacedKey itemId;
private boolean reflectingDamage;
@Override
public void onEnable() {
saveDefaultConfig();
itemId = new NamespacedKey(this, "mace_id");
registerRecipes();
Bukkit.getPluginManager().registerEvents(this, this);
getCommand("custommaces").setExecutor(this::command);
}
private ItemStack makeItem(String id, int amount) {
ItemStack item = XMaterial.matchXMaterial("MACE").map(XMaterial::parseItem).orElseThrow();
item.setAmount(amount);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', getConfig().getString("maces." + id + ".name", id)));
meta.setItemModel(new NamespacedKey("custommaces", id));
meta.getPersistentDataContainer().set(itemId, PersistentDataType.STRING, id);
item.setItemMeta(meta);
return item;
}
private String idOf(ItemStack item) {
if (item == null || !item.hasItemMeta() || XMaterial.matchXMaterial(item.getType()) != XMaterial.matchXMaterial("MACE").orElse(null)) return null;
String id = item.getItemMeta().getPersistentDataContainer().get(itemId, PersistentDataType.STRING);
return IDS.contains(id) ? id : null;
}
private NamespacedKey recipeKey(String id) { return new NamespacedKey(this, id); }
private void registerRecipes() {
for (String id : IDS) {
Bukkit.removeRecipe(recipeKey(id));
String path = "maces." + id + ".recipe";
List<String> shape = getConfig().getStringList(path + ".shape");
ConfigurationSection ingredients = getConfig().getConfigurationSection(path + ".ingredients");
if (shape.size() != 3 || shape.stream().anyMatch(row -> row.length() != 3) || ingredients == null) {
getLogger().warning("Invalid recipe for " + id);
continue;
}
try {
ShapedRecipe recipe = new ShapedRecipe(recipeKey(id), makeItem(id, 1));
recipe.shape(shape.toArray(new String[0]));
for (String key : ingredients.getKeys(false)) {
if (key.length() != 1 || key.charAt(0) == ' ') throw new IllegalArgumentException("Invalid ingredient key " + key);
Material material = XMaterial.matchXMaterial(ingredients.getString(key, "")).map(XMaterial::parseMaterial).orElseThrow();
recipe.setIngredient(key.charAt(0), material);
}
if (!Bukkit.addRecipe(recipe)) getLogger().warning("Could not register recipe for " + id);
} catch (IllegalArgumentException | java.util.NoSuchElementException ex) {
getLogger().warning("Invalid recipe for " + id + ": " + ex.getMessage());
}
}
}
@EventHandler(ignoreCancelled = true)
public void onCraft(CraftItemEvent event) {
if (!(event.getRecipe() instanceof ShapedRecipe)) return;
ShapedRecipe recipe = (ShapedRecipe) event.getRecipe();
if (!recipe.getKey().getNamespace().equals(getName().toLowerCase(java.util.Locale.ROOT)) || !IDS.contains(recipe.getKey().getKey())) return;
for (ItemStack ingredient : event.getInventory().getMatrix()) {
if (idOf(ingredient) != null) {
event.setCancelled(true);
event.getWhoClicked().sendMessage(ChatColor.RED + "Custom maces cannot be used as recipe ingredients.");
return;
}
}
}
private double value(String id, String key, int power) {
List<Double> values = getConfig().getDoubleList("maces." + id + "." + key);
return values.size() > power ? Math.max(0, values.get(power)) : 0;
}
@EventHandler(ignoreCancelled = true)
public void onInteract(PlayerInteractEvent event) {
if (event.getHand() != EquipmentSlot.HAND) return;
Player player = event.getPlayer();
String id = idOf(player.getInventory().getItemInMainHand());
if (id == null) return;
Action action = event.getAction();
boolean right = action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK;
boolean left = action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK;
if (!right && !(left && player.isSneaking())) return;
event.setCancelled(true);
if (!player.hasPermission("custommaces.use." + id)) { player.sendMessage(ChatColor.RED + "You cannot use this mace."); return; }
int power = right ? (player.isSneaking() ? 1 : 0) : 2;
String key = player.getUniqueId() + ":" + id + ":" + power;
long now = System.currentTimeMillis();
long remaining = cooldowns.getOrDefault(key, 0L) - now;
if (remaining > 0) { player.sendActionBar(Component.text("Cooldown: " + (long) Math.ceil(remaining / 1000.0) + "s")); return; }
if (power == 0 && !id.equals("blackhole") && target(player, range(id)) == null) {
player.sendActionBar(Component.text("No target in range"));
return;
}
cooldowns.put(key, now + (long) (value(id, "cooldown-seconds", power) * 1000));
player.sendActionBar(Component.text("Power " + (power + 1) + " activated"));
activate(player, id, power, value(id, "damage-hearts", power) * 2.0);
}
private double range(String id) { return id.equals("stormbreaker") ? 20 : id.equals("wind") ? 10 : 12; }
private LivingEntity target(Player player, double range) {
org.bukkit.util.RayTraceResult result = player.getWorld().rayTraceEntities(player.getEyeLocation(), player.getEyeLocation().getDirection(), range, 0.5,
entity -> entity instanceof LivingEntity && entity != player && !entity.isDead());
if (result == null || !(result.getHitEntity() instanceof LivingEntity)) return null;
LivingEntity entity = (LivingEntity) result.getHitEntity();
return player.hasLineOfSight(entity) ? entity : null;
}
private List<LivingEntity> enemies(Player player, Location center, double radius) {
List<LivingEntity> result = new ArrayList<>();
for (Entity entity : center.getWorld().getNearbyEntities(center, radius, radius, radius)) {
if (entity instanceof LivingEntity && entity != player && !entity.isDead() && entity.getLocation().distanceSquared(center) <= radius * radius) result.add((LivingEntity) entity);
}
return result;
}
private void damage(Player source, LivingEntity target, double amount) { if (amount > 0 && !target.isDead()) target.damage(amount, source); }
private void potion(LivingEntity entity, String name, int ticks, int amplifier) {
XPotion.matchXPotion(name).map(p -> p.buildPotionEffect(ticks, amplifier)).ifPresent(entity::addPotionEffect);
}
private void particle(Location location, String name, int count, double spread) {
XParticle.of(name).ifPresent(p -> location.getWorld().spawnParticle(p.get(), location, count, spread, spread, spread, 0.02));
}
private void sound(Player player, String name) { XSound.matchXSound(name).ifPresent(s -> s.play(player)); }
private void push(LivingEntity entity, Location origin, double strength, double up) {
Vector v = entity.getLocation().toVector().subtract(origin.toVector()).setY(0);
if (v.lengthSquared() < 0.0001) v = new Vector(1, 0, 0);
entity.setVelocity(v.normalize().multiply(strength).setY(up));
}
private void pull(LivingEntity entity, Location center, double strength) {
Vector v = center.toVector().subtract(entity.getLocation().toVector());
if (v.lengthSquared() > 0.01) entity.setVelocity(v.normalize().multiply(strength));
}
private void ring(Location center, String particle, double radius, int step) {
for (int i = 0; i < 24; i++) {
double angle = 2 * Math.PI * i / 24 + step * 0.2;
particle(center.clone().add(Math.cos(angle) * radius, 0.3 + (i % 4) * 0.3, Math.sin(angle) * radius), particle, 1, 0);
}
}
private void activate(Player p, String id, int power, double damage) {
Location center = p.getLocation();
if (id.equals("stormbreaker")) {
sound(p, "ENTITY_LIGHTNING_BOLT_THUNDER");
if (power == 0) {
LivingEntity t = target(p, 20); if (t == null) return;
t.getWorld().strikeLightningEffect(t.getLocation()); damage(p, t, damage);
particle(t.getLocation(), "ELECTRIC_SPARK", 60, 1); particle(t.getLocation(), "CLOUD", 30, 1);
} else if (power == 1) {
for (LivingEntity t : enemies(p, center, 6)) { damage(p, t, damage); push(t, center, 1.3, 0.5); }
ring(center, "ELECTRIC_SPARK", 6, 0); particle(center, "CLOUD", 60, 2);