Files
src
manifest.kod
pasted-code-1795264061285.txt
pom.xml
README.md
Code
7 1,076
src/main/java/com/heartbound/Heartbound.java
package com.heartbound;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XPotion;
import com.cryptomorin.xseries.XSound;
import com.cryptomorin.xseries.particles.XParticle;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockExplodeEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
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.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
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;
import java.util.function.Consumer;
public final class Heartbound extends JavaPlugin implements Listener, CommandExecutor {
private enum Ability {
THUNDER("Speed I", "SPEED", "&b", "ENTITY_LIGHTNING_BOLT_THUNDER"),
KNIGHT("Resistance I", "RESISTANCE", "&7", "ITEM_SHIELD_BLOCK"),
WARRIOR("Strength I", "STRENGTH", "&c", "ENTITY_PLAYER_ATTACK_CRIT"),
SOUL("Regeneration I", "REGENERATION", "&a", "BLOCK_SOUL_SAND_BREAK"),
PHANTOM("Invisibility", "INVISIBILITY", "&5", "ENTITY_PHANTOM_AMBIENT"),
PHOENIX("Fire Resistance", "FIRE_RESISTANCE", "&6", "ITEM_FIRECHARGE_USE"),
OCEAN("Water Breathing", "WATER_BREATHING", "&9", "ENTITY_DOLPHIN_AMBIENT");
final String effect, potion, color, sound;
Ability(String effect, String potion, String color, String sound) {
this.effect = effect; this.potion = potion; this.color = color; this.sound = sound;
}
String display() { return color + name() + " HEART"; }
}
private static final class State {
final UUID id;
String name;
long points;
boolean eliminated, notice;
final List<Ability> abilities = new ArrayList<>();
final Map<Ability, Long> expiry = new HashMap<>();
State(UUID id, String name) { this.id = id; this.name = name; }
}
private static final class Menu implements InventoryHolder {
final Map<Integer, UUID> targets = new HashMap<>();
Inventory inventory;
@Override public Inventory getInventory() { return inventory; }
}
private record Pending(UUID target, long expires) {}
private record Settings(long cooldown, long soul, long phantom, boolean animation, int interval,
String particle, String startSound, String revealSound, String world,
int x, int y, int z, String beaconName, String eliminated, String revived,
String reward, String error) {}
private interface Work<T> { T run() throws Exception; }
private ExecutorService executor;
private Connection db;
private volatile Settings settings;
private final Map<UUID, State> online = new HashMap<>();
private final Map<UUID, Pending> pending = new HashMap<>();
private volatile boolean stopping;
@Override public void onEnable() {
saveDefaultConfig();
loadSettings();
executor = Executors.newSingleThreadExecutor(r -> new Thread(r, "Heartbound-SQLite"));
String filename = getConfig().getString("storage.file", "heartbound.db");
if (filename == null || !filename.matches("[a-zA-Z0-9_.-]+") || filename.equals(".") || filename.equals("..")) {
getLogger().severe("Invalid storage.file; disabling Heartbound.");
getServer().getPluginManager().disablePlugin(this);
return;
}
submit(() -> { openDatabase(filename); return null; }, ignored -> {}, null);
getServer().getPluginManager().registerEvents(this, this);
getCommand("heart").setExecutor(this);
Bukkit.getScheduler().runTaskTimer(this, () -> {
for (Player player : Bukkit.getOnlinePlayers()) {
State state = online.get(player.getUniqueId());
if (state != null && !state.eliminated) applyEffects(player, state);
}
}, 20L, 100L);
for (Player p : Bukkit.getOnlinePlayers()) loadPlayer(p);
}
@Override public void onDisable() {
stopping = true;
if (executor != null) {
executor.execute(() -> { try { if (db != null) db.close(); } catch (SQLException e) { getLogger().severe(e.toString()); } });
executor.shutdown();
try { if (!executor.awaitTermination(30, TimeUnit.SECONDS)) getLogger().severe("Database shutdown timed out; queued operations may not be saved."); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
}
private void loadSettings() {
FileConfiguration c = getConfig();
settings = new Settings(Math.max(0, c.getLong("kill-cooldown-seconds", 300)) * 1000L,
Math.max(1, c.getLong("abilities.soul-duration-seconds", 30)) * 1000L,
Math.max(1, c.getLong("abilities.phantom-duration-seconds", 30)) * 1000L,
c.getBoolean("animation.enabled", true), Math.max(1, c.getInt("animation.interval-ticks", 8)),
c.getString("animation.particle", "TOTEM_OF_UNDYING"), c.getString("animation.start-sound", "BLOCK_BEACON_ACTIVATE"),
c.getString("animation.reveal-sound", "UI_TOAST_CHALLENGE_COMPLETE"), c.getString("beacon.world", ""),
c.getInt("beacon.x"), c.getInt("beacon.y"), c.getInt("beacon.z"), c.getString("beacon.name", "&6Revival Beacon"),
c.getString("messages.eliminated", "&cYou have been eliminated."), c.getString("messages.revived", "&aYou have been revived."),
c.getString("messages.reward", "&6You received a Golden Heart!"), c.getString("messages.error", "&cDatabase error."));
}
private String color(String text) { return ChatColor.translateAlternateColorCodes('&', text == null ? "" : text); }
private void tell(CommandSender sender, String text) { sender.sendMessage(color(text)); }
private <T> void submit(Work<T> work, Consumer<T> success, UUID recipient) {
if (stopping) return;
executor.execute(() -> {
try {
T result = work.run();
if (!stopping) Bukkit.getScheduler().runTask(this, () -> success.accept(result));
} catch (Exception e) {
getLogger().severe("Heartbound operation failed: " + e);
if (!stopping && recipient != null) Bukkit.getScheduler().runTask(this, () -> {
Player p = Bukkit.getPlayer(recipient); if (p != null) tell(p, settings.error());
});
}
});
}
private void openDatabase(String filename) throws Exception {
Class.forName("org.sqlite.JDBC");
db = DriverManager.getConnection("jdbc:sqlite:" + new File(getDataFolder(), filename).getAbsolutePath());
try (Statement s = db.createStatement()) {
s.execute("PRAGMA journal_mode=WAL"); s.execute("PRAGMA synchronous=FULL"); s.execute("PRAGMA busy_timeout=5000");
s.execute("CREATE TABLE IF NOT EXISTS players (uuid TEXT PRIMARY KEY, name TEXT NOT NULL, points INTEGER NOT NULL, eliminated INTEGER NOT NULL, notice INTEGER NOT NULL DEFAULT 0)");
s.execute("CREATE TABLE IF NOT EXISTS abilities (uuid TEXT NOT NULL, ability TEXT NOT NULL, expires INTEGER NOT NULL, position INTEGER NOT NULL, PRIMARY KEY(uuid,ability))");
s.execute("CREATE TABLE IF NOT EXISTS kills (killer TEXT NOT NULL, victim TEXT NOT NULL, last INTEGER NOT NULL, PRIMARY KEY(killer,victim))");
s.execute("CREATE TABLE IF NOT EXISTS revivals (id INTEGER PRIMARY KEY AUTOINCREMENT, target TEXT NOT NULL, reviver TEXT, time INTEGER NOT NULL, admin INTEGER NOT NULL)");
}
}
private State get(UUID id) throws SQLException {
if (db == null) throw new SQLException("Storage not initialized");
try (PreparedStatement q = db.prepareStatement("SELECT name,points,eliminated,notice FROM players WHERE uuid=?")) {
q.setString(1, id.toString());
try (ResultSet r = q.executeQuery()) {
if (!r.next()) return null;
State s = new State(id, r.getString(1)); s.points = r.getLong(2); s.eliminated = r.getInt(3) != 0; s.notice = r.getInt(4) != 0;
try (PreparedStatement a = db.prepareStatement("SELECT ability,expires FROM abilities WHERE uuid=? ORDER BY position")) {
a.setString(1, id.toString());
try (ResultSet ar = a.executeQuery()) { while (ar.next()) { Ability ability = Ability.valueOf(ar.getString(1)); s.abilities.add(ability); s.expiry.put(ability, ar.getLong(2)); } }
}
return s;
}
}
}
private void save(State s) throws SQLException {
try (PreparedStatement p = db.prepareStatement("INSERT INTO players(uuid,name,points,eliminated,notice) VALUES(?,?,?,?,?) ON CONFLICT(uuid) DO UPDATE SET name=excluded.name,points=excluded.points,eliminated=excluded.eliminated,notice=excluded.notice")) {
p.setString(1, s.id.toString()); p.setString(2, s.name); p.setLong(3, s.points); p.setInt(4, s.eliminated ? 1 : 0); p.setInt(5, s.notice ? 1 : 0); p.executeUpdate();
}
try (PreparedStatement d = db.prepareStatement("DELETE FROM abilities WHERE uuid=?")) { d.setString(1, s.id.toString()); d.executeUpdate(); }
try (PreparedStatement p = db.prepareStatement("INSERT INTO abilities(uuid,ability,expires,position) VALUES(?,?,?,?)")) {
for (int i = 0; i < s.abilities.size(); i++) { Ability a = s.abilities.get(i); p.setString(1, s.id.toString()); p.setString(2, a.name()); p.setLong(3, s.expiry.getOrDefault(a, 0L)); p.setInt(4, i); p.addBatch(); } p.executeBatch();
}
}
private <T> T transaction(Work<T> work) throws Exception {
if (db == null) throw new SQLException("Storage not initialized");