Skip to content

GroovyValueReader - 数值读取器基类

GroovyValueReader 是数值读取组件的抽象基类,继承自 Kotlin 核心的 ValueReader 类。用于从物品 Lore、名称等文本中提取属性值(如「物理攻击 +100」)。

类定义

groovy
package scripts.libs

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

@CompileStatic
abstract class GroovyValueReader extends ValueReader {

    String name        // 读取器名称
    String configKey   // 在 read.yml 中的配置键名
    int priority       // 优先级,决定执行顺序
    List<ConfigSetting> settingConfig = new ArrayList<>()

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

需要重写的方法

groovy
/**
 * 从一行文本中读取属性值
 * @return ReadValueResult(解析成功)或 null(不匹配)
 */
@Override
ReadValueResult read(ReadableLine readableLine, AttributeData data, AttributeSource attributeSource)

辅助方法

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

// 使用自定义正则提取值
List<String> extractValues(ReadableLine readableLine, List<String> readFormat, String valueRegex)

使用示例

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.manager.CacheManager
import cn.org.bukkit.craneattribute.core.read.data.ReadValueResult
import groovy.transform.CompileStatic
import scripts.libs.GroovyValueReader

@CompileStatic
class CustomValueReader extends GroovyValueReader {

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

    CustomValueReader() {
        super("custom_value", 10)
    }

    @Override
    ReadValueResult read(ReadableLine readableLine, AttributeData data, AttributeSource attributeSource) {
        List<String> list = CacheManager.INSTANCE.getStringList(readableLine) {
            extractValues(readableLine, readFormat)
        }

        if (list == null || list.isEmpty()) return null

        double[] numbers = StringUtilsKt.toDoubleArray(list.first())

        // 参数:属性ID, 最小值, 最大值, 百分比最小值, 百分比最大值, 是否百分比
        return new ReadValueResult(
            "custom_attr",    // 属性 ID
            numbers[0],       // 最小值
            numbers[1],       // 最大值
            0.0D, 0.0D,       // 无百分比
            false
        )
    }
}

返回值说明

返回值含义
ReadValueResult解析成功,包含属性 ID 和数值
null当前行不匹配此读取组件

注意事项

  1. 正则表达式要确保能正确匹配目标格式,注意转义
  2. 解析数值时注意捕获 NumberFormatException
  3. 合理设置 priority 避免与其他读取组件冲突
  4. 使用 CacheManager 缓存避免重复解析