package games.dmg.spigotinventoryhelper; import java.util.Objects; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; public final class ToolReplacementService { private static final int HOTBAR_SIZE = 9; private static final int PLAYER_STORAGE_SIZE = 36; public boolean replace( PlayerInventory inventory, Material brokenMaterial, int selectedSlot ) { Objects.requireNonNull(inventory, "inventory"); Objects.requireNonNull(brokenMaterial, "brokenMaterial"); if (selectedSlot < 0 || selectedSlot >= HOTBAR_SIZE || !isEmpty(inventory.getItem(selectedSlot))) { return false; } ItemStack[] storage = inventory.getStorageContents(); int source = find(storage, brokenMaterial, HOTBAR_SIZE, PLAYER_STORAGE_SIZE, selectedSlot); if (source < 0) { source = find(storage, brokenMaterial, 0, HOTBAR_SIZE, selectedSlot); } if (source < 0) { return false; } ItemStack replacement = storage[source]; inventory.setItem(selectedSlot, replacement); inventory.setItem(source, null); return true; } private static int find( ItemStack[] storage, Material material, int from, int to, int excludedSlot ) { int limit = Math.min(to, storage.length); for (int slot = from; slot < limit; slot++) { ItemStack candidate = storage[slot]; if (slot != excludedSlot && candidate != null && candidate.getAmount() > 0 && candidate.getType() == material) { return slot; } } return -1; } private static boolean isEmpty(ItemStack item) { return item == null || item.getType() == Material.AIR || item.getAmount() == 0; } }