Skip to content

Commit

Permalink
Add custom item features
Browse files Browse the repository at this point in the history
(Not tested)
  • Loading branch information
esotericenderman committed Oct 28, 2024
1 parent cfc36df commit c6d807e
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package foundation.esoteric.minecraft.plugins.library.item

import org.bukkit.Bukkit
import org.bukkit.Material
import org.bukkit.entity.Player
import org.bukkit.event.Listener
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.ItemMeta
import org.bukkit.persistence.PersistentDataType

abstract class CustomItem(private val plugin: CustomItemPlugin, private val itemId: String, private val material: Material) : Listener {
init {
Bukkit.getPluginManager().registerEvents(this, plugin)

plugin.customItemManager.addCustomItem(itemId, this)
}

protected abstract fun generateCustomItem(baseCustomItem: ItemStack?, player: Player?): ItemStack

fun getCustomItem(player: Player?): ItemStack {
val item = ItemStack(material)
item.editMeta { meta: ItemMeta ->
meta.persistentDataContainer.set(
plugin.customItemManager.customItemIdKey,
PersistentDataType.STRING,
itemId
)
}
return generateCustomItem(item, player)
}

fun isItem(itemStack: ItemStack?): Boolean {
if (itemStack == null) {
return false
}

if (!itemStack.hasItemMeta()) {
return false
}

val dataContainerItemIdValue =
itemStack.itemMeta.persistentDataContainer.get(plugin.customItemManager.customItemIdKey, PersistentDataType.STRING)
?: return false

return try {
itemId === dataContainerItemIdValue
} catch (exception: IllegalArgumentException) {
false
}
}

fun give(player: Player) {
player.inventory.addItem(getCustomItem(player))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package foundation.esoteric.minecraft.plugins.library.item

import org.bukkit.NamespacedKey
import org.bukkit.entity.Player
import org.bukkit.plugin.java.JavaPlugin

class CustomItemManager(private val plugin: JavaPlugin) {

private val customItemMap: MutableMap<String, CustomItem> = HashMap()

val customItemIdKey: NamespacedKey = NamespacedKey(plugin, "custom_item_id")

fun getPlugin(): JavaPlugin {
return plugin
}

fun addCustomItem(itemId: String, customItem: CustomItem) {
customItemMap[itemId] = customItem
}

fun getAbstractCustomItem(itemId: String): CustomItem? {
return customItemMap[itemId]
}

fun giveCustomItem(itemId: String, player: Player?) {
customItemMap[itemId]!!.give(player!!)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package foundation.esoteric.minecraft.plugins.library.item

import org.bukkit.plugin.Plugin

interface CustomItemPlugin : Plugin {
val customItemManager: CustomItemManager
}

0 comments on commit c6d807e

Please sign in to comment.