crafty_yt.

1.21.11 paper

📎 1 file 2,968 chars
📄
pasted-code-1795340492906.txt
txt 24 lines
▶
Create a complete, lag-free Minecraft Paper/Spigot plugin (Java 21, API 1.21+) for a custom "Ruin Sword" event. Everything must be customizable in config.yml with a /ruinsword reload command.
1. The Custom Item (Ruin Sword):
• Base Material: Netherite Sword (configurable).
• Display Name: &c&lRuin Sword (Red, Bold - configurable).
• Lore: Configurable list of lore lines.
• Custom Model Data: Supports string-based item model / custom model data key RuinSword (or integer fallback if older version, configurable).
• Enchantments: Mending (1), Unbreaking (3), Sharpness (6) — ensure unsafe enchantments are allowed so Sharpness 6 applies properly.
• Combat Ability: Track hits per player using PersistentDataContainer or a Map. Every 20th hit (configurable) with the Ruin Sword spawns an instant explosion / primed TNT effect directly at the victim's location. The explosion must NOT damage the attacker or break blocks (configurable), only damaging the victim and nearby entities.
• Toggle: Include a boolean option in config.yml (sword-ability-enabled: true) to toggle the explosion ability on or off globally.
2. The Event Command (/startruinevent):
• Permission: ruinsword.admin (OP by default).
• Random Coordinate Generation: When /startruinevent is executed, pick a random X and Z coordinate strictly within a 500 to 1000 block radius (inclusive: minimum 500 blocks away, maximum 1000 blocks away—never 499 or 1001) around the center point X: -168, Y: 73, Z: 62 (all center coordinates and min/max radius values must be configurable). Find the highest solid block at the chosen X and Z so it doesn't spawn underground.
• BossBar & Countdown: Display a RED BossBar (BarColor.RED) to all online players with red text showing the target X, Y, Z coordinates and a live countdown timer starting at 30 minutes (1800 seconds) (duration, BossBar color, and text format must be configurable).
• Sky Drop: When the 30-minute countdown reaches 00:00, remove the BossBar, announce the drop in chat, and spawn the Ruin Sword as a glowing, invulnerable dropped item falling from the sky (e.g., 50 blocks above the target ground Y coordinate) with particle/lightning visual effects (no fire/damage) so players can claim it.
3. Full Configuration (config.yml):
Make EVERY single value configurable:
• Event center coordinates (x: -168, y: 73, z: 62) and world name
• Min radius (500) and max radius (1000)
• Countdown duration in seconds (1800)
• BossBar text format (with placeholders {x}, {y}, {z}, {time}), color (RED), and style
• Sky drop height offset, lightning/particle toggles, and broadcast messages
• Sword material, display name, lore, custom model data (RuinSword), and enchantments list
• Sword ability toggle (true/false), hits required (20), explosion power, block-damage (false), and self-damage (false)
Ensure clean code, proper tab completion for commands (/startruinevent, /stopruinevent, /ruinsword reload), and null-checks so there are no console errors.
Kodari AI
KodariToday at 9:42 am 3
RuinSwordEvent
A complete Paper plugin for a custom Ruin Sword event. Features a configurable netherite sword with custom lore, enchantments, and a combat ability that triggers an explosion every 20th hit (toggleable). Includes /startruinevent command that generates random coordinates within configurable radius, displays a red BossBar countdown to all players, and spawns a glowing invulnerable sword drop from the sky with lightning effects when time expires. All values configurable in config.yml with /ruinsword reload, plus /stopruinevent command and full tab completion.
  • Add the configurable sword, hit counter and explosion ability.

  • Add the timed event, BossBar, sky drop and admin commands.

  • Use Paper 1.21.11 item models, with an integer custom-model-data fallback.

Created the Ruin Sword event plugin with configurable sword abilities, countdown, BossBar and sky drop, plus admin commands.

The item model and integer custom-model-data fallback are configurable. Active events retain their settings until the next event after a reload.

crafty_yt.

add a /ruinsword give command

Kodari AI
KodariToday at 9:47 am 1
  • Add /ruinsword give [player] with admin permission and tab completion.

  • Give the configured sword, dropping it safely if the inventory is full.

Added /ruinsword give [player] with tab completion. It requires ruinsword.admin; omit the player name to give yourself the sword.

crafty_yt.

make it explode bigger, and use the text custom model data in the new 1.21.11 not the number, like this command gives me he right one /give @s netherite_sword[custom_model_data={strings:["RuinSword"]}], fix this so it gives the right sword model, and make it explode bigger like a normal tnt explosion

Kodari AI
KodariToday at 9:52 am 1
  1. Set the default explosion power to match TNT.

  2. Put RuinSword in the item’s string custom model data.

  • Set explosion power to 4.0, matching normal TNT.

  • Changed the sword to use string custom model data RuinSword, without overriding its item model. Integer values remain supported.

  • Existing default settings migrate on plugin startup. Re-give the sword to get the corrected model data.

crafty_yt.

Fiix the sword so when it explodes it doesn't kill a player with a totem and 2 lines of health, so only explosion and the swords damage, no extra damage, because it killa a player with maxed armor 2 lines of health and a totem with an explosion, totem must save the player and the sword must not kill the player again

Kodari AI
KodariToday at 6:02 pm 2
  • Apply the sword hit before the explosion.

  • If that hit activates a totem, prevent the same explosion from damaging that player again.

Fixed the damage order: the sword hit now lands before the explosion. If the hit activates a totem, that explosion won’t damage the saved player again.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
settings.gradle
Code
5 481
src/main/java/com/kodari/ruinsword/RuinSwordPlugin.java
package com.kodari.ruinsword;

import com.cryptomorin.xseries.XEnchantment;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.particles.XParticle;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityResurrectEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.components.CustomModelDataComponent;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

public final class RuinSwordPlugin extends JavaPlugin implements Listener, CommandExecutor, TabCompleter {
    private NamespacedKey swordKey;
    private final Map<UUID, Integer> hits = new HashMap<>();
    private final Map<UUID, List<boolean[]>> pendingHits = new HashMap<>();
    private UUID protectedAttacker;
    private UUID protectedVictim;
    private BossBar bossBar;
    private BukkitTask countdownTask;
    private Location target;
    private int remaining;
    private int duration;
    private String barFormat;
    private String droppedMessage;
    private int dropOffset;
    private boolean lightning;
    private boolean particles;
    private String particleType;
    private int particleCount;
    private ItemStack eventSword;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        boolean migrated = false;
        if ("ruinsword:ruinsword".equals(getConfig().getString("sword.model.item-model"))) {
            getConfig().set("sword.model.item-model", "");
            migrated = true;
        }
        if (getConfig().isInt("sword.model.custom-model-data") && getConfig().getInt("sword.model.custom-model-data") == 0) {
            getConfig().set("sword.model.custom-model-data", "RuinSword");
            migrated = true;
        }
        if (getConfig().getDouble("ability.explosion-power") == 3.0) {
            getConfig().set("ability.explosion-power", 4.0);
            migrated = true;
        }
        if (migrated) saveConfig();
        swordKey = new NamespacedKey(this, "ruin_sword");
        getServer().getPluginManager().registerEvents(this, this);
        for (String name : new String[]{"startruinevent", "stopruinevent", "ruinsword"}) {
            org.bukkit.command.PluginCommand command = getCommand(name);
            if (command != null) {
                command.setExecutor(this);
                command.setTabCompleter(this);
            }
        }
    }

    @Override
    public void onDisable() {
        clearEvent();
        hits.clear();
        pendingHits.clear();
    }

    private String color(String value) {
        return ChatColor.translateAlternateColorCodes('&', value == null ? "" : value);
    }

    private String message(String key) {
        return color(getConfig().getString("event.messages." + key, ""));
    }

    private String format(String text, Location location, int seconds) {
        return color(text.replace("{x}", Integer.toString(location.getBlockX()))
                .replace("{y}", Integer.toString(location.getBlockY()))
                .replace("{z}", Integer.toString(location.getBlockZ()))
                .replace("{time}", String.format(Locale.ROOT, "%02d:%02d", seconds / 60, seconds % 60)));
    }

    private ItemStack createSword() {
        String material = getConfig().getString("sword.material", "NETHERITE_SWORD");
        ItemStack item = XMaterial.matchXMaterial(material).map(XMaterial::parseItem).orElse(null);
        if (item == null || item.getType().isAir()) {
            getLogger().warning("Invalid sword material: " + material);
            return null;
        }
        ItemMeta meta = item.getItemMeta();
        if (meta == null) return null;
        meta.setDisplayName(color(getConfig().getString("sword.name", "&c&lRuin Sword")));
        List<String> lore = new ArrayList<>();
        for (String line : getConfig().getStringList("sword.lore")) lore.add(color(line));
        meta.setLore(lore);
        meta.getPersistentDataContainer().set(swordKey, PersistentDataType.BYTE, (byte) 1);
        String model = getConfig().getString("sword.model.item-model", "");
        if (model != null && !model.isBlank()) {
            NamespacedKey key = NamespacedKey.fromString(model.toLowerCase(Locale.ROOT), this);
            if (key != null) meta.setItemModel(key);
            else getLogger().warning("Invalid item model key: " + model);
        }
        Object modelData = getConfig().get("sword.model.custom-model-data", "RuinSword");
        if (modelData instanceof Number) {
            int value = ((Number) modelData).intValue();
            if (value != 0) meta.setCustomModelData(value);
        } else if (modelData instanceof String && !((String) modelData).isBlank()) {
            CustomModelDataComponent component = meta.getCustomModelDataComponent();
            component.setStrings(Collections.singletonList((String) modelData));
            meta.setCustomModelDataComponent(component);
        }
        ConfigurationSection enchants = getConfig().getConfigurationSection("sword.enchantments");
        if (enchants != null) {
            for (String name : enchants.getKeys(false)) {
                int level = enchants.getInt(name);
                XEnchantment.matchXEnchantment(name).ifPresentOrElse(enchantment -> {
                    if (level > 0 && enchantment.getEnchant() != null) meta.addEnchant(enchantment.getEnchant(), level, true);
                }, () -> getLogger().warning("Invalid enchantment: " + name));
            }
        }
        item.setItemMeta(meta);
        return item;
    }

    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onHit(EntityDamageByEntityEvent event) {
        if (!(event.getDamager() instanceof Player player) || !getConfig().getBoolean("sword-ability-enabled", true)) return;
        if (event.getCause() != EntityDamageEvent.DamageCause.ENTITY_ATTACK
                && event.getCause() != EntityDamageEvent.DamageCause.ENTITY_SWEEP_ATTACK) return;
        ItemStack item = player.getInventory().getItemInMainHand();
        ItemMeta meta = item.getItemMeta();
        if (meta == null || !meta.getPersistentDataContainer().has(swordKey, PersistentDataType.BYTE)) return;
        int required = Math.max(1, getConfig().getInt("ability.hits-required", 20));
        int count = hits.getOrDefault(player.getUniqueId(), 0) + 1;
        if (count < required) {
            hits.put(player.getUniqueId(), count);
            return;
        }
        hits.remove(player.getUniqueId());
        float power = (float) Math.max(0.0, getConfig().getDouble("ability.explosion-power", 4.0));
        boolean blockDamage = getConfig().getBoolean("ability.block-damage", false);
        boolean selfDamage = getConfig().getBoolean("ability.self-damage", false);
        UUID victimId = event.getEntity().getUniqueId();
        Location explosionLocation = event.getEntity().getLocation();
        boolean[] resurrected = {false};
        pendingHits.computeIfAbsent(victimId, ignored -> new ArrayList<>()).add(resurrected);
        Bukkit.getScheduler().runTask(this, () -> {
            List<boolean[]> pending = pendingHits.get(victimId);
            if (pending != null) {
                pending.remove(resurrected);
                if (pending.isEmpty()) pendingHits.remove(victimId);
            }
            UUID previousAttacker = protectedAttacker;
            UUID previousVictim = protectedVictim;
            protectedAttacker = selfDamage ? null : player.getUniqueId();
            protectedVictim = resurrected[0] ? victimId : null;
            try {
                explosionLocation.getWorld().createExplosion(explosionLocation, power, false, blockDamage, player);
            } finally {
                protectedAttacker = previousAttacker;
                protectedVictim = previousVictim;
            }
        });
    }

    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onResurrect(EntityResurrectEvent event) {
        List<boolean[]> pending = pendingHits.get(event.getEntity().getUniqueId());