📖 古龙精灵 API 参考手册

面向游戏脚本开发者的完整 API 参考文档。涵盖触控模拟、图像识别、OCR 文字识别、YOLO 目标检测、设备控制、网络请求等全部功能。

🚀 概览与快速入门

什么是古龙精灵?

古龙精灵是一个面向游戏脚本开发者的全栈自动化平台。开发者使用 Lua 编写脚本,通过 PC 开发工具调试,最终打包为 APK 部署到 Android 设备上运行。平台提供丰富的 API 用于触控模拟、图像识别、OCR 文字识别、YOLO 目标检测等。

脚本基本结构

每个脚本是一个 Lua 文件,必须包含 main() 函数作为入口点。脚本引擎在加载文件后会自动调用 main()

Lua - 脚本基本结构
-- ============================================================
-- 古龙精灵脚本模板
-- ============================================================

-- 加载子模块
dofile("settings_fields.lua")   -- 设置字段定义
dofile("server_api.lua")        -- 服务器通信模块

-- 全局配置
GAMENAME = "我的游戏脚本"
ACCOUNT_ID = "user_001"

-- 主函数(脚本引擎自动调用)
function main()
    log("脚本开始运行")
    
    -- 获取用户设置
    local auto_fight = get_setting("auto_fight", true)
    
    -- 主循环
    while true do
        if auto_fight then
            tap(500, 800)       -- 点击攻击按钮
            sleep(2000)             -- 等待2秒
        end
        sleep(1000)
    end
end

main()

开发流程

  1. 在 PC 开发工具中编写 Lua 脚本
  2. 使用工具 → 抓取窗口获取坐标、颜色、图片等数据
  3. 在开发工具中连接 Android 设备进行调试
  4. 通过开发者面板上传脚本包
  5. 打包 APK 分发给用户

🎨 UI 控件参考(用户设置面板)

脚本可以在 SCRIPT_SETTINGS_FIELDS 中定义设置字段,这些字段会显示在用户控制面板的"脚本设置"选项卡中。所有控件定义使用 Lua table 格式。

控件结构层级

设置字段支持三层嵌套结构:fold(折叠面板)tab_container(选项卡容器)控件字段

Lua - 完整结构示例
SCRIPT_SETTINGS_FIELDS = {
    {
        key = "section_1",
        label = "战斗设置",
        type = "fold",              -- 折叠面板
        default = true,
        icon = "⚔️",
        fields = {
            {
                type = "tab_container",  -- 选项卡容器
                tabs = {
                    {
                        label = "基础",
                        icon = "❤️",
                        fields = {
                            {key = "auto_fight", label = "自动打怪", type = "bool", default = true, icon = "⚔️"},
                            -- ... 更多控件
                        }
                    },
                }
            }
        },
    },
}

1. ☑️ 布尔开关 (bool)

用于开启/关闭某个功能。必填属性:key, label, type, default。可选属性:icon, description。

属性类型必填说明
keystring唯一标识,脚本中用此 key 读取值
labelstring显示名称
type"bool"控件类型
defaultboolean默认值:true 或 false
iconstring图标(HTML实体编码)
descriptionstring提示文字
示例:基础开关 / 带副标题开关 / 默认关闭开关 / 通知开关 / 调试模式开关
-- 基础开关(默认开启)
{key = "auto_fight", label = "自动打怪", type = "bool", default = true, icon = "⚔️", description = "是否开启自动打怪功能"},

-- 带副标题开关
{key = "auto_pickup", label = "自动拾取", type = "bool", default = true, icon = "📦", description = "是否自动拾取掉落物品"},

-- 默认关闭开关
{key = "auto_sell", label = "自动出售装备", type = "bool", default = false, icon = "💰", description = "是否自动出售背包中的装备"},

-- 通知开关
{key = "enable_notify", label = "启用通知", type = "bool", default = true, icon = "🔔", description = "是否启用任务通知提醒"},

-- 调试模式开关
{key = "debug_mode", label = "调试模式", type = "bool", default = false, icon = "🐛", description = "开启后显示调试信息"},

2. 🔢 数字输入 (number)

用于输入数值。必填属性:key, label, type, default, min, max。可选:step, unit, icon, description。

属性类型必填说明
keystring唯一标识
labelstring显示名称
type"number"控件类型
defaultnumber默认值
minnumber最小值
maxnumber最大值
stepnumber步进值,默认1
unitstring单位(秒、%、分钟等)
iconstring图标
descriptionstring提示文字
示例:基础数字 / 百分比数字 / 时长数字 / 次数数字 / 浮点数
-- 基础数字(带单位)
{key = "fight_interval", label = "打怪间隔", type = "number", default = 5, min = 1, max = 60, step = 1, unit = "秒", icon = "⏱️"},

-- 百分比数字
{key = "hp_threshold", label = "回血阈值", type = "number", default = 30, min = 10, max = 90, step = 5, unit = "%", icon = "❤️"},

-- 时长数字(分钟)
{key = "max_duration", label = "最大时长", type = "number", default = 120, min = 30, max = 1440, step = 10, unit = "分钟"},

-- 次数数字
{key = "max_attempts", label = "最大尝试次数", type = "number", default = 3, min = 1, max = 99, step = 1, unit = "次"},

-- 浮点数(带小数)
{key = "move_speed", label = "移动速度", type = "number", default = 1.5, min = 0.5, max = 5.0, step = 0.1, unit = "倍"},

3. 📝 文本输入 (text)

用于输入文本。必填属性:key, label, type, default。可选:placeholder, password, multiline, icon, description。

属性类型必填说明
keystring唯一标识
labelstring显示名称
type"text"控件类型
defaultstring默认值
placeholderstring占位提示文字
passwordboolean是否为密码输入框
multilineboolean是否多行文本
iconstring图标
descriptionstring提示文字
示例:基础文本 / 密码输入 / 多行文本 / 过滤关键词
-- 基础文本(带占位符)
{key = "target_monster", label = "目标怪物", type = "text", default = "银月贤者", icon = "🎯", placeholder = "输入怪物名称", description = "要自动攻击的怪物名称"},

-- 密码输入
{key = "account_password", label = "账号密码", type = "text", default = "", icon = "🔑", placeholder = "输入密码", password = true, description = "登录密码"},

-- 多行文本
{key = "custom_notice", label = "自定义公告", type = "text", default = "", icon = "📋", multiline = true, placeholder = "输入公告内容..."},

-- 过滤关键词
{key = "filter_keywords", label = "过滤关键词", type = "text", default = "", icon = "🔍", placeholder = "关键词用逗号分隔"},

4. 📋 下拉选择 (select)

用于从预设选项中选择。必填属性:key, label, type, default, options。

属性类型必填说明
keystring唯一标识
labelstring显示名称
type"select"控件类型
defaultstring默认值(对应 option 的 value)
optionstable选项列表:{{value="x", label="显示名"}, ...}
iconstring图标
descriptionstring提示文字
示例:基础下拉 / 地图选择 / 职业选择 / 分辨率选择
-- 基础下拉选择
{key = "difficulty", label = "难度选择", type = "select", default = "normal", icon = "🎮",
 options = {{value = "easy", label = "简单"},{value = "normal", label = "普通"},{value = "hard", label = "困难"},{value = "hell", label = "地狱"}},
 description = "选择打怪难度等级"},

-- 地图选择
{key = "target_map", label = "目标地图", type = "select", default = "map1", icon = "🗺️",
 options = {{value = "map1", label = "新手村"},{value = "map2", label = "幽暗森林"},{value = "map3", label = "冰封雪域"},{value = "map4", label = "火焰山"}}},

-- 职业选择
{key = "class_type", label = "职业选择", type = "select", default = "warrior",
 options = {{value = "warrior", label = "战士"},{value = "mage", label = "法师"},{value = "archer", label = "弓箭手"},{value = "assassin", label = "刺客"}}},

-- 分辨率选择
{key = "resolution", label = "分辨率", type = "select", default = "720p",
 options = {{value = "720p", label = "720x1280"},{value = "1080p", label = "1080x1920"},{value = "2k", label = "1440x2560"}}},
⚠️ 重要提示:中文 key 必须使用方括号语法
如果 key包含中文字符(例如 "difficulty_选择采集物品"),在入口文件中必须使用方括号语法 settings["key"] 来获取值,不能使用点号语法 settings.key
示例:包含中文的 key 用方括号读取
-- ===== 📋 select(下拉选择)=====
-- 读取用户选择的值,用于条件判断
local difficulty_选择采集物品 = settings["difficulty_选择采集物品"] or "wp_流寇"

-- 控件定义
{key = "difficulty_选择采集物品", label = "采集物品", type = "select", default = "normal", icon = "🎮",
 options = {{value = "wp_流寇", label = "流寇"},{value = "wp_煤矿", label = "煤矿"},{value = "wp_铁矿", label = "铁矿"},{value = "wp_伐木场", label = "伐木场"}},
 description = "选择采集物品"},

-- ✅ 正确:使用方括号语法
local val = settings["difficulty_选择采集物品"]
-- ❌ 错误:不能使用点号语法(key含中文时)
-- local val = settings.difficulty_选择采集物品  -- 这会报错!

5. 📦 折叠面板 (fold)

用于将一组控件折叠/展开。必填属性:key, label, type, default, fields。fields 内部可以嵌套 tab_container,tab_container 的 tabs 里才是真正的控件。

属性类型必填说明
keystring唯一标识
labelstring显示名称
type"fold"控件类型
defaultboolean是否默认展开
iconstring图标
descriptionstring提示文字
fieldstable内部控件列表(通常含 tab_container)
fold 完整示例
{
    key = "fight_settings",
    label = "战斗设置",
    type = "fold",
    default = true,
    icon = "⚔️",
    description = "战斗相关设置(可折叠)",
    fields = {
        {
            type = "tab_container",
            tabs = {
                {
                    label = "基础",
                    icon = "⚔️",
                    fields = {
                        {key = "auto_fight", label = "自动打怪", type = "bool", default = true, icon = "⚔️"},
                        {key = "fight_interval", label = "打怪间隔", type = "number", default = 5, min = 1, max = 60, step = 1, unit = "秒"},
                    }
                },
                {
                    label = "高级",
                    icon = "⚙️",
                    fields = {
                        {key = "debug_mode", label = "调试模式", type = "bool", default = false, icon = "🐛"},
                    }
                },
            }
        }
    },
},

6. 📑 选项卡容器 (tab_container)

在折叠面板内部创建多个选项卡,每个选项卡包含一组控件。通常在 fold 的 fields 内部使用。

属性类型必填说明
type"tab_container"固定值
tabstable选项卡列表,每个 tab 有 label, icon, fields

7. 🎨 颜色选择 (color)

示例
-- 颜色选择器
{key = "theme_color", label = "主题颜色", type = "color", default = "#FF5722", icon = "🎨", description = "选择界面主题颜色"},

-- 文字颜色
{key = "text_color", label = "文字颜色", type = "color", default = "#FFFFFF", icon = "✏️"},

📋 入口文件使用示例(完整)

以下示例展示如何在脚本入口文件 main() 中读取所有类型控件的值,并据其控制脚本逻辑。覆盖:bool、number、text、select、date、time、slider、file、multi_select、tag 等全部控件类型。这是实际项目中最核心的模式。

Lua - 入口文件完整示例(全部控件读取 + 使用)
-- ============================================================
-- 第一步:加载设置字段定义文件
-- ============================================================
dofile("settings_fields.lua")

-- ============================================================
-- 第二步:main() 入口函数 - 获取并读取所有控件值
-- ============================================================
function main()
    log("==================================================")
    log("  古龙精灵 - 使用示例")

    -- ===== 获取用户设置 =====
    local settings = get_user_settings()

    -- ===== ☑️ bool(布尔开关)=====
    -- 中文key必须用方括号 settings["key"]
    local auto_fight = false
    if settings["auto_fight_自动打怪"] ~= nil then
        auto_fight = settings["auto_fight_自动打怪"]
    end
    -- 英文key可用点号语法
    local auto_pickup = settings.auto_pickup
    if auto_pickup == nil then auto_pickup = true end

    -- ===== 🔢 number(数字输入)=====
    -- 读取并在脚本中使用,单位由控件定义决定(秒、%、分钟等)
    local fight_interval = settings["fight_interval"] or 5           -- 控件单位:秒
    local hp_threshold = settings.hp_threshold or 30                      -- 控件单位:%
    local max_duration = settings.max_duration or 120                    -- 控件单位:分钟
    local move_speed = settings.move_speed or 1.5                      -- 控件单位:倍(浮点数)
    log("  📊 打怪间隔=" .. fight_interval .. "秒, 回血<" .. hp_threshold .. "%, 最长" .. max_duration .. "分钟, 移速x" .. move_speed)

    -- ===== 📝 text(文本输入)=====
    -- 读取用户输入的文本,常用于匹配目标名称、过滤关键词等
    local target_monster = settings.target_monster or "银月贤者"
    local filter_keywords = settings.filter_keywords or ""
    log("  📝 目标怪物=" .. target_monster .. ", 过滤词=" .. filter_keywords)

    -- ===== 📋 select(下拉选择)=====
    -- 读取用户选择的值,用于条件判断
    local difficulty = settings.difficulty or "normal"
    local target_map = settings.target_map or "map1"
    if difficulty == "hell" then
        log("  ⚠️ 地狱难度已开启!")
    end

    -- ===== 📅 date(日期选择)=====
    local start_date = settings.start_date or "2025-01-01"
    -- 可用于判断当天是否在设定日期之后才执行
    local y, m, d = get_current_time()
    local today = string.format("%d-%02d-%02d", y, m, d)
    if today > start_date then
        log("  📅 日期已到达,开始执行...")
    end

    -- ===== ⏰ time(时间选择)=====
    local start_time = settings.start_time or "08:00"
    -- 解析时间字符串用于判断当前是否在指定时间之后
    local start_hour = tonumber(start_time:sub(1, 2)) or 8
    if h >= start_hour then
        log("  ⏰ 已过" .. start_time .. ",开始执行任务")
    end

    -- ===== 🎚️ slider(滑块)=====
    local volume = settings.volume or 80
    -- 将滑块值(0-100)映射到实际逻辑(如点击速度比例)
    local click_speed = 1.0 + (volume / 100) * 2.0  -- 映射为 1.0~3.0 倍速
    log("  🎚️ 音量=" .. volume .. ", 点击倍速=" .. click_speed)

    -- ===== 📁 file(文件选择)=====
    local script_file = settings.script_file or ""
    if script_file ~= "" then
        log("  📁 用户指定脚本文件: " .. script_file)
        -- 可以 dofile(script_file) 加载用户指定的脚本
    end

    -- ===== ☑️ multi_select(多选列表)=====
    -- 多选列表返回的是 table(数组),包含所有选中的 value
    local target_maps = settings.target_maps or {}
    if #target_maps > 0 then
        log("  🗺️ 多选地图: " .. table.concat(target_maps, ", "))
        -- 遍历每个选中的地图执行逻辑
        for i, map_name in ipairs(target_maps) do
            log("    正在处理地图: " .. map_name)
            -- 跳转到对应地图、执行对应逻辑...
        end
    else
        log("  🗺️ 未选择地图,使用默认地图")
    end

    -- ===== 🏷️ tag(分组标签)=====
    -- 分组标签返回的是 table(数组),包含所有选中的标签 value
    local item_filter = settings.item_filter or {}
    local filter_equip = false
    local filter_potion = false
    for i, tag in ipairs(item_filter) do
        if tag == "equip" then filter_equip = true end
        if tag == "potion" then filter_potion = true end
    end
    log("  🏷️ 物品过滤: 装备=" .. tostring(filter_equip) .. ", 药水=" .. tostring(filter_potion))

    -- ===== 🎨 color(颜色选择)=====
    local theme_color = settings.theme_color or "#FF5722"
    log("  🎨 主题颜色: " .. theme_color)

    -- ===== 主循环:根据控件值控制脚本逻辑 =====
    while true do
        if auto_fight then
            log("⚔️ 自动打怪开始!目标: " .. target_monster .. ", 难度: " .. difficulty)
            -- 调用对应的打怪子程序
        else
            log("⚔️ 自动打怪已关闭")
            log("  [提示] 请在用户控制面板中开启自动打怪")
        end
        sleep(fight_interval * 1000)
    end
end

main()

8. 📅 其他控件

日期选择 (date)、时间选择 (time)、滑块 (slider)、文件选择 (file)、多选列表 (multi_select)、分组标签 (tag)

其他控件示例
-- 日期选择
{key = "start_date", label = "开始日期", type = "date", default = "2025-01-01", icon = "📅"},

-- 时间选择
{key = "start_time", label = "开始时间", type = "time", default = "08:00", icon = "⏰"},

-- 滑块
{key = "volume", label = "音量调节", type = "slider", default = 80, min = 0, max = 100, step = 1, icon = "🔊"},

-- 文件选择
{key = "script_file", label = "脚本文件", type = "file", default = "", icon = "📄", placeholder = "选择脚本文件..."},

-- 多选列表
{key = "target_maps", label = "目标地图(多选)", type = "multi_select", default = {}, icon = "🗺️",
 options = {{value = "map1", label = "新手村"},{value = "map2", label = "幽暗森林"},{value = "map3", label = "冰封雪域"}}},

-- 分组标签
{key = "item_filter", label = "物品过滤", type = "tag", default = {}, icon = "🏷️",
 options = {{value = "equip", label = "装备"},{value = "potion", label = "药水"},{value = "material", label = "材料"}}},

⚙️ 脚本中获取用户设置参数

在脚本中,用户通过控制面板配置的设置可以通过多种方式获取。以下是完整的使用方法:

方法一:全局变量 user_settings

user_settings 是一个全局 table,包含用户在控制面板保存的所有设置。

Lua - 使用 user_settings
while true do
    if user_settings.auto_fight then
        log("自动打怪已开启")
        -- 执行打怪逻辑
    end
    sleep((user_settings.fight_interval or 5) * 1000)
end

方法二:get_setting() 函数

安全地获取单个设置项的值,如果键不存在则返回默认值。

Lua - 使用 get_setting
local auto_fight = get_setting("auto_fight", true)        -- 获取布尔值,默认 true
local fight_interval = get_setting("fight_interval", 5) -- 获取数字,默认 5
local target = get_setting("target_monster", "银月贤者") -- 获取文本
local difficulty = get_setting("difficulty", "normal") -- 获取下拉选择

if auto_fight then
    log("自动打怪已开启,间隔: " .. fight_interval .. "秒")
end

方法三:set_setting() 函数

在脚本中动态修改用户配置项的值。

Lua - 使用 set_setting
set_setting("auto_fight", false)       -- 关闭自动打怪
set_setting("fight_interval", 10)   -- 修改打怪间隔为10秒
set_setting("target_monster", "boss") -- 切换目标怪物

方法四:从 settings 字典读取(节点模式)

在节点模式下,通过服务器 API 获取用户设置后使用。这是实际项目(梦幻逍遥脚本)中使用的方式:

Lua - 从服务器获取设置后使用
-- 获取设置
local settings = get_user_settings()

-- 读取配置项(中文 key 必须用方括号)
local auto_fight_自动饱食度 = false
if settings["auto_fight_自动饱食度"] ~= nil then
    auto_fight_自动饱食度 = settings["auto_fight_自动饱食度"]
end

auto_fight_自动打怪 = false
auto_fight_自动打怪 = settings["auto_fight_自动打怪"]

-- 控制主循环
if auto_fight_自动打怪 then
    log("⚔️ 自动打怪开始!")
    -- 执行打怪逻辑
else
    log("⚔️ 自动打怪已关闭")
end

-- ⚠️ 重要:包含中文的 key 必须使用方括号语法 settings["key"]
-- 不能用 settings.key 点号语法

扁平化设置字段

当设置字段包含 fold 和 tab_container 嵌套结构时,使用 flatten_settings_fields() 函数提取所有字段的默认值:

Lua - 扁平化与默认值
function flatten_settings_fields(fields)
    local result = {}
    for _, field in ipairs(fields) do
        if field.type == "tab_container" then
            for _, tab in ipairs(field.tabs or {}) do
                for _, f in ipairs(tab.fields or {}) do
                    table.insert(result, f)
                end
            end
        elseif field.type == "fold" then
            for _, f in ipairs(field.fields or {}) do
                if f.type == "tab_container" then
                    for _, tab in ipairs(f.tabs or {}) do
                        for _, tf in ipairs(tab.fields or {}) do
                            table.insert(result, tf)
                        end
                    end
                else
                    table.insert(result, f)
                end
            end
        else
            table.insert(result, field)
        end
    end
    return result
end

-- 获取所有默认设置
function get_default_settings()
    local settings = {}
    local flat = flatten_settings_fields(SCRIPT_SETTINGS_FIELDS)
    for _, field in ipairs(flat) do
        settings[field.key] = field.default
    end
    return settings
end

🖱️ 触控方法 11个API

tap点击
点击坐标为x,y的点(推荐使用)
📥 参数:
x (number): 当前屏幕横坐标 y (number): 当前屏幕纵坐标
📤 返回值:boolean - true表示成功
示例
-- 点击坐标
tap(100, 100)

-- 配合找图使用
local result = find_image("images/button.png")
if result and result.success then
    tap(result.x, result.y)
end
longTap长点击
长点击坐标为x,y的点(按住约500ms后抬起)
📥 参数:
x (number): 当前屏幕横坐标 y (number): 当前屏幕纵坐标
示例
longTap(100, 100)
swipe划动
模拟从一点滑动到另外一点(所有模式可用,推荐用于滑动操作)
📥 参数:
x1 (number): 起点x / y1 (number): 起点y / x2 (number): 终点x / y2 (number): 终点y / time (number, 可选): 耗时(毫秒),默认300
示例
-- 从左滑到右
swipe(200, 200, 800, 200, 500)

-- 向上滑动翻页
swipe(540, 800, 540, 200, 300)
touchDown / touchMove / touchUp手指按下/移动/弹起
底层触摸控制,用于复杂手势(推荐使用 swipe 替代)
📥 参数:
id (number): 手指索引0-4 / x,y (number): 坐标
示例
-- 从下往上滑动
touchDown(1, 297, 327)
for i = 1, 300 do
    touchMove(1, 297, 327 - i)
end
touchUp(1)
touchMoveEx模拟滑动增强版
带时间控制的滑动(增强版)
📥 参数:
id (number): 手指索引 / x,y (number): 目标坐标 / time (number): 滑动耗时(毫秒)
示例
touchDown(1, 100, 100)
sleep(50)
touchMoveEx(1, 300, 300, 800)
touchUp(1)
keyPress / keyDown / keyUp按键
模拟物理按键操作(home/back/recent/power等)
示例
-- 按HOME键
keyPress("home")
-- 按返回键
keyPress("back")

-- 按下并弹起
keyDown("home")
sleep(100)
keyUp("home")
inputText模拟输入文字
模拟输入文字
示例
inputText("hello nice!!!")
imeLib.setText / imeLib.deleteChar / imeLib.finishInput / imeLib.keyEvent输入法系列
使用输入法进行文本输入、删除、确认等操作
示例
-- 输入法输入文本
imeLib.setText("hello")
-- 删除一个字符
imeLib.deleteChar()
-- 完成输入
imeLib.finishInput()
-- 模拟按键字符
imeLib.keyEvent(0, 7)  -- 按下字符"0"
imeLib.keyEvent(1, 7)  -- 弹起字符"0"
setOnTouchListener获取用户触摸屏幕坐标
设置触摸监听,获取用户在屏幕上的触摸坐标(仅在root/激活模式下有效)
示例
function onTouchEvent(x, y)
    log("触摸坐标: " .. x .. ", " .. y)
end
setOnTouchListener(onTouchEvent)
sleep(1000000)

🔍 图像识别 8个API

screenshot截图
截取当前设备屏幕
示例
-- 保存截图到文件
screenshot("output/screen.png")

-- 截图到内存(用于找图)
local img = screenshot()
local result = find_image("images/target.png")
find_image找图
在屏幕截图中查找指定模板图片的位置
📥 参数:
template_path (string): 模板图片路径 / threshold (number, 可选): 匹配阈值0.0~1.0,默认0.8
📤 返回值:table - {success, x, y, center_x, center_y, confidence}
示例
local result = find_image("images/button.png")
if result and result.success then
    tap(result.x, result.y)
    log(string.format("置信度: %.2f", result.confidence))
end
wait_image等待图片
等待指定图片在屏幕上出现(带超时机制)
示例
-- 等待图片出现(最多等10秒)
local result = wait_image("images/loading_done.png")
if result then
    tap(result.x, result.y)
end

-- 等待30秒超时
local result = wait_image("images/login_success.png", 30)
if not result then
    log("登录超时!")
end
exists判断存在
判断指定图片是否在屏幕上存在
示例
if exists("images/button.png") then
    log("按钮存在")
    tap(100, 200)
end
get_color获取颜色
获取屏幕指定坐标点的颜色值(返回16进制颜色字符串)
📤 返回值:string - 如 "ff0000"(红色)
示例
-- 获取坐标颜色并解析RGB
local color = get_color(500, 300)
local r, g, b = tonumber("0x"..color:sub(1,2)), tonumber("0x"..color:sub(3,4)), tonumber("0x"..color:sub(5,6))
log(r..","..g..","..b)

-- 判断颜色
if r > 200 then log("该点偏红") end
find_color找色
在屏幕上查找所有匹配指定颜色的像素点
示例
-- 查找所有红色像素
local points = find_color({255, 0, 0}, 20)
log("找到 " .. #points .. " 个红色像素点")
findMultiColor多点取色
在屏幕上查找与指定多点颜色匹配的位置(最常用的取色函数)
📥 参数:
x1,y1,x2,y2 (number): 搜索区域 / base_color (string): 基准点颜色 "RRGGBB" / offset_str (string): 偏移点 "dx|dy|RRGGBB|..." / direction (number, 可选): 方向0-4 / sim_threshold (number, 可选): 相似度0.0~1.0
示例
local result = findMultiColor(0, 0, 1080, 1920, "ff0000", "10|0|00ff00|20|0|0000ff", 0, 0.9)
if result then
    tap(result[1], result[2])
end
cmpColorEx / findMultiColorAll / findColor更多图色函数
cmpColorEx: 比较多点颜色(返回匹配索引)/ findMultiColorAll: 查找所有匹配位置 / findColor: 查找任意匹配颜色
示例
-- 比较多点颜色
local ret = cmpColorEx("ff0000", "10|0|00ff00|20|0|0000ff", 0, 0.9)
if ret ~= -1 then log("颜色匹配成功") end

-- 查找所有匹配位置
local results = findMultiColorAll(0, 0, 1080, 1920, "ff0000", "10|0|00ff00|20|0|0000ff")
for i, pos in ipairs(results) do
    tap(pos[1], pos[2])
end

📝 OCR文字识别 4个API

使用本地ONNX模型进行文字识别,无需联网。

ocr_recognize_localOCR本地文字识别
识别指定区域的文字
📥 参数:
lang (string): 'ch'(中英文)/ region (table): {x1, y1, x2, y2}
📤 返回值:table - {success, text, error}
示例
local text = ocr_recognize_local("ch", { 987, 332, 1121, 368 })
if text.success then
    log("识别结果: " .. text.text)
    if text.text == "开始挑战" then
        tap(1050, 350)
    end
end
ocr_find_text_localOCR本地查找文字
在指定区域查找目标文字并返回位置(推荐用于定位后点击)
📤 返回值:table - {found, x, y, w, h, text, confidence}
示例
local pos = ocr_find_text_local("开始", nil, {987, 332, 1121, 368})
if pos and pos.found then
    -- 点击文字中心
    tap(pos.x + pos.w / 2, pos.y + pos.h / 2)
end
ocr_recognize_detail_localOCR本地文字识别详情
识别区域中所有文字块,返回每个文字块的位置和内容
示例
local detail = ocr_recognize_detail_local("ch", {800, 300, 1200, 500})
if detail.success then
    for i, item in ipairs(detail.results) do
        if string.find(item.text, "开始挑战") then
            tap(item.x + item.w / 2, item.y + item.h / 2)
            break
        end
    end
end
ocr_find_text_all_localOCR本地查找所有匹配文字
查找所有匹配目标文字的位置,适合多个相同文字的场景
示例
local result = ocr_find_text_all_local("确认", nil, {100, 200, 600, 400})
if result.found then
    -- 从下往上点击所有匹配项
    for i = result.count, 1, -1 do
        local item = result.results[i]
        tap(item.x + item.w / 2, item.y + item.h / 2)
        sleep(500)
    end
end

🤖 YOLO目标检测 6个API

yolo_detectYOLO目标检测
YOLO v11目标检测 - 检测屏幕上的物体
📥 参数:
conf_threshold (number, 可选): 置信度阈值,默认0.25 / iou_threshold (number, 可选): IoU阈值默认0.45
示例
local result = yolo_detect()
if result.success then
    log("检测到 " .. result.count .. " 个物体")
    for i, det in ipairs(result.detections) do
        log(string.format("%s: %.2f, (%d,%d)", det.class_name, det.confidence, det.center_x, det.center_y))
    end
    -- 点击第一个检测到的物体
    if result.count > 0 then
        tap(result.detections[1].center_x, result.detections[1].center_y)
    end
end
yolo_load_custom_model加载自定义YOLO模型
加载自定义训练的NCNN格式YOLO模型(.param + .bin)
示例
-- 加载自定义模型
local result = yolo_load_custom_model("resources/models/yolov11_npc.param")
if result.success then
    log("类别: " .. table.concat(result.class_names, ", "))
    -- 执行检测
    local det = yolo_detect(0.35)
end
yolo_detect_file / yolo_detect_and_draw / yolo_load_model / yolo_get_available_models
yolo_detect_file: 从图片文件检测 / yolo_detect_and_draw: 检测并绘制边界框 / yolo_load_model: 切换内置模型 / yolo_get_available_models: 获取模型列表
示例
-- 从文件检测
local result = yolo_detect_file("screenshot.png")

-- 检测并绘制
local result = yolo_detect_and_draw()

-- 加载内置模型
yolo_load_model("yolo11n")  -- Nano最快
yolo_load_model("yolo11s")  -- Small

-- 查看可用模型
local models = yolo_get_available_models()
for i, m in ipairs(models) do
    log(m.name .. ": " .. (m.exists and "✅" or "⬇️"))
end

🔧 工具函数 38个API

sleep等待
等待指定毫秒数
示例
sleep(2000)   -- 等待2秒
sleep(500)    -- 等待0.5秒
random_sleep随机等待
随机等待一段时间(模拟人类操作,避免被检测)
示例
random_sleep(1000, 3000)   -- 随机等待1~3秒
tap(500, 300)
random_sleep(300, 800)   -- 模拟人类点击间隔
tap(500, 400)
log输出日志
输出日志信息到控制台
示例
log("脚本开始执行")
log(string.format("坐标: (%d, %d)", x, y))
user_settings / get_setting / set_setting用户设置
获取/设置用户在控制面板中配置的参数(详见上方"脚本参数获取"章节)
示例
-- 全局变量
if user_settings.auto_fight then ... end

-- 安全获取
local val = get_setting("key", defaultValue)

-- 动态修改
set_setting("key", newValue)
http_get / http_postHTTP请求
发送HTTP GET/POST请求(支持JSON和表单数据)
示例
local resp = http_get("http://api.example.com/data")
local data = json_parse(resp)

local resp = http_post("http://api.example.com/login", nil, {username = "admin", password = "123456"})
open_url打开网址
在默认浏览器中打开URL
示例
open_url("http://www.baidu.com")
write_file写入文件
写入内容到文件(PC调试模式)
示例
write_file("output/result.txt", "执行完成")
call_python调用Python
调用Python文件中的函数(Lua→Python跨语言调用)
示例
local result = call_python("scripts/my_module.py", "process_data", "input.txt")
get_account_info获取账号信息
获取当前登录的账号信息(节点模式下使用)
示例
local account = get_account_info()
if account then log("账号: " .. account.account_id) end
get_device_info获取设备信息
获取当前连接的设备信息
示例
local info = get_device_info()
if info then log("设备: " .. info.device_name) end

更多工具函数(简要列表)

函数名说明示例
get_clipboard获取剪贴板内容local text = get_clipboard()
set_clipboard设置剪贴板内容set_clipboard("文本")
get_battery_level获取电池电量百分比local b = get_battery_level()
get_network_type获取网络类型local n = get_network_type()
is_screen_on检查屏幕是否亮起if not is_screen_on() then ...
wake_screen唤醒设备屏幕wake_screen()
get_volume / set_volume获取/设置媒体音量set_volume(15)
get_notifications获取通知列表local n = get_notifications()
clear_notifications清除通知栏clear_notifications()
get_location获取GPS定位local loc = get_location()
get_contacts获取联系人local c = get_contacts()
get_sms_list获取短信列表local s = get_sms_list(10)
send_sms发送短信send_sms("号", "内容")
make_call拨打电话make_call("10086")
get_sim_info获取SIM卡信息local s = get_sim_info()
get_wifi_list获取WiFi列表local w = get_wifi_list()
connect_wifi连接WiFiconnect_wifi("名", "密码")
get_bluetooth_devices获取蓝牙设备local b = get_bluetooth_devices()
get_file_list获取文件列表local f = get_file_list("/sdcard/")
download_file下载文件到设备download_file(url, path)
upload_file上传文件到服务器upload_file(path, url)
delete_file删除文件delete_file("/sdcard/temp.txt")
create_dir创建目录create_dir("/sdcard/app")
file_exists检查文件是否存在if file_exists(path) then ...
read_file_content读取文件内容local c = read_file_content(path)
write_file_content写入文件内容write_file_content(path, c)
get_sdcard_path等获取各种路径get_download_path()

📱 设备方法 13个API

show_message显示消息
在设备屏幕上显示消息(APK模式可用)
示例
show_message("任务开始执行", "top")
show_message("任务完成!", "bottom", 5000)
toast显示提示
在设备上显示Toast弹窗
示例
toast("操作完成")
runApp / stopApp打开/关闭应用
打开或关闭指定应用(传入包名)
示例
runApp("com.tencent.mm")
stopApp("com.tencent.mm")
frontAppName / appIsFront / appIsRunning
获取/判断前台应用和运行状态
示例
local pkg = frontAppName()
if appIsFront("com.example.game") then
    log("游戏在前台")
end
readPasteboard / writePasteboard读写剪贴板
读取/写入剪贴板内容
示例
writePasteboard("123")
local text = readPasteboard()
rnd生成随机整数
生成指定范围的随机整数(包含端点)
示例
local num = rnd(1, 100)
local x = rnd(100, 500)   -- 随机点击位置
getDisplaySize获取屏幕分辨率
获取设备的屏幕宽度和高度
示例
local w, h = getDisplaySize()
tap(w / 2, h / 2)  -- 点击屏幕中心
setControlBarPosNew设置悬浮窗位置
设置悬浮窗位置(按比例0~1.0)
示例
setControlBarPosNew(0, 0)        -- 左上角
setControlBarPosNew(1.0, 0)      -- 右上角
setControlBarPosNew(0.5, 0.5)    -- 屏幕中心
get_current_time获取当前时间
获取当前年月日时分秒
示例
local y, m, d, h, mi, s = get_current_time()
log(string.format("%d-%02d-%02d %02d:%02d:%02d", y, m, d, h, mi, s))
get_uptime获取开机运行时间
获取系统开机运行时间(毫秒)
示例
local hours = get_uptime() / 3600000

📝 字符串方法 9个API

函数名说明示例
splitStr根据分隔符拆分字符串splitStr("a#b#c", "#") → {"a","b","c"}
string.lower转换为小写string.lower("AbC") → "abc"
string.upper转换为大写string.upper("AbC") → "ABC"
string.find查找子串位置string.find("Hello Lua", "Lua") → 7, 9
string.reverse反转字符串string.reverse("abc") → "cba"
string.format格式化字符串string.format("值=%d", 666)
string.char / string.byteASCII与字符互转string.char(97) → "a" / string.byte("a") → 97
string.len获取字节长度string.len("abc") → 3
string.rep重复字符串n次string.rep("ab",3) → "ababab"

UTF-8 扩展方法(支持中文)

函数名说明示例
utf8.inStrUTF-8查找子串utf8.inStr(1, "中国人民", "人民")
utf8.inStrRevUTF-8反向查找utf8.inStrRev("中国人民人民", "人民")
utf8.strReverseUTF-8字符串反转utf8.strReverse("中国人民")
utf8.lengthUTF-8字符长度utf8.length("中国人民万岁")
utf8.left从左截取n个字符utf8.left("中国人民", 2)
utf8.right从右截取n个字符utf8.right("中国人民", 2)
utf8.mid中间截取utf8.mid("中国人民", 2, 2)
utf8.strCut移除指定范围字符utf8.strCut("中国人民", 2, 2)

📊 数组方法 4个API

函数名说明示例
# (数组长度)获取数组元素个数local len = #arr
table.concat连接数组元素为字符串table.concat({"a","b"}, ",") → "a,b"
table.insert插入元素table.insert(arr, "x") / table.insert(arr, 1, "x")
table.remove移除元素table.remove(arr, 2) → 移除第2个元素
table.sort数组排序table.sort(nums) / table.sort(nums, function(a,b) return a>b end)

📋 JSON方法 2个API

json_parseJSON解析
解析JSON字符串为Lua table
示例
local data = json_parse('{"name":"test","value":123}')
log("名称: " .. data.name)  -- 输出: test
json_stringifyJSON序列化
将Lua table序列化为JSON字符串
示例
local data = {name = "test", value = 123}
local json_str = json_stringify(data)
log(json_str)  -- 输出: {"name":"test","value":123}

📄 完整脚本示例

以下是一个完整的游戏挂机脚本示例,演示了触控、找图、取色、OCR、用户设置等核心功能的使用。

Lua - 梦幻逍遥脚本(核心逻辑摘录)
-- ============================================================
-- 梦幻逍遥脚本 - 核心逻辑示例
-- 演示:触控、取色、OCR、用户设置获取
-- ============================================================

-- 加载子模块
dofile("settings_fields.lua")
dofile("server_api.lua")

local 打怪调用 = require("子程序_打怪")
local 综合调用 = require("子程序_综合调用")
local 组队调用 = require("子程序_组队")

-- 判断是否正在战斗中(取色方式)
function 判断_人物停止了()
    -- 取色判断:如果画面中某特征颜色不变,说明人物停在原处
    local colorStr = get_color(451, 585)
    local r, g, b = tonumber("0x"..colorStr:sub(1,2)), tonumber("0x"..colorStr:sub(3,4)), tonumber("0x"..colorStr:sub(5,6))
    
    sleep(900)
    
    local colorStr2 = get_color(451, 585)
    local r1, g1, b1 = tonumber("0x"..colorStr2:sub(1,2)), ...
    
    -- 颜色不变 = 人物已停止
    if r == r1 and g == g1 and b == b1 then
        return true
    end
    return false
end

-- 主函数
function main()
    log("==================================================")
    log("  古龙精灵 - 梦幻逍遥")
    
    -- 获取用户设置
    local settings = get_user_settings()
    
    -- ⚠️ 中文key必须用方括号语法
    local auto_fight_自动饱食度 = settings["auto_fight_自动饱食度"]
    local auto_自动巡山 = settings["auto_自动巡山"]
    local auto_自动除妖 = settings["auto_自动除妖"]
    local auto_fight_自动打怪 = settings["auto_fight_自动打怪"]
    
    -- 主循环
    while true do
        综合调用.操作_关闭异常提示弹出()
        
        if auto_自动除妖 then
            log("⚔️ 自动除妖开始!")
            主程序调用.主程序_除妖()
        end
        
        if auto_自动巡山 then
            log("⭐ 自动巡山开始!")
            主程序调用.主程序_巡山()
        end
        
        if auto_fight_自动打怪 then
            log("⚔️ 自动打怪开始!")
            主程序调用.主程序_除妖()
        end
        
        sleep(1000)
    end
end

main()

抓取工具使用技巧

在 PC 开发工具的工具 → 抓取窗口中:

  • 右键点击画面 → 取色:自动生成 get_color(x, y) 代码
  • 左键框选区域:自动生成 findMultiColor 代码(多点取色)
  • Ctrl+左键自定义取色:手动添加取色点,生成多点取色代码
  • 右键 → ONNX查找文字:自动生成 ocr_find_text_local 代码
  • 左键框选 + OCR模式:自动生成 ocr_recognize_local 代码

代码插入方式

在开发工具的右侧 API参考面板和UI设计面板中,点击任意代码即可自动插入到编辑器复制到剪贴板

🐉 古龙精灵 · 自动化脚本开发平台 © 2026

API参考手册 · 版本 v1.1.0

✅ 已复制到剪贴板