Files
src
pom.xml
README.md
Code
7 750
src/main/java/com/kodari/pinkbubble/PinkBubblePlugin.java
package com.kodari.pinkbubble;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XSound;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class PinkBubblePlugin extends JavaPlugin {
private static final Pattern HEX_COLOR = Pattern.compile("(?i)&?#([0-9a-f]{6})");
private final Map<UUID, Long> cooldowns = new HashMap<>();
private final Map<UUID, Long> actionBarWarnings = new HashMap<>();
private NamespacedKey axeKey;
private BubbleManager bubbles;
private Material axeMaterial;
private int cooldownSeconds;
private int durationSeconds;
private int radius;
@Override
public void onEnable() {
saveDefaultConfig();
axeKey = new NamespacedKey(this, "bubble_axe");
axeMaterial = XMaterial.matchXMaterial("NETHERITE_AXE").map(XMaterial::parseMaterial).orElseThrow();
Material bubbleMaterial = resolveBubbleMaterial(getConfig().getString("bubble-material", "PINK_STAINED_GLASS"));
if (bubbleMaterial == null) {
getLogger().severe("bubble-material must be a solid, non-falling block.");
getServer().getPluginManager().disablePlugin(this);
return;
}
cooldownSeconds = Math.max(1, getConfig().getInt("cooldown-seconds", 45));
durationSeconds = Math.max(1, getConfig().getInt("bubble-duration-seconds", 15));
radius = Math.max(2, Math.min(16, getConfig().getInt("bubble-radius", 7)));
try {
bubbles = new BubbleManager(this, bubbleMaterial);
} catch (IOException | RuntimeException ex) {
getLogger().severe("Could not recover bubble journal; refusing to start to protect world blocks: " + ex.getMessage());
getServer().getPluginManager().disablePlugin(this);
return;
}
getServer().getPluginManager().registerEvents(new BubbleListener(this, bubbles), this);
Bukkit.getScheduler().runTaskTimer(this, () -> {
long now = System.currentTimeMillis();
for (Player player : Bukkit.getOnlinePlayers()) {
if (!isAxe(player.getInventory().getItemInMainHand())) continue;
if (actionBarWarnings.getOrDefault(player.getUniqueId(), 0L) > now) continue;
if (player.getWorld().getName().equals("spawn")) continue;
showStatus(player, now);
}
cooldowns.entrySet().removeIf(entry -> entry.getValue() <= now);
actionBarWarnings.entrySet().removeIf(entry -> entry.getValue() <= now);
}, 0L, 20L);
}
@Override
public void onDisable() {
if (bubbles != null) bubbles.shutdown();
}
private Material resolveBubbleMaterial(String name) {
Material material = XMaterial.matchXMaterial(name).map(XMaterial::parseMaterial)
.filter(Material::isBlock).orElse(null);
return material != null && material.isSolid() && !material.hasGravity() ? material : null;
}
boolean isAxe(ItemStack item) {
if (item == null || item.getType() != axeMaterial || !item.hasItemMeta()) return false;
Byte tag = item.getItemMeta().getPersistentDataContainer().get(axeKey, PersistentDataType.BYTE);
return tag != null && tag == (byte) 1;
}
void activate(Player player) {
if (player.getWorld().getName().equals("spawn")) {
String text = getConfig().getString("messages.disabled-world-prefix", "")
+ getConfig().getString("messages.disabled-world-action-bar", " &8» &cThis ability is disabled here.");
player.sendActionBar(LegacyComponentSerializer.legacySection().deserialize(color(text)));
actionBarWarnings.put(player.getUniqueId(), System.currentTimeMillis() + 2000L);
failed(player);
return;
}
long now = System.currentTimeMillis();
long remaining = Math.max(0, (cooldowns.getOrDefault(player.getUniqueId(), 0L) - now + 999) / 1000);
if (remaining > 0) {
actionBarWarnings.remove(player.getUniqueId());
showStatus(player, now);
failed(player);
return;
}
BubbleManager.Result result = bubbles.activate(player, radius, durationSeconds);
switch (result) {
case CREATED -> {
cooldowns.put(player.getUniqueId(), now + cooldownSeconds * 1000L);
message(player, "activated", "&dYour protective bubble is active!");
}
case ALREADY_ACTIVE -> {
message(player, "already-active", "&dYou already have an active bubble.");
failed(player);
}
case OBSTRUCTED -> {
message(player, "obstructed", "&dThere is not enough space here.");
failed(player);
}
case STORAGE_ERROR -> {
message(player, "storage-error", "&cCould not safely save bubble blocks. Try again later.");
failed(player);
}
}
}
private void failed(Player player) {
XSound.matchXSound("ENTITY_VILLAGER_NO").ifPresent(sound -> sound.play(player));
}
void expired(UUID owner) {
Player player = Bukkit.getPlayer(owner);
if (player != null) message(player, "expired", "&dYour protective bubble has disappeared.");
}
void message(CommandSender sender, String key, String fallback, String... replacements) {
String text = getConfig().getString("messages." + key, fallback);
for (int i = 0; i < replacements.length; i += 2) text = text.replace(replacements[i], replacements[i + 1]);
text = withPrefix(text, true);
if (sender instanceof Player player) {
player.sendActionBar(LegacyComponentSerializer.legacySection().deserialize(color(text)));
actionBarWarnings.put(player.getUniqueId(), System.currentTimeMillis() + 2000L);
} else {
sender.sendMessage(color(text));
}
}
private void showStatus(Player player, long now) {
long remaining = Math.max(0, (cooldowns.getOrDefault(player.getUniqueId(), 0L) - now + 999) / 1000);
String text = remaining == 0 ? getConfig().getString("ready-action-bar", "&dʀᴇᴀᴅʏ")
: getConfig().getString("cooldown-action-bar", "&d{seconds}ꜱ")
.replace("{seconds}", String.valueOf(remaining));
player.sendActionBar(LegacyComponentSerializer.legacySection().deserialize(color(withPrefix(text, false))));
}
private String withPrefix(String text, boolean prepend) {
String prefix = getConfig().getString("messages.prefix", "");
if (text.contains("{prefix}")) return text.replace("{prefix}", prefix);
return prepend ? prefix + text : text;
}
private String color(String text) {
Matcher matcher = HEX_COLOR.matcher(text);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
StringBuilder code = new StringBuilder("&x");
for (char digit : matcher.group(1).toCharArray()) code.append('&').append(digit);
matcher.appendReplacement(result, code.toString());
}
matcher.appendTail(result);
return ChatColor.translateAlternateColorCodes('&', result.toString());
}
private ItemStack makeAxe() {
ItemStack axe = new ItemStack(axeMaterial);
ItemMeta meta = axe.getItemMeta();
meta.setDisplayName(color(withPrefix(getConfig().getString("axe-name", "&d&lPink Bubble Axe"), false)));
List<String> lore = getConfig().getStringList("axe-lore");
meta.setLore(lore.stream().map(line -> color(withPrefix(line, false))).toList());
meta.getPersistentDataContainer().set(axeKey, PersistentDataType.BYTE, (byte) 1);
axe.setItemMeta(meta);
return axe;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("bubbleaxe")) {
if (!sender.isOp()) {
message(sender, "no-permission", "&cOnly server operators can use this command.");
return true;
}
if (args.length != 1 || !args[0].equalsIgnoreCase("reload")) {
message(sender, "reload-usage", "&dUsage: /bubbleaxe reload");
return true;
}
Material newMaterial = resolveBubbleMaterial(YamlConfiguration.loadConfiguration(