No chat to show

This project's files are all here to explore.

Files
src
pom.xml
README.md
Code
5 698
src/main/java/com/kage/smp/KageSystem.java
package com.kage.smp;

import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.command.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.*;
import org.bukkit.event.player.*;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.Vector;

import java.io.File;
import java.sql.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public final class KageSystem extends JavaPlugin implements Listener, CommandExecutor, TabCompleter {
    private Connection db;
    private NamespacedKey menuKey;
    private NamespacedKey abilityKey;
    private final Map<UUID, Map<String, Long>> cooldowns = new ConcurrentHashMap<>();
    private final Set<UUID> nextHitBonus = ConcurrentHashMap.newKeySet();
    private final Set<UUID> nextArrow = ConcurrentHashMap.newKeySet();
    private final Map<UUID, Long> shieldUntil = new ConcurrentHashMap<>();
    private final Map<UUID, Boolean> previousAllowFlight = new ConcurrentHashMap<>();
    private final Map<UUID, Boolean> previousFlying = new ConcurrentHashMap<>();
    private final Map<UUID, Long> lastKillFrom = new ConcurrentHashMap<>();
    private final Map<UUID, Map<String, Integer>> dailyKills = new ConcurrentHashMap<>();
    private final Map<UUID, Long> dailyReset = new ConcurrentHashMap<>();

    @Override public void onEnable() {
        saveDefaultConfig();
        menuKey = new NamespacedKey(this, "kage_menu");
        abilityKey = new NamespacedKey(this, "kage_ability");
        try { openDatabase(); } catch (SQLException e) { getLogger().severe("Database startup failed: " + e.getMessage()); getServer().getPluginManager().disablePlugin(this); return; }
        Objects.requireNonNull(getCommand("kagesmp")).setExecutor(this);
        Objects.requireNonNull(getCommand("kagesmp")).setTabCompleter(this);
        Objects.requireNonNull(getCommand("kp")).setExecutor(this);
        Objects.requireNonNull(getCommand("kp")).setTabCompleter(this);
        Objects.requireNonNull(getCommand("bounty")).setExecutor(this);
        getServer().getPluginManager().registerEvents(this, this);
        getLogger().info("KageSystem enabled. Check config.yml before production use.");
    }
    @Override public void onDisable() {
        for (UUID id : previousAllowFlight.keySet()) restoreFlight(Bukkit.getPlayer(id));
        try { if (db != null && !db.isClosed()) db.close(); } catch (SQLException ignored) {}
    }
    private void openDatabase() throws SQLException {
        if (!getDataFolder().exists()) getDataFolder().mkdirs();
        db = DriverManager.getConnection("jdbc:sqlite:" + new File(getDataFolder(), "kagesystem.db").getAbsolutePath());
        try (Statement s = db.createStatement()) {
            s.executeUpdate("CREATE TABLE IF NOT EXISTS players (uuid TEXT PRIMARY KEY, kp INTEGER NOT NULL DEFAULT 0)");
            s.executeUpdate("CREATE TABLE IF NOT EXISTS unlocks (uuid TEXT NOT NULL, ability TEXT NOT NULL, PRIMARY KEY(uuid, ability))");
        }
    }
    private synchronized int kp(UUID id) {
        try (PreparedStatement p = db.prepareStatement("SELECT kp FROM players WHERE uuid=?")) {
            p.setString(1, id.toString()); try (ResultSet r = p.executeQuery()) { return r.next() ? r.getInt(1) : 0; }
        } catch (SQLException e) { getLogger().warning(e.getMessage()); return 0; }
    }
    private synchronized boolean changeKp(UUID id, int delta) {
        try {
            db.setAutoCommit(false);
            try (PreparedStatement p = db.prepareStatement("INSERT OR IGNORE INTO players(uuid,kp) VALUES(?,0)")) { p.setString(1,id.toString()); p.executeUpdate(); }
            int current = kp(id);
            if (current + delta < 0) { db.rollback(); return false; }
            try (PreparedStatement p = db.prepareStatement("UPDATE players SET kp=? WHERE uuid=?")) { p.setInt(1,current+delta); p.setString(2,id.toString()); p.executeUpdate(); }
            db.commit(); return true;
        } catch (SQLException e) { try { db.rollback(); } catch (SQLException ignored) {} getLogger().warning(e.getMessage()); return false; }
        finally { try { db.setAutoCommit(true); } catch (SQLException ignored) {} }
    }
    private synchronized boolean owned(UUID id, String ability) {
        try (PreparedStatement p = db.prepareStatement("SELECT 1 FROM unlocks WHERE uuid=? AND ability=?")) {
            p.setString(1,id.toString()); p.setString(2,ability); try (ResultSet r=p.executeQuery()) { return r.next(); }
        } catch (SQLException e) { return false; }
    }
    private synchronized boolean unlock(UUID id, String ability) {
        try (PreparedStatement p = db.prepareStatement("INSERT OR IGNORE INTO unlocks(uuid,ability) VALUES(?,?)")) {
            p.setString(1,id.toString()); p.setString(2,ability); return p.executeUpdate() == 1;
        } catch (SQLException e) { getLogger().warning(e.getMessage()); return false; }
    }
    private String msg(String key) { return color(getConfig().getString("settings.messages."+key, "")); }
    private String color(String s) { return ChatColor.translateAlternateColorCodes('&', s == null ? "" : s); }
    private void tell(Player p, String key, Map<String,String> replacements) {
        String s = msg(key);
        for (var e: replacements.entrySet()) s = s.replace("%"+e.getKey()+"%", e.getValue());
        p.sendMessage(msg("prefix")+s);
    }
    private ItemStack item(Material material, String name, List<String> lore, String menuId) {
        ItemStack it = new ItemStack(material); ItemMeta meta = it.getItemMeta();
        meta.setDisplayName(color(name));
        if (lore != null) meta.setLore(lore.stream().map(this::color).toList());
        if (menuId != null) meta.getPersistentDataContainer().set(menuKey, PersistentDataType.STRING, menuId);
        it.setItemMeta(meta); return it;
    }
    private void openMain(Player p) {
        Inventory inv = Bukkit.createInventory(null, 54, color(getConfig().getString("settings.gui.main-title","&0&lKAGE SYSTEM")));
        inv.setItem(20,item(Material.EMERALD,"&d&lAbility Shop",List.of("&7Purchase weapon abilities","&eClick to open"),"open_shop"));
        inv.setItem(22,item(Material.NETHERITE_SWORD,"&5&lMy Abilities",List.of("&7View your unlocked abilities"),"my_abilities"));
        inv.setItem(24,item(Material.GOLD_INGOT,"&6&lPlayer Profile",List.of("&7Balance: &f"+kp(p.getUniqueId())+" KP"),"profile"));
        inv.setItem(31,item(Material.BOOK,"&b&lHow to Play",List.of("&7Purchase abilities, then use","&7the control shown in their lore."),"help"));
        inv.setItem(49,balanceItem(p)); p.openInventory(inv);
    }
    private ItemStack balanceItem(Player p) {
        return item(Material.DIAMOND,"&d&lYOUR KAGEPOINTS",List.of("&7Current balance: &f"+kp(p.getUniqueId())+" KP","&8Earn KP by defeating players."),"balance");
    }
    private void openShop(Player p) {
        Inventory inv = Bukkit.createInventory(null,54,color(getConfig().getString("settings.gui.shop-title","&0&lABILITY SHOP")));
        String[] cats={"mace","trident","bow","crossbow","sword","axe","spear","special","token"};
        Material[] icons={Material.MACE,Material.TRIDENT,Material.BOW,Material.CROSSBOW,Material.NETHERITE_SWORD,Material.NETHERITE_AXE,Material.TRIDENT,Material.NETHER_STAR,Material.AMETHYST_SHARD};
        for(int i=0;i<cats.length;i++) inv.setItem(10+i,item(icons[i],"&d&l"+cats[i].toUpperCase(Locale.ROOT),List.of("&7Browse "+cats[i]+" abilities","&eClick to open"),"category:"+cats[i]));
        inv.setItem(45,item(Material.ARROW,"&cBack",List.of("&7Return to main menu"),"back_main"));
        inv.setItem(49,balanceItem(p)); p.openInventory(inv);
    }
    private void openCategory(Player p,String category) {
        Inventory inv=Bukkit.createInventory(null,54,color("&0&l"+category.toUpperCase(Locale.ROOT)+" ABILITIES"));
        ConfigurationSection sec=getConfig().getConfigurationSection("abilities");
        int slot=10;
        if(sec!=null) for(String id:sec.getKeys(false)) {
            if(!id.startsWith(category+".")) continue;
            if(slot>43) break;
            boolean isOwned=owned(p.getUniqueId(),id);
            int price=sec.getInt(id+".price",0);
            List<String> lore=new ArrayList<>(sec.getStringList(id+".description"));
            lore.add(" "); lore.add("&7Price: &e"+price+" KP");
            lore.add("&7Cooldown: &e"+sec.getInt(id+".cooldown",0)+" seconds");
            lore.add("&7Control: &f"+sec.getString(id+".control","UNCONFIGURED"));
            lore.add(isOwned?"&aUNLOCKED":"&cLOCKED — Click to purchase");
            Material icon=materialFor(id);
            inv.setItem(slot++,item(icon,sec.getString(id+".name",id),lore,"ability:"+id));
        }
        inv.setItem(45,item(Material.ARROW,"&cBack to Shop",List.of(),"back_shop"));
        inv.setItem(49,balanceItem(p)); p.openInventory(inv);
    }
    private Material materialFor(String id) {
        if(id.startsWith("mace")) return Material.MACE;
        if(id.startsWith("trident")) return Material.TRIDENT;
        if(id.startsWith("bow")) return Material.BOW;
        if(id.startsWith("crossbow")) return Material.CROSSBOW;
        if(id.startsWith("sword")) return Material.NETHERITE_SWORD;
        if(id.startsWith("axe")) return Material.NETHERITE_AXE;
        if(id.contains("sun_shield")) return Material.SHIELD;
        if(id.contains("orbital")) return Material.FISHING_ROD;
        if(id.contains("warden")) return Material.SCULK_CATALYST;
        if(id.contains("thors")) return Material.NETHERITE_SWORD;
        return Material.AMETHYST_SHARD;
    }
    @EventHandler public void onInventoryClick(InventoryClickEvent e) {
        if(!(e.getWhoClicked() instanceof Player p)) return;
        ItemStack clicked=e.getCurrentItem();
        if(clicked==null || !clicked.hasItemMeta()) return;
        String menu=clicked.getItemMeta().getPersistentDataContainer().get(menuKey,PersistentDataType.STRING);
        if(menu==null) return;
        e.setCancelled(true);
        if(menu.equals("open_shop")) openShop(p);
        else if(menu.equals("back_main")) openMain(p);
        else if(menu.equals("back_shop")) openShop(p);
        else if(menu.equals("profile")) p.sendMessage(msg("prefix")+color("&dBalance: &f"+kp(p.getUniqueId())+" KP"));
        else if(menu.startsWith("category:")) openCategory(p,menu.substring("category:".length()));
        else if(menu.startsWith("ability:")) purchase(p,menu.substring("ability:".length()));
    }
    private void purchase(Player p,String id) {
        if(!getConfig().getBoolean("abilities."+id+".enabled",false)) { p.sendMessage(color("&cThis ability is disabled.")); return; }
        if(owned(p.getUniqueId(),id)) { p.sendMessage(msg("prefix")+msg("already-owned")); return; }
        int price=getConfig().getInt("abilities."+id+".price",0);
        if(kp(p.getUniqueId())<price) {
            p.sendMessage(msg("prefix")+msg("not-enough").replace("%price%",String.valueOf(price)).replace("%kp%",String.valueOf(kp(p.getUniqueId())))); return;
        }
        if(price>0 && !changeKp(p.getUniqueId(),-price)) { p.sendMessage(color("&cPurchase failed safely. Try again.")); return; }
        if(!unlock(p.getUniqueId(),id)) {
            if(price>0) changeKp(p.getUniqueId(),price);
            p.sendMessage(color("&cPurchase failed; no KP was lost.")); return;
        }
        p.sendMessage(msg("prefix")+msg("purchase-success").replace("%ability%",color(getConfig().getString("abilities."+id+".name",id))).replace("%price%",String.valueOf(price)));
        String category=id.substring(0,id.indexOf('.'));
        openCategory(p,category);
    }
    @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) {
        String c=command.getName().toLowerCase(Locale.ROOT);
        if(c.equals("kagesmp")) {
            if(!(sender instanceof Player p)) { sender.sendMessage("Players only."); return true; }
            if(args.length==0) { openMain(p); return true; }
            switch(args[0].toLowerCase(Locale.ROOT)) {
                case "shop" -> openShop(p);
                case "weapons","abilities" -> openShop(p);
                case "profile" -> p.sendMessage(msg("prefix")+msg("balance").replace("%kp%",String.valueOf(kp(p.getUniqueId()))));
                case "top" -> showTop(p);
                case "reload" -> { if(!sender.hasPermission("kagesystem.admin")) { p.sendMessage(msg("prefix")+msg("no-permission")); return true; } reloadConfig(); p.sendMessage(color("&aKageSystem config reloaded.")); }
                default -> openMain(p);
            } return true;
        }