Skip to content

GroovyConditionReader - 条件读取器基类

GroovyConditionReader 是条件读取组件的抽象基类,继承自 Kotlin 核心的 ConditionReader 类。用于从物品 Lore 或 NBT 中解析条件(如「血量需求: 50~100」),并判断该条件是否满足。

类定义

groovy
package scripts.libs

import cn.org.bukkit.craneattribute.api.utils.ConfigSetting
import cn.org.bukkit.craneattribute.core.read.ConditionReader
import groovy.transform.CompileStatic

@CompileStatic
abstract class GroovyConditionReader extends ConditionReader {

    String name        // 读取器名称
    String configKey   // 在 read.yml 中的配置键名
    int priority       // 优先级,决定执行顺序
    String key         // 条件键名,如「血量需求」「等级需求」
    List<ConfigSetting> settingConfig = new ArrayList<>()

    GroovyConditionReader(String name, int priority, String key) {
        this.name = name
        this.configKey = name
        this.priority = priority
        this.key = key
    }
    // ...
}

需要重写的方法

groovy
/**
 * 判断条件是否满足
 * @return true 满足条件;false 不满足
 */
@Override
protected boolean read(ReadableLine readableLine, AttributeData data, AttributeSource attributeSource)

辅助方法

groovy
// 使用默认正则提取值
List<String> extractValues(ReadableLine readableLine, List<String> readFormat)

// 使用自定义正则提取值(@value 会被替换为数值匹配模式)
List<String> extractValues(ReadableLine readableLine, List<String> readFormat, String valueRegex)

readFormat 中的 {key} 会被替换为构造时传入的 key 值,@value 会被替换为数值正则。

使用示例

groovy
package scripts.reads

import cn.org.bukkit.craneattribute.api.attribute.data.AttributeData
import cn.org.bukkit.craneattribute.api.attribute.source.AttributeSource
import cn.org.bukkit.craneattribute.api.read.ReadableLine
import cn.org.bukkit.craneattribute.api.utils.StringUtilsKt
import cn.org.bukkit.craneattribute.core.attribute.data.PlayerAttributeData
import cn.org.bukkit.craneattribute.core.manager.CacheManager
import groovy.transform.CompileStatic
import scripts.libs.GroovyConditionReader

@CompileStatic
class HealthConditionReader extends GroovyConditionReader {

    List<String> readFormat = Arrays.asList("{key}.*?@value")

    HealthConditionReader() {
        super("health", 10, "血量需求")
    }

    @Override
    protected boolean read(ReadableLine readableLine, AttributeData data, AttributeSource attributeSource) {
        if (data instanceof PlayerAttributeData) {
            List<String> list = CacheManager.INSTANCE.getStringList(readableLine) {
                extractValues(readableLine, readFormat)
            }
            if (list == null) return true

            double[] numbers = StringUtilsKt.toDoubleArray(list.first())
            double health = data.player.getHealth()

            if (numbers[0] == numbers[1] && health >= numbers[0]) return true
            if (numbers[0] != numbers[1] && health in numbers[0]..numbers[1]) return true

            return false
        }
        return true
    }
}

返回值说明

返回值含义
true条件满足,属性值生效
false条件不满足,该行属性值被跳过

注意事项

  1. 非玩家实体通常返回 true 以避免阻塞
  2. 解析失败时应返回 true(容错)
  3. 使用 CacheManager 做缓存可避免重复解析同一行
  4. 条件不满足时可通过 data.player.sendMessage(...) 发送提示