Skip to content

AttributeHandler

属性处理器,它负责处理全部的运行逻辑

编写处理器类

需要实现 cn.org.bukkit.craneattribute.api.attribute.trigger.AttributeHandler 接口
以及可以同时实现 cn.org.bukkit.craneattribute.api.attribute.handler 中的其他接口

Kotlin
class CustomHandler(
    val killerData: AttributeData,
    val entityData: AttributeData,
) : AttributeHandler, AttributeTracker, MetadataTracker, Cancellable {

    // 使用最开始注册的 CUSTOME_TYPE 属性类型
    override val type: AttributeType = ....CUSTOME_TYPE

    // 实现 Cancellable 接口
    override var cancelled: Boolean = false

    // 可以取出实体
    val killer = killerData.entity
    val entity = entityData.entity

    // 实现 AttributeTracker 接口
    override val dataMap: MutableMap<UUID, AttributeData> = mutableMapOf(
        attacker.uniqueId to attackerData,
        entity.uniqueId to entityData,
    )

    // 实现 AttributeTracker 接口
    override val tempAttribute: MutableMap<UUID, MutableMap<String, Array<Double>>> = mutableMapOf(
        killer.uniqueId to mutableMapOf(),
        entity.uniqueId to mutableMapOf()
    )

    // 实现 AttributeTracker 接口
    override val triggerAttribute: MutableSet<String> = mutableSetOf()

    // 实现 MetadataTracker 接口
    override val metadata: MutableMap<UUID, MutableMap<String, Any>> = mutableMapOf(
        killer.uniqueId to mutableMapOf(),
        entity.uniqueId to mutableMapOf()
    )

    // 主要处理逻辑
    override fun handle() {
        // 使用一对实体过滤出本次运行的属性
        val attributeComponents = (killer cp entity).filterAttributes(type)
        // 逐个运行
        for (attributeComponent in attributeComponents) {
            // 将运行 属性脚本 中的 custom(attr, handler) 函数
            if (attributeComponent.run("custom", this)) {
                // 因为实现了 Cancellable 接口
                // 处理器可能在处理过程中被取消
                if (!cancelled) {
                    // 因为会返回 true 或 false,所以设置属性是否触发
                    // trigger() 是 AttributeTracker 中的默认函数
                    trigger(attributeComponent)
                } else {
                    // 还需要处理 ignoreCancelled 的属性
                    if (attributeComponent.ignoreCancelled) {
                        trigger(attributeComponent)
                    }
                }
            }
        }
    }
    
}

预设接口

AttributeTracker:属性控制器,若想获取实体属性、临时属性,可实现此接口
DamageTracker:伤害控制器,若想管理两个实体直接的伤害,可实现此接口
ProjectileTracker:抛射物控制器,若存在 Bukkit 原版抛射物,可实现此接口
BlockTracker:方块控制器,若处理器与方块有关,可实现此接口
MessageTracker: 信息控制器,若想管理属性信息,可实现此接口
MetadataTracker:元数据控制器,若想存储数据,可实现此接口
Cancellable:代表可取消,若处理器可取消,可实现此接口

请参阅 javadoc