Files
src
build.gradle
Code
3 106
src/main/java/com/kodari/strengthsword/StrengthSwordPlugin.java
package com.kodari.strengthsword;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XPotion;
import org.bukkit.ChatColor;
import org.bukkit.NamespacedKey;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
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.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
public final class StrengthSwordPlugin extends JavaPlugin implements Listener {
private NamespacedKey swordKey;
@Override
public void onEnable() {
swordKey = new NamespacedKey(this, "strength_sword");
getServer().getPluginManager().registerEvents(this, this);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player player)) {
sender.sendMessage("Only players can use this command.");
return true;
}
ItemStack sword = XMaterial.matchXMaterial("DIAMOND_SWORD").map(XMaterial::parseItem).orElse(null);
if (sword == null) {
player.sendMessage(ChatColor.RED + "Could not create the Strength Sword.");
return true;
}
ItemMeta meta = sword.getItemMeta();
meta.setDisplayName(ChatColor.LIGHT_PURPLE + "Strength Sword");
meta.setLore(java.util.List.of(ChatColor.GRAY + "Right-click to gain Strength II for 10 seconds."));
meta.getPersistentDataContainer().set(swordKey, PersistentDataType.BYTE, (byte) 1);
sword.setItemMeta(meta);
player.getInventory().addItem(sword);
player.sendMessage(ChatColor.GREEN + "You received a Strength Sword.");
return true;
}
@EventHandler
public void onSwordUse(PlayerInteractEvent event) {
Action action = event.getAction();
if (action != Action.RIGHT_CLICK_AIR && action != Action.RIGHT_CLICK_BLOCK) {
return;
}
ItemStack item = event.getItem();
if (item == null || !item.hasItemMeta()) {
return;
}
Byte marked = item.getItemMeta().getPersistentDataContainer().get(swordKey, PersistentDataType.BYTE);
if (marked == null || marked != (byte) 1) {
return;
}
XPotion.matchXPotion("STRENGTH")
.map(potion -> potion.buildPotionEffect(200, 1))
.ifPresent(event.getPlayer()::addPotionEffect);
}
}