文本与代码预览

卡密.txt

txt · 203.5 KB

-------------使用说明--------
---对接之前请在你们后台的接口管理,接口安全根据以下内容配置
--[[
1、加密方式:RC4对称加密
2、加密编码方式:Base64编码
3、请求加密方式:全部加密
4、响应加密方式:全部加密
5、随机数防劫持:开
6、签名方式:SHA256
7、时间戳验证 :30000(30秒)
8、签名计算规则:方式二
  脚本放置位置搜索词:这里放置你的脚本代码
]]
--
-- 应用编号
local appId = 1171
-- RC4秘钥
local encryptKey = "aXyxdnBSjac6Ckdb5nTZGmXp8KFrbCWS"
-- 应用秘钥
local appKey = "SJMDTF4OU9SHSMJGZNX0X5JCQQTKVNZX"
 -- 应用版本号
local version = "2.6"
 -- 店铺地址ID
local shopId = 9  
 -- 公告变量ID
local noticeId = 633
-- 时间戳验证时间差(单位:毫秒)- 新增配置
local timestampTolerance = 5000000
local http = gg.makeRequest
-- GG框架网络请求
local json = { _version = "0.1.2" }
-- JSON编解码对象
local shopAddr = ""
  -- 店铺地址

-- 请将您的主脚本代码放在这个函数内
local function developerMainScript()
    -- 这里放置你的脚本代码
    gg.alert("验证成功!开始执行主脚本...")

end

-- 核心加密
local function decryptDomains()
   
    local encoded1 = "aHR0cHM6Ly95ei5ibHlmdy5jbg=="
    local encoded2 = "aHR0cHM6Ly9vcHMubmV3LWNkbi5jb20="
    
    local function base64Decode(data)
        local b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
        data = string.gsub(data, '[^'..b64chars..'=]', '')
        return (data:gsub('.', function(x)
            if (x == '=') then return '' end
            local r,f='',(b64chars:find(x)-1)
            for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
            return r;
        end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
            if (#x ~= 8) then return '' end
            local c=0
            for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
            return string.char(c)
        end))
    end
    
    local domain1 = base64Decode(encoded1)
    local domain2 = base64Decode(encoded2)
    
    return {domain1, domain2}
end

local DOMAINS = decryptDomains()
local currentDomain = DOMAINS[1]
local domainIndex = 1
local isDomainInitialized = false 

local SECURE_STORAGE_DIR = "/storage/emulated/0/lua_secure/"
local CONFIG_FILE_NAME = "secure_config.dat"

local function stringTrim(str)
    str = tostring(str)
    return str:gsub("^%s+", ""):gsub("%s+$", "")
end

local function completeDomainProtocol(domain)
    domain = stringTrim(domain)
    if domain:find("^https?://") then
        return { domain }
    end
    return { "https://" .. domain, "http://" .. domain }
end

-- 时间戳验证函数 
local function validateTimestamp(serverTimestamp)
    if not serverTimestamp then return false end
    
    local clientTime = os.time() * 1000  -- 客户端当前时间戳(毫秒)
    local timeDiff = math.abs(clientTime - serverTimestamp)
    
    -- 检查时间差是否在容忍范围内
    if timeDiff > timestampTolerance then
        gg.alert(string.format("时间戳验证失败!\n时间差:%.1f秒(最大容忍:%.1f秒)", 
                              timeDiff/1000, timestampTolerance/1000))
        return false
    end
    
    return true
end

-- 获取Android ID
local function getAndroidId()
    local androidId = ""
    local ok, serialNo = pcall(gg.getProperty, "ro.serialno")
    if ok and serialNo and stringTrim(serialNo) ~= "" then
        androidId = stringTrim(serialNo)
    else
        local ok2, androidIdRaw = pcall(gg.getProperty, "persist.sys.android_id")
        if ok2 and androidIdRaw and stringTrim(androidIdRaw) ~= "" then
            androidId = stringTrim(androidIdRaw)
        end
    end
    return androidId
end

-- 读取安卓设备IMEI
local function getImei()
    local imei = ""
    local imeiPaths = {
        "/data/user_de/0/com.android.providers.telephony/databases/telephony.db",
        "/data/data/com.android.providers.telephony/databases/telephony.db"
    }
    for _, path in ipairs(imeiPaths) do
        local ok, file = pcall(io.open, path, "r")
        if ok and file then
            local content = file:read("*a")
            file:close()
            local matchImei = content:match("IMEI[^%d]*(%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d)")
            if matchImei then
                imei = matchImei
                break
            end
        end
    end
    return imei
end

local function generateAndroidDeviceMac()
    local deviceId = ""
    local androidId = getAndroidId()
    if androidId ~= "" then
        deviceId = androidId
    else
        local imei = getImei()
        if imei ~= "" then
            deviceId = imei
        else
            deviceId = tostring(math.random(10000000, 99999999)) .. os.time()
        end
    end
    return SHA256(deviceId)
end

-- 随机字符串生成
function getRandomString()
    return tostring(math.random(10000000, 99999999))
end

function RC4(code, key)
    code = tostring(code)
    key = tostring(key)
    XINXIN = {}
    function XINXIN.__andBit(left, right)
        return (left == 1 and right == 1) and 1 or 0
    end
    function XINXIN.__orBit(left, right)
        return (left == 1 or right == 1) and 1 or 0
    end
    function XINXIN.__xorBit(left, right)
        return (left + right) == 1 and 1 or 0
    end
    function XINXIN.__base(left, right, op)
        if left < right then
            left, right = right, left
        end
        local res = 0
        local shift = 1
        while left ~= 0 do
            local ra = left % 2
            local rb = right % 2
            res = shift * op(ra, rb) + res
            shift = shift * 2
            left = math.modf(left / 2)
            right = math.modf(right / 2)
        end
        return res
    end
    function XINXIN.andOp(left, right)
        return XINXIN.__base(left, right, XINXIN.__andBit)
    end
    function XINXIN.xorOp(left, right)
        return XINXIN.__base(left, right, XINXIN.__xorBit)
    end
    function XINXIN.orOp(left, right)
        return XINXIN.__base(left, right, XINXIN.__orBit)
    end
    function XINXIN.notOp(left)
        return left > 0 and -(left + 1) or -left - 1
    end
    function XINXIN.lShiftOp(left, num)
        return left * (2 ^ num)
    end
    function XINXIN.rShiftOp(left, num)
        return math.floor(left / (2 ^ num))
    end
    function encrypt(text, key)
        local function KSA(key)
            local keyLen = string.len(key)
            local schedule = {}
            local keyByte = {}
            for i = 0, 255 do
                schedule[i] = i
            end
            for i = 1, keyLen do
                keyByte[i - 1] = string.byte(key, i, i)
            end
            local j = 0
            for i = 0, 255 do
                j = (j + schedule[i] + keyByte[i % keyLen]) % 256
                schedule[i], schedule[j] = schedule[j], schedule[i]
            end
            return schedule
        end
        local function PRGA(schedule, textLen)
            local i = 0
            local j = 0
            local k = {}
            for n = 1, textLen do
                i = (i + 1) % 256
                j = (j + schedule[i]) % 256
                schedule[i], schedule[j] = schedule[j], schedule[i]
                k[n] = schedule[(schedule[i] + schedule[j]) % 256]
            end
            return k
        end
        local function output(schedule, text)
            local len = string.len(text)
            local c = nil
            local res = {}
            for i = 1, len do
                c = string.byte(text, i, i)
                res[i] = string.char(XINXIN.xorOp(schedule[i], c))
            end
            return table.concat(res)
        end
        local textLen = string.len(text)
        local schedule = KSA(key)
        local k = PRGA(schedule, textLen)
        return output(k, text)
    end
    return encrypt(code, key)
end

-- Base64编码解码
function Base64Convert(str, isEncrypt)
    str = tostring(str)
    if isEncrypt then
        local b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
        local bytes = {}
        for i = 1, #str do
            bytes[#bytes + 1] = str:byte(i)
        end
        local result = ""
        for i = 1, #bytes, 3 do
            local a, b, c = bytes[i], bytes[i+1], bytes[i+2]
            local n = (a or 0) * 0x10000 + (b or 0) * 0x100 + (c or 0)
            local b1 = math.floor(n / 262144) % 64
            local b2 = math.floor(n / 4096) % 64
            local b3 = math.floor(n / 64) % 64
            local b4 = n % 64
            result = result .. b64chars:sub(b1+1, b1+1) .. b64chars:sub(b2+1, b2+1)
            if b then
                result = result .. b64chars:sub(b3+1, b3+1)
            else
                result = result .. '='
            end
            if c then
                result = result .. b64chars:sub(b4+1, b4+1)
            else
                result = result .. '='
            end
        end
        return result
    else
        str = str:gsub("[^%w%+%/=]", "")
        local b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
        local result = ""
        for i = 1, #str, 4 do
            local chunk = str:sub(i, i+3)
            if #chunk == 0 then break end
            local values = {}
            for j = 1, 4 do
                local char = chunk:sub(j, j)
                if char == '=' then
                    values[j] = nil
                else
                    values[j] = b64chars:find(char) - 1
                end
            end
            if values[1] and values[2] then
                local byte1 = (values[1] * 4) + math.floor(values[2] / 16)
                result = result .. string.char(byte1)
                if values[3] then
                    local byte2 = ((values[2] % 16) * 16) + math.floor(values[3] / 4)
                    result = result .. string.char(byte2)
                    if values[4] then
                        local byte3 = ((values[3] % 4) * 64) + values[4]
                        result = result .. string.char(byte3)
                    end
                end
            end
        end
        return result
    end
end

-- 参数加密
local function paramEncrypt(str)
    local rc4 = RC4(str, encryptKey)
    local base64 = Base64Convert(rc4, true)
    return base64
end

-- 参数排序拼接
function sort_and_concat_params(params)
    local keys = {}
    for k, _ in pairs(params) do
        if k ~= "appId" then
            table.insert(keys, k)
        end
    end
    table.sort(keys)
    local param_str = ""
    for _, k in ipairs(keys) do
        if param_str ~= "" then
            param_str = param_str .. "&"
        end
        param_str = param_str .. k .. "=" .. tostring(params[k])
    end
    return param_str
end

-- SHA256签名函数
function SHA256(str)
    str = tostring(str)
    local k = {
        1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221,
        3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580,
        3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986,
        2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895,
        666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037,
        2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344,
        430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779,
        1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298
    }
    local h = {
        1779033703, 3144134277, 1013904242, 2773480762,
        1359893119, 2600822924, 528734635, 1541459225
    }
    local msg_len = #str
    local bit_len = msg_len * 8
    str = str .. string.char(128)
    while (#str + 8) % 64 ~= 0 do
        str = str .. string.char(0)
    end
    for i = 7, 0, -1 do
        str = str .. string.char(bit32.band(bit32.rshift(bit_len, i * 8), 255))
    end
    for chunk_start = 1, #str, 64 do
        local chunk = str:sub(chunk_start, chunk_start + 63)
        local w = {}
        for i = 0, 15 do
            local word = 0
            for j = 1, 4 do
                word = bit32.lshift(word, 8) + chunk:byte((i * 4) + j)
            end
            w[i] = word
        end
        for i = 16, 63 do
            local s0 = bit32.bxor(bit32.bxor(bit32.rrotate(w[i-15], 7), bit32.rrotate(w[i-15], 18)), bit32.rshift(w[i-15], 3))
            local s1 = bit32.bxor(bit32.bxor(bit32.rrotate(w[i-2], 17), bit32.rrotate(w[i-2], 19)), bit32.rshift(w[i-2], 10))
            w[i] = (w[i-16] + s0 + w[i-7] + s1) % 4294967296
        end
        local a, b, c, d, e, f, g, hh = h[1], h[2], h[3], h[4], h[5], h[6], h[7], h[8]
        for i = 0, 63 do
            local S1 = bit32.bxor(bit32.bxor(bit32.rrotate(e, 6), bit32.rrotate(e, 11)), bit32.rrotate(e, 25))
            local ch = bit32.bxor(bit32.band(e, f), bit32.band(bit32.bnot(e), g))
            local temp1 = (hh + S1 + ch + k[i+1] + w[i]) % 4294967296
            local S0 = bit32.bxor(bit32.bxor(bit32.rrotate(a, 2), bit32.rrotate(a, 13)), bit32.rrotate(a, 22))
            local maj = bit32.bxor(bit32.bxor(bit32.band(a, b), bit32.band(a, c)), bit32.band(b, c))
            local temp2 = (S0 + maj) % 4294967296
            hh = g
            g = f
            f = e
            e = (d + temp1) % 4294967296
            d = c
            c = b
            b = a
            a = (temp1 + temp2) % 4294967296
        end
        h[1] = (h[1] + a) % 4294967296
        h[2] = (h[2] + b) % 4294967296
        h[3] = (h[3] + c) % 4294967296
        h[4] = (h[4] + d) % 4294967296
        h[5] = (h[5] + e) % 4294967296
        h[6] = (h[6] + f) % 4294967296
        h[7] = (h[7] + g) % 4294967296
        h[8] = (h[8] + hh) % 4294967296
    end
    local result = ""
    for i = 1, 8 do
        result = result .. string.format("%08x", h[i])
    end
    return result
end

-- 基础参数获取
local function getBaseParams()
    return { 
        timestamp = os.time() * 1000,
        safeCode = getRandomString()
    }
end

-- 签名计算规则
local function goEncrypt(paramsMap)
    local baseMap = getBaseParams()
    local newTable = {}
    for k, v in pairs(paramsMap) do
        newTable[k] = v
    end
    for k, v in pairs(baseMap) do
        newTable[k] = v
    end
    local sortedParamsStr = sort_and_concat_params(newTable)
    newTable["signature"] = SHA256(sortedParamsStr .. appKey)
    local finalParams = {}
    for k, v in pairs(newTable) do
        if k ~= "appId" then
            finalParams[k] = v
        end
    end
    local paramsStr = sort_and_concat_params(finalParams)
    paramsStr = paramEncrypt(paramsStr)
    return "appId=" .. appId .. "&params=" .. paramsStr
end

-- RC4解密函数
function rc4_decrypt(key, ciphertext_base64)
    if not ciphertext_base64 or ciphertext_base64 == "" then
        return ""
    end
    local ciphertext = Base64Convert(ciphertext_base64, false)
    if ciphertext == "" then
        return ""
    end
    local function rc4_decrypt_core(key, ciphertext)
        local sbox = {}
        for i = 0, 255 do
            sbox[i] = i
        end
        local keylen = #key
        if keylen == 0 then
            return ""
        end
        local j = 0
        for i = 0, 255 do
            j = (j + sbox[i] + key:byte((i % keylen) + 1)) % 256
            sbox[i], sbox[j] = sbox[j], sbox[i]
        end
        local i, j = 0, 0
        local plaintext = {}
        for k = 1, #ciphertext do
            i = (i + 1) % 256
            j = (j + sbox[i]) % 256
            sbox[i], sbox[j] = sbox[j], sbox[i]
            local keybyte = sbox[(sbox[i] + sbox[j]) % 256]
            plaintext[k] = string.char(bit32.bxor(ciphertext:byte(k), keybyte))
        end
        return table.concat(plaintext)
    end
    return rc4_decrypt_core(key, ciphertext)
end

-- 时间戳验证响应处理
local function validateResponseTimestamp(jsonRes)
    if jsonRes and jsonRes.timestamp then
        return validateTimestamp(jsonRes.timestamp)
    end
    return true
end

-- 初始化存储目录
local function initStorageDir()
    local ok, err = pcall(function()
        os.execute("mkdir -p " .. SECURE_STORAGE_DIR)
    end)
    if not ok then
        local testFile = io.open(SECURE_STORAGE_DIR .. "test.tmp", "w")
        if testFile then
            testFile:close()
            os.remove(SECURE_STORAGE_DIR .. "test.tmp")
        else
            SECURE_STORAGE_DIR = "/storage/emulated/0/"
        end
    end
end
initStorageDir()

local function writeConfig(configData)
    local filePath = SECURE_STORAGE_DIR .. CONFIG_FILE_NAME
    local ok, file = pcall(io.open, filePath, "w")
    if not ok or not file then
        filePath = "/storage/emulated/0/" .. CONFIG_FILE_NAME
        ok, file = pcall(io.open, filePath, "w")
        if not ok or not file then
            return false
        end
    end
    local jsonData = json.encode(configData)
    local encryptedData = RC4(jsonData, encryptKey .. "_config_salt")
    file:write(encryptedData)
    file:close()
    return true
end

local function readConfig()
    local filePath = SECURE_STORAGE_DIR .. CONFIG_FILE_NAME
    local ok, file = pcall(io.open, filePath, "r")
    if not ok or not file then
        filePath = "/storage/emulated/0/" .. CONFIG_FILE_NAME
        ok, file = pcall(io.open, filePath, "r")
        if not ok or not file then
            return {}
        end
    end
    local encryptedData = file:read("*all")
    file:close()
    if encryptedData == "" then
        return {}
    end
    local success, jsonData = pcall(RC4, encryptedData, encryptKey .. "_config_salt")
    if not success then
        return {}
    end
    local success2, configData = pcall(json.decode, jsonData)
    if not success2 then
        return {}
    end
    return configData or {}
end

local function getMac()
    local config = readConfig()
    if config.mac then
        return config.mac
    end
    return nil
end

-- 保存机器码
local function saveMac(mac)
    local config = readConfig()
    config.mac = mac
    return writeConfig(config)
end

-- 卡密存储
local function saveCard(card)
    local config = readConfig()
    config.card = card
    return writeConfig(config)
end

local function getCard()
    local config = readConfig()
    return config.card or ""
end

-- 自动登录状态存储
local function saveAutoLogin(isEnable, isUserChecked, isUserRejected)
    local config = readConfig()
    if type(config.autoLogin) ~= "table" then
        config.autoLogin = {}
    end
    config.autoLogin.enable = isEnable
    config.autoLogin.checked = isUserChecked
    config.autoLogin.rejected = isUserRejected
    return writeConfig(config)
end

local function getAutoLoginStatus()
    local config = readConfig()
    if not config.autoLogin or type(config.autoLogin) ~= "table" then
        return false, false, false
    end
    return config.autoLogin.enable or false, 
           config.autoLogin.checked or false, 
           config.autoLogin.rejected or false
end

-- 清除卡密
local function clearCard()
    local config = readConfig()
    config.card = nil
    if type(config.autoLogin) ~= "table" then
        config.autoLogin = {}
    end
    config.autoLogin.enable = false
    config.autoLogin.checked = false
    config.autoLogin.rejected = false
    return writeConfig(config)
end

-- 清除所有配置(解绑时使用)
local function clearAllConfig()
    local filePath = SECURE_STORAGE_DIR .. CONFIG_FILE_NAME
    local success1 = pcall(os.remove, filePath)
    filePath = "/storage/emulated/0/" .. CONFIG_FILE_NAME
    local success2 = pcall(os.remove, filePath)
    return success1 or success2
end

local function isProtocolDomainAvailable(protocolDomain)
    local testParams = { safeCode = getRandomString() }
    local encryptStr = goEncrypt(testParams)
    local fullUrl = protocolDomain .. "/api/expand/new-ver?" .. encryptStr
    local ok, response = pcall(http, fullUrl)
    
    if not ok or not response then
        return false
    end
    local responseContent = tostring(response.content)
    if responseContent == "" then
        return false
    end
    local blockKeywords = { "屏蔽", "拦截", "禁止访问", "404 Not Found", "502 Bad Gateway", "503 Service Unavailable" }
    for _, keyword in ipairs(blockKeywords) do
        if string.find(responseContent, keyword) then
            return false
        end
    end
    local decryptStr = rc4_decrypt(encryptKey, responseContent)
    local success, jsonRes = pcall(json.decode, decryptStr)
    return success and jsonRes and jsonRes.code == 1
end

local function switchToAvailableDomain()
    if isDomainInitialized then
        return true
    end
    local foundAvailable = false
    local availableDomainIndex = 0
    local availableProtocolDomain = ""
    for i, domain in ipairs(DOMAINS) do
        local protocolDomains = completeDomainProtocol(domain)
        for _, protoDomain in ipairs(protocolDomains) do
            if isProtocolDomainAvailable(protoDomain) then
                currentDomain = protoDomain
                foundAvailable = true
                availableDomainIndex = i
                availableProtocolDomain = protoDomain
                isDomainInitialized = true
                break
            end
        end
        if foundAvailable then
            break
        end
    end
    if foundAvailable then
        return true
    else
        return false
    end
end

local function enhancedDomainCheck()
    if not switchToAvailableDomain() then
        local testParams = { safeCode = getRandomString() }
        local encryptStr = goEncrypt(testParams)
        local testUrl = currentDomain .. "/api/expand/new-ver?" .. encryptStr
        local ok, response = pcall(http, testUrl)
        if not ok or not response then
            gg.alert("网络连接失败,请检查网络设置")
            return false
        end
        local responseContent = tostring(response.content)
        if responseContent == "" then
            gg.alert("服务器无响应,请稍后重试")
            return false
        end
        local decryptStr = rc4_decrypt(encryptKey, responseContent)
        if decryptStr == "" then
            gg.alert("签名验证失败,请检查加密配置")
            return false
        end
        local success, jsonRes = pcall(json.decode, decryptStr)
        if not success or not jsonRes then
            local errorInfo = "服务器链接失败"
            if decryptStr and decryptStr ~= "" then
                if decryptStr:find("{") and decryptStr:find("}") then
                    errorInfo = errorInfo .. "\n请检查后台配置是否正确配\n将接口管理,接口安全配置修改为\nRC4对称加密,Base64编码"
                else
                    errorInfo = errorInfo .. "\n服务器正在维护\n请稍后进行重试,或者联系管理员" 
                end
            end
            gg.alert(errorInfo)
            return false
        end
        if jsonRes.code and jsonRes.msg then
            gg.alert("签名计算有误\n请检查后台配置\n将接口管理,接口安全改为\n签名方式:SHA256\n签名计算规则:方法二\n时间戳验证:30000")
        else
            gg.alert("服务器响应异常")
        end
        return false
    end
    return true
end

local function enhancedMultiDomainRequest(apiPath, encryptStr)
    if not isDomainInitialized then
        if not switchToAvailableDomain() then
            return nil
        end
    end
    local fullUrl = currentDomain .. apiPath .. "?" .. encryptStr
    local ok, response = pcall(http, fullUrl)
    if not ok or not response then
        return nil
    end
    local responseContent = tostring(response.content)
    if responseContent == "" then
        return nil
    end
    local decryptStr = rc4_decrypt(encryptKey, responseContent)
    if not decryptStr or decryptStr == "" then
        return nil
    end
    local success, jsonRes = pcall(json.decode, decryptStr)
    if not success then
        return nil
    end
    if not validateResponseTimestamp(jsonRes) then
        return nil
    end
    return jsonRes
end

-- 获取应用状态函数
local function getAppStatus()
    if not enhancedDomainCheck() then
        return nil
    end
    
    local paramsMap = {
        safeCode = getRandomString(),
        timestamp = os.time() * 1000
    }
    
    local encryptStr = goEncrypt(paramsMap)
    local jsonRes = enhancedMultiDomainRequest("/api/expand/app-status", encryptStr)
    
    return jsonRes
end

-- 正确判断应用模式
local function isFreeMode()
    local appStatus = getAppStatus()
    
    if appStatus and appStatus.code == 1 then
        -- 免费模式
        if appStatus.msg and (appStatus.msg:find("免费模式") or appStatus.msg:find("免费")) then
            return true
        end
        
        -- 检查data字段中的模式标识
        if appStatus.data then
            if type(appStatus.data) == "table" then
                for _, item in ipairs(appStatus.data) do
                    if item.values and tostring(item.values):find("免费") then
                        return true
                    end
                    if item.mark and tostring(item.mark):find("免费") then
                        return true
                    end
                end
            elseif type(appStatus.data) == "string" and appStatus.data:find("免费") then
                return true
            end
        end
    end
    
    return false
end

-- 获取单码信息接口
local function getCardInfo(card)
    if not enhancedDomainCheck() then
        return nil
    end
    
    local paramsMap = {
        card = card,
        safeCode = getRandomString(),
        timestamp = os.time() * 1000
    }
    
    local encryptStr = goEncrypt(paramsMap)
    local jsonRes = enhancedMultiDomainRequest("/api/single/info", encryptStr)
    return jsonRes
end

-- 解绑逻辑:根据后台配置处理设备验证
local function unbind(card)
    if not card or card == "" then
        gg.alert("请输入卡密进行解绑")
        return false
    end
    
    -- 取卡密信息,确认绑定状态
    local cardInfo = getCardInfo(card)
    if not cardInfo or cardInfo.code ~= 1 then
        gg.alert("获取卡密信息失败,无法进行解绑操作")
        return false
    end
    
    -- 检查卡密是否已绑定设备
    local boundMac = cardInfo.data and cardInfo.data.mac or ""
    if not boundMac or boundMac == "" then
        gg.alert("该卡密未绑定任何设备,无需解绑")
        return false
    end
    
    local currentMac = getMac()
    if not currentMac then
        currentMac = generateAndroidDeviceMac()
        saveMac(currentMac)
    end
    
    -- 处理解绑逻辑
    local paramsMap = {
        safeCode = getRandomString(),
        card = card,
        newMac = "", 
        timestamp = os.time() * 1000
    }
    
    -- 判断是否需要验证原设备:采用智能处理:先尝试不传originalMac,如果失败再尝试传originalMac
    
    local function tryUnbind(withOriginalMac, originalMacValue)
        local tempParams = {}
        for k, v in pairs(paramsMap) do
            tempParams[k] = v
        end
        
        if withOriginalMac and originalMacValue and originalMacValue ~= "" then
            tempParams.originalMac = originalMacValue
        end
        
        local encryptStr = goEncrypt(tempParams)
        local jsonRes = enhancedMultiDomainRequest("/api/single/unbind", encryptStr)
        return jsonRes
    end
    
    -- 不传originalMac(假设后台允许其他设备解绑)
    local jsonRes = tryUnbind(false, nil)
    
    -- 如果返回特定错误码,说明需要验证原设备
    if jsonRes and jsonRes.code == -10010 then
        -- 检查当前设备是否是绑定的设备
        if currentMac ~= boundMac then
            local choice = gg.alert("只能在绑定的设备上解绑!", "确定")
            return false
        end
        
        -- 传入originalMac(验证原设备)
        jsonRes = tryUnbind(true, boundMac)
    end
    
    -- 处理解绑结果
    if jsonRes and jsonRes.code == 1 then
        if jsonRes.msg ~= "应用当前为免费模式" then
            gg.alert(jsonRes.msg .. "\n您可以在其他设备进行重新登录。")
            clearAllConfig()  -- 清除本地配置
            return true
        else
            gg.alert("当前应用为免费模式无需解绑")
        end
    elseif jsonRes then
        local errorMsg = "解绑失败:\n" .. jsonRes.msg
        if jsonRes.code == -10009 then
            errorMsg = errorMsg .. "\n可能原因:该应用不允许解绑操作"
        elseif jsonRes.code == -10010 then
            errorMsg = errorMsg .. "\n可能原因:只能在原设备解绑"
        end
        gg.alert(errorMsg)
    else
        gg.alert("解绑失败:网络请求异常")
    end
    return false
end

-- 优化后的登录逻辑 
local function login(card, isUserCheckedAutoLogin)
    -- 收费模式
    if not card or card == "" then
        saveAutoLogin(false, false, true)
        return 0, "卡密不能为空"
    end
    
    local currentMac = getMac()
    if not currentMac then
        currentMac = generateAndroidDeviceMac()
        saveMac(currentMac)
    end
    
    local paramsMap = {
        card = card,
        safeCode = getRandomString(),
        mac = currentMac,
        timestamp = os.time() * 1000
    }
    local encryptStr = goEncrypt(paramsMap)
    local jsonRes = enhancedMultiDomainRequest("/api/single/login", encryptStr)
    
    if jsonRes and jsonRes.code == 1 then
        saveCard(card)
        local popupContent = ""
        local callback = nil
        
        if jsonRes.data and jsonRes.data.endTime then
            popupContent = string.format("登录成功!\n到期时间为:%s", jsonRes.data.endTime)
        else
            popupContent = "登录成功!"
        end
        
        if isUserCheckedAutoLogin then
            callback = gg.alert(popupContent, "确定", "取消自动登录")
        else
            callback = gg.alert(popupContent, "确定")
        end
        
        local finalEnable = false
        local finalChecked = false
        local finalRejected = false
        
        if isUserCheckedAutoLogin then
            if callback ~= nil and callback == 2 then
                finalEnable = false
                finalChecked = true
                finalRejected = true
            else
                finalEnable = true
                finalChecked = true
                finalRejected = false
            end
        else
            finalEnable = false
            finalChecked = false
            finalRejected = true
        end
        
        saveAutoLogin(finalEnable, finalChecked, finalRejected)
        
        return 1, "登录成功"
    elseif jsonRes then
        saveAutoLogin(false, false, true)
        return 0, "登录失败:" .. jsonRes.msg
    else
        saveAutoLogin(false, false, true)
        return 0, "登录失败:网络请求异常"
    end
end

-- 改进的主流程控制函数
local function main()
    if not enhancedDomainCheck() then
        os.exit(0)
    end
    
    -- 先检测应用模式
    local freeMode = isFreeMode()
    
    if freeMode then

        gg.alert("当前为免费模式")

        return 1, "免费模式"
    end
    
    local input = {}
    local savedCard = getCard()
    local isAutoLoginEnable, isAutoLoginChecked, isUserRejected = getAutoLoginStatus()
    
    if savedCard and savedCard ~= "" then
        input[1] = savedCard
    end
    
    if isAutoLoginEnable and isAutoLoginChecked and not isUserRejected and savedCard ~= "" then
        gg.alert("正在自动登录...")
        local loginResult, loginMsg = login(savedCard, true)
        if loginResult == 1 then
            return 1, "自动登录成功"
        else
            gg.alert("自动登录失败:" .. loginMsg .. "\n请手动登录")
            saveAutoLogin(false, false, true)
        end
    end
    
    -- 循环输入,直到登录成功或用户取消
    while true do
        local defaultAutoLogin = isAutoLoginEnable and not isUserRejected
        if shopAddr == nil or shopAddr == "" then
            input = gg.prompt({ "请输入卡密", "自动登录", "解绑卡密" }, 
                { input[1] or "", defaultAutoLogin, false },
                { "text", "checkbox", "checkbox" })
        else
            input = gg.prompt({ "请输入卡密", "自动登录", "解绑卡密", "复制购卡地址" }, 
                { input[1] or "", defaultAutoLogin, false, false },
                { "text", "checkbox", "checkbox", "checkbox" })
        end
        
        if input == nil then
   
            return 0, "用户取消登录"
        end
        
        if input[2] and input[3] then
            gg.alert("不可同时选中\"自动登录\"和\"解绑卡密\"")
            -- 重新输入
            goto continue
        end
        
        if input[3] then
            local result = unbind(input[1])
            if result then
                -- 解绑后清空输入框
                input[1] = ""
            end
            -- 解绑后继续登录流程
            goto continue
        end
        
        if input[4] then
            gg.alert("已复制购卡地址")
            gg.copyText(shopAddr)
            -- 复制地址后继续登录流程
            goto continue
        end
        
        local loginResult, loginMsg = login(input[1], input[2])
        if loginResult == 1 then
            return 1, loginMsg
        else
            gg.alert(loginMsg .. "\n请重新输入卡密")
            -- 登录失败,继续循环
        end
        
        ::continue::
    end
end

-- 公告获取
local function getNotice()
    if not enhancedDomainCheck() then
        return
    end
    local paramsMap = {
        variableId = noticeId,
        safeCode = getRandomString(),
        timestamp = os.time() * 1000
    }
    local encryptStr = goEncrypt(paramsMap)
    local jsonRes = enhancedMultiDomainRequest("/api/expand/variable", encryptStr)
    if jsonRes and jsonRes.code == 1 then
        if jsonRes.data and jsonRes.data.content then
            gg.alert("系统公告:\n" .. jsonRes.data.content)
        end
    end
end

-- 店铺地址获取
local function getShop()
    if not enhancedDomainCheck() then
        return
    end
    local paramsMap = {
        safeCode = getRandomString(),
        variableId = shopId,
        timestamp = os.time() * 1000
    }
    local encryptStr = goEncrypt(paramsMap)
    local jsonRes = enhancedMultiDomainRequest("/api/expand/variable", encryptStr)
    if jsonRes and jsonRes.code == 1 then
        if jsonRes.data and jsonRes.data.content then
            shopAddr = jsonRes.data.content
        end
    end
end

-- 版本检查
local function checkVersion()
    if not enhancedDomainCheck() then
        return
    end
    local paramsMap = { 
        safeCode = getRandomString(),
        timestamp = os.time() * 1000
    }
    local encryptStr = goEncrypt(paramsMap)
    local jsonRes = enhancedMultiDomainRequest("/api/expand/new-ver", encryptStr)
    if jsonRes and jsonRes.code == 1 then
        if jsonRes.data and jsonRes.data.num and jsonRes.data.num ~= version then
            if jsonRes.data.forced == 0 then
                local result = gg.alert("最新版:" .. (jsonRes.data.name or "") .. "\n" .. (jsonRes.data.content or ""), "前往更新", "晚些再说")
                if result == 1 then
                    gg.copyText(jsonRes.data.addr or "")
                    gg.alert("已为您复制更新地址,请打开浏览器访问")
                end
            else
                while true do
                    local result = gg.alert("强制更新 最新版:" .. (jsonRes.data.name or "") .. "\n" .. (jsonRes.data.content or ""), "前往更新", "退出脚本")
                    if result == 1 then
                        gg.copyText(jsonRes.data.addr or "")
                        gg.alert("已为您复制更新下载地址,请打开浏览器访问\n更新完成后重新启动脚本")
                        os.exit(0)
                    elseif result == 2 then
                        os.exit(0)
                    end
                end
            end
        end
    end
end

-- JSON编解码库(完整代码)
local encode
local escape_char_map = {
    ["\\"] = "\\",
    ["\""] = "\"",
    ["\b"] = "b",
    ["\f"] = "f",
    ["\n"] = "n",
    ["\r"] = "r",
    ["\t"] = "t",
}
local escape_char_map_inv = { ["/"] = "/" }
for k, v in pairs(escape_char_map) do
    escape_char_map_inv[v] = k
end
local function escape_char(c)
    return "\\" .. (escape_char_map[c] or string.format("u%04x", c:byte()))
end
local function encode_nil(val)
    return "null"
end
local function encode_table(val, stack)
    local res = {}
    stack = stack or {}
    if stack[val] then error("circular reference") end
    stack[val] = true
    if rawget(val, 1) ~= nil or next(val) == nil then
        local n = 0
        for k in pairs(val) do
            if type(k) ~= "number" then
                error("invalid table: mixed or invalid key types")
            end
            n = n + 1
        end
        if n ~= #val then
            error("invalid table: sparse array")
        end
        for i, v in ipairs(val) do
            table.insert(res, encode(v, stack))
        end
        stack[val] = nil
        return "[" .. table.concat(res, ",") .. "]"
    else
        for k, v in pairs(val) do
            if type(k) ~= "string" then
                error("invalid table: mixed or invalid key types")
            end
            table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
        end
        stack[val] = nil
        return "{" .. table.concat(res, ",") .. "}"
    end
end
local function encode_string(val)
    return '"' .. val:gsub('[%z\1-\31\\"]', escape_char) .. '"'
end
local function encode_number(val)
    if val ~= val or val <= -math.huge or val >= math.huge then
        error("unexpected number value '" .. tostring(val) .. "'")
    end
    return string.format("%.14g", val)
end
local type_func_map = {
    ["nil"] = encode_nil,
    ["table"] = encode_table,
    ["string"] = encode_string,
    ["number"] = encode_number,
    ["boolean"] = tostring,
}
encode = function(val, stack)
    local t = type(val)
    local f = type_func_map[t]
    if f then
        return f(val, stack)
    end
    error("unexpected type '" .. t .. "'")
end
function json.encode(val)
    return (encode(val))
end
local parse
local function create_set(...)
    local res = {}
    for i = 1, select("#", ...) do
        res[select(i, ...)] = true
    end
    return res
end
local space_chars  = create_set(" ", "\t", "\r", "\n")
local delim_chars  = create_set(" ", "\t", "\r", "\n", "]", "}", ",")
local escape_chars = create_set("\\", "/", '"', "b", "f", "n", "r", "t", "u")
local literals     = create_set("true", "false", "null")
local literal_map  = {
    ["true"] = true,
    ["false"] = false,
    ["null"] = nil,
}
local function next_char(str, idx, set, negate)
    for i = idx, #str do
        if set[str:sub(i, i)] ~= negate then
            return i
        end
    end
    return #str + 1
end
local function decode_error(str, idx, msg)
    local line_count = 1
    local col_count = 1
    for i = 1, idx - 1 do
        col_count = col_count + 1
        if str:sub(i, i) == "\n" then
            line_count = line_count + 1
            col_count = 1
        end
    end
    error(string.format("%s at line %d col %d", msg, line_count, col_count))
end
local function codepoint_to_utf8(n)
    local f = math.floor
    if n <= 127 then
        return string.char(n)
    elseif n <= 2047 then
        return string.char(f(n / 64) + 192, n % 64 + 128)
    elseif n <= 65535 then
        return string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128)
    elseif n <= 1114111 then
        return string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128,
            f(n % 4096 / 64) + 128, n % 64 + 128)
    end
    error(string.format("invalid unicode codepoint '%x'", n))
end
local function parse_unicode_escape(s)
    local n1 = tonumber(s:sub(1, 4), 16)
    local n2 = tonumber(s:sub(7, 10), 16)
    if n2 then
        return codepoint_to_utf8((n1 - 55296) * 1024 + (n2 - 56320) + 65536)
    else
        return codepoint_to_utf8(n1)
    end
end
local function parse_string(str, i)
    local res = ""
    local j = i + 1
    local k = j
    while j <= #str do
        local x = str:byte(j)
        if x < 32 then
            decode_error(str, j, "control character in string")
        elseif x == 92 then
            res = res .. str:sub(k, j - 1)
            j = j + 1
            local c = str:sub(j, j)
            if c == "u" then
                local hex = str:match("^[dD][89aAbB]%x%x\\u%x%x%x%x", j + 1)
                    or str:match("^%x%x%x%x", j + 1)
                    or decode_error(str, j - 1, "invalid unicode escape in string")
                res = res .. parse_unicode_escape(hex)
                j = j + #hex
            else
                if not escape_chars[c] then
                    decode_error(str, j - 1, "invalid escape char '" .. c .. "' in string")
                end
                res = res .. escape_char_map_inv[c]
            end
            k = j + 1
        elseif x == 34 then
            res = res .. str:sub(k, j - 1)
            return res, j + 1
        end
        j = j + 1
    end
    decode_error(str, i, "expected closing quote for string")
end
local function parse_number(str, i)
    local x = next_char(str, i, delim_chars)
    local s = str:sub(i, x - 1)
    local n = tonumber(s)
    if not n then
        decode_error(str, i, "invalid number '" .. s .. "'")
    end
    return n, x
end
local function parse_literal(str, i)
    local x = next_char(str, i, delim_chars)
    local word = str:sub(i, x - 1)
    if not literals[word] then
        decode_error(str, i, "invalid literal '" .. word .. "'")
    end
    return literal_map[word], x
end
local function parse_array(str, i)
    local res = {}
    local n = 1
    i = i + 1
    while 1 do
        local x
        i = next_char(str, i, space_chars, true)
        if str:sub(i, i) == "]" then
            i = i + 1
            break
        end
        x, i = parse(str, i)
        res[n] = x
        n = n + 1
        i = next_char(str, i, space_chars, true)
        local chr = str:sub(i, i)
        i = i + 1
        if chr == "]" then break end
        if chr ~= "," then decode_error(str, i, "expected ']'或','") end
    end
    return res, i
end
local function parse_object(str, i)
    local res = {}
    i = i + 1
    while 1 do
        local key, val
        i = next_char(str, i, space_chars, true)
        if str:sub(i, i) == "}" then
            i = i + 1
            break
        end
        if str:sub(i, i) ~= '"' then
            decode_error(str, i, "expected string for key")
        end
        key, i = parse(str, i)
        i = next_char(str, i, space_chars, true)
        if str:sub(i, i) ~= ":" then
            decode_error(str, i, "expected ':' after key")
        end
        i = next_char(str, i + 1, space_chars, true)
        val, i = parse(str, i)
        res[key] = val
        i = next_char(str, i, space_chars, true)
        local chr = str:sub(i, i)
        i = i + 1
        if chr == "}" then break end
        if chr ~= "," then decode_error(str, i, "expected '}'或','") end
    end
    return res, i
end
local char_func_map = {
    ['"'] = parse_string,
    ["0"] = parse_number,
    ["1"] = parse_number,
    ["2"] = parse_number,
    ["3"] = parse_number,
    ["4"] = parse_number,
    ["5"] = parse_number,
    ["6"] = parse_number,
    ["7"] = parse_number,
    ["8"] = parse_number,
    ["9"] = parse_number,
    ["-"] = parse_number,
    ["t"] = parse_literal,
    ["f"] = parse_literal,
    ["n"] = parse_literal,
    ["["] = parse_array,
    ["{"] = parse_object,
}
parse = function(str, idx)
    local chr = str:sub(idx, idx)
    local f = char_func_map[chr]
    if f then
        return f(str, idx)
    end
    decode_error(str, idx, "unexpected character '" .. chr .. "'")
end
function json.decode(str)
    if type(str) ~= "string" then
        error("expected argument of type string, got " .. type(str))
    end
    local res, idx = parse(str, next_char(str, 1, space_chars, true))
    idx = next_char(str, idx, space_chars, true)
    if idx <= #str then
        decode_error(str, idx, "trailing garbage")
    end
    return res
end

-- 主执行流程
if enhancedDomainCheck() then
    checkVersion()
    getNotice()
    getShop()
    
    local authResult, authMsg = main()
    
    if authResult == 1 then

        local success, err = pcall(developerMainScript)
        if not success then
            gg.alert("脚本执行出错:" .. tostring(err))
        end
    else

        if authMsg and authMsg ~= "用户取消登录" then
            gg.alert(authMsg .. "\n脚本停止运行")
        end
        os.exit(0)
    end
else
    os.exit(0)
end

--[[Welcome to Dluae]]

-- ==================== 悬浮窗系统(稳定版) ====================
import "android.app.*"
import "android.os.*"
import "android.widget.*"
import "android.view.*"
import "android.content.*"
import "android.graphics.drawable.*"
import "android.graphics.PixelFormat"
import "android.animation.ObjectAnimator"
import "android.view.animation.DecelerateInterpolator"
import "android.graphics.Typeface"
import "android.graphics.drawable.GradientDrawable"

TEXT_open = 0xFFFF57B0
TEXT_close = 0xFFFFFFFF
BG_COLOR = 0xFF3B3C40
BORDER_close = 0xFF2B2D2F
BORDER_width = 8
CORNER_RADIUS = 15

context = activity
windowManager = context.getSystemService("window")
allSwitches = {}

-- ==================== 新增:模式切换全局变量 ====================
PC_MODE_ENABLED = false    -- 电脑模式(特征码)
MOBILE_MODE_ENABLED = false -- 手机模式(指针)

-- ==================== 新增:泳池体力修改 ====================
local POOL_ENERGY_ADDRS = nil   -- 存储修改过的地址

function createRoundRectBg(fillColor, borderColor, borderWidth, cornerRadius)
    local shape = GradientDrawable()
    shape.setShape(GradientDrawable.RECTANGLE)
    shape.setColor(fillColor)
    shape.setCornerRadius(cornerRadius)
    shape.setStroke(borderWidth, borderColor)
    return shape
end

function clickAnimation(view)
    local anim1 = ObjectAnimator.ofFloat(view, "scaleX", 1.2, 0.8, 1.1, 0.9, 1.0)
    local anim2 = ObjectAnimator.ofFloat(view, "scaleY", 1.2, 0.8, 1.1, 0.9, 1.0)
    anim1.setDuration(500)
    anim2.setDuration(500)
    anim1.start()
    anim2.start()
end

function getLayoutParams()
    local LayoutParams = WindowManager.LayoutParams
    local layoutParams = luajava.new(LayoutParams)
    if (Build.VERSION.SDK_INT >= 26) then
        layoutParams.type = LayoutParams.TYPE_APPLICATION_OVERLAY
    else
        layoutParams.type = LayoutParams.TYPE_PHONE
    end
    layoutParams.format = PixelFormat.RGBA_8888
    layoutParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE
    layoutParams.gravity = Gravity.CENTER
    layoutParams.width = LayoutParams.WRAP_CONTENT
    layoutParams.height = LayoutParams.WRAP_CONTENT
    return layoutParams
end

function showFloatingNotify(title, msg)
    luajava.runOnUiThread(function()
        if Inform and Inform.showSuccessNotification_Simplicity then
            Inform.showSuccessNotification_Simplicity(nil, title, msg, 2000)
        else
            toast.black(title .. ":" .. msg, 1)
        end
    end)
end

function createSwitch(name, onFunction, offFunction)
    local switch = {}
    local isActive = false
    local layoutParams = getLayoutParams()
    layoutParams.x = math.random(200, 500)
    layoutParams.y = math.random(30, 200)
    local switchLayout = {
        LinearLayout;
        layout_height="fill";
        layout_width="fill";
        {
            TextView;
            layout_width="150";
            layout_height="70";
            id="switch_" .. name;
            text=name;
            textColor=TEXT_close;
            textSize="13";
            gravity="center";
            background=createRoundRectBg(BG_COLOR, BORDER_close, BORDER_width, CORNER_RADIUS);
            padding="8";
            typeface=Typeface.DEFAULT_BOLD;
        };
    }
    local switchView = loadlayout(switchLayout)
    local textView = switchView.getChildAt(0)
    local initialX, initialY = 0, 0
    local initialTouchX, initialTouchY = 0, 0

    switchView.setOnTouchListener(View.OnTouchListener{
        onTouch=function(v, event)
            local action = event.getAction()
            if action == MotionEvent.ACTION_DOWN then
                initialX = layoutParams.x
                initialY = layoutParams.y
                initialTouchX = event.getRawX()
                initialTouchY = event.getRawY()
                return true
            elseif action == MotionEvent.ACTION_MOVE then
                local deltaX = event.getRawX() - initialTouchX
                local deltaY = event.getRawY() - initialTouchY
                layoutParams.x = initialX + deltaX
                layoutParams.y = initialY + deltaY
                windowManager.updateViewLayout(switchView, layoutParams)
                return true
            elseif action == MotionEvent.ACTION_UP then
                local moveDistance = math.sqrt(
                    math.pow(event.getRawX() - initialTouchX, 2) +
                    math.pow(event.getRawY() - initialTouchY, 2)
                )
                if moveDistance < 50 then
                    if isActive then
                        textView.setTextColor(TEXT_close)
                        textView.setBackground(createRoundRectBg(BG_COLOR, BORDER_close, BORDER_width, CORNER_RADIUS))
                        isActive = false
                        if offFunction then
                            thread(function()
                                local ok, err = pcall(offFunction)
                                if not ok then
                                    showFloatingNotify(name, "关闭出错: " .. tostring(err))
                                else
                                    showFloatingNotify(name, "已关闭")
                                end
                            end)
                        else
                            showFloatingNotify(name, "已关闭")
                        end
                    else
                        textView.setTextColor(TEXT_open)
                        textView.setBackground(createRoundRectBg(BG_COLOR, TEXT_open, BORDER_width, CORNER_RADIUS))
                        isActive = true
                        if onFunction then
                            thread(function()
                                local ok, err = pcall(onFunction)
                                if not ok then
                                    showFloatingNotify(name, "开启出错: " .. tostring(err))
                                else
                                    showFloatingNotify(name, "已开启")
                                end
                            end)
                        else
                            showFloatingNotify(name, "已开启")
                        end
                    end
                    clickAnimation(textView)
                end
                return true
            end
            return false
        end
    })

    function switch.show()
        if not switchView:isAttachedToWindow() then
            windowManager.addView(switchView, layoutParams)
            clickAnimation(textView)
        end
    end
    function switch.hide()
        if switchView:isAttachedToWindow() then
            windowManager.removeView(switchView)
        end
    end
    function switch.setState(state)
        if state then
            textView.setTextColor(TEXT_open)
            textView.setBackground(createRoundRectBg(BG_COLOR, TEXT_open, BORDER_width, CORNER_RADIUS))
            isActive = true
        else
            textView.setTextColor(TEXT_close)
            textView.setBackground(createRoundRectBg(BG_COLOR, BORDER_close, BORDER_width, CORNER_RADIUS))
            isActive = false
        end
    end
    function switch.getState() return isActive end
    allSwitches[name] = switch
    return switch
end

-- 悬浮窗绑定功能(原有)
function createLeftCrystalSwitch()
    return createSwitch("秒左", function() Zuilong_LeftKill_On() end, function() end)
end
function createRightCrystalSwitch()
    return createSwitch("秒右", function() Zuilong_RightKill_On() end, function() end)
end
function createPerspectiveSwitch()
    return createSwitch("透视", function() ModelPenetration_On() end, function() ModelPenetration_Off() end)
end
function createGatherSwitch()
    return createSwitch("聚怪", function() Zuilong_Gather_On() end, function() Zuilong_Gather_Off() end)
end
function createStepSwitch()
    return createSwitch("穿图", function() StepByStep_Enable() end, function() StepByStep_Disable() end)
end

-- ==================== 新增:电脑模式(特征码)开关 ====================
function createPCSwitch()
    return createSwitch(
        "电脑模式",
        function()
            PC_MODE_ENABLED = true
            showCloudNotify("模式切换", "电脑模式(特征码)已开启", true)
        end,
        function()
            PC_MODE_ENABLED = false
            showCloudNotify("模式切换", "电脑模式(特征码)已关闭", true)
        end
    )
end

-- ==================== 新增:手机模式(指针)开关 ====================
function createMobileSwitch()
    return createSwitch(
        "手机模式",
        function()
            MOBILE_MODE_ENABLED = true
            showCloudNotify("模式切换", "手机模式(指针)已开启", true)
        end,
        function()
            MOBILE_MODE_ENABLED = false
            showCloudNotify("模式切换", "手机模式(指针)已关闭", true)
        end
    )
end

local leftSwitch, rightSwitch, perspectiveSwitch, gatherSwitch, stepSwitch, pcSwitch, mobileSwitch = nil, nil, nil, nil, nil, nil, nil

function initAllSwitches()
    leftSwitch = createLeftCrystalSwitch()
    rightSwitch = createRightCrystalSwitch()
    perspectiveSwitch = createPerspectiveSwitch()
    gatherSwitch = createGatherSwitch()
    stepSwitch = createStepSwitch()
    pcSwitch = createPCSwitch()
    mobileSwitch = createMobileSwitch()
end

function showSwitch(switchName)
    luajava.runOnUiThread(function()
        local s = allSwitches[switchName]
        if s then s.show() end
    end)
end
function hideSwitch(switchName)
    luajava.runOnUiThread(function()
        local s = allSwitches[switchName]
        if s then s.hide() end
    end)
end
function hideAllSwitches()
    luajava.runOnUiThread(function()
        for _, s in pairs(allSwitches) do if s and s.hide then s.hide() end end
    end)
end

function allshowSwitches()
    luajava.runOnUiThread(function()
        for _, s in pairs(allSwitches) do if s and s.show then s.show() end end
    end)
end

-- ==================== 云通知初始化 ====================
loadYunLuaGroup("5C3C4E3813681C4C204C35346F1B4C2F7EFF612D2B22176FF346535E1C0B1E493339036EE15318")
function init() stab = _ENV["分页"]; ttitle = _ENV["标题"]; xfcpic = _ENV["悬浮窗图标"] end

local Cloud_Note_Url = 'https://sharechain.qq.com/bb8dfff6a3346b24f73fe7c626ae6ec7'
local function getCloudContent()
    local response = gg.makeRequest(Cloud_Note_Url)
    if not response or not response.content then return nil,nil,nil,"网络错误" end
    local note_content = response.content:match('"html_content":"(.-)",')
    if not note_content then return nil,nil,nil,"QQ收藏格式错误" end
    note_content = note_content:gsub("\\u003C","<"):gsub("\\u003E",">"):gsub("\\u003Cbr%s*/?%s*\\u003E","\n"):gsub("<div>","\n"):gsub("</div>",""):gsub("&nbsp;"," ")
    local announcement = note_content:match("【公告】(.-)【公告】")
    local notification = note_content:match("【通知】(.-)【通知】")
    local qqGroupKey = note_content:match("【joinQQGroup】(.-)【joinQQGroup】")
    if announcement then announcement = announcement:gsub("<.->",""):gsub("^%s+",""):gsub("%s+$","") end
    if notification then notification = notification:gsub("<.->",""):gsub("^%s+",""):gsub("%s+$","") end
    if qqGroupKey then qqGroupKey = qqGroupKey:gsub("<.->",""):gsub("%s+","") end
    return announcement, notification, qqGroupKey
end
local announcement, notification, qqGroupKey = getCloudContent()

elgg.import("toast")
elgg.import("AlGui")
import "android.graphics.drawable.GradientDrawable"
import "android.widget.LinearLayout"
import "android.view.LayoutInflater"
import "android.widget.TextView"
import "android.widget.Button"
import "java.util.Locale"
import "android.view.Gravity"
import "android.graphics.Typeface"
import "irene.window.algui.AlGuiData"
import "android.view.animation.Animation"
import "irene.window.algui.AlGuiDialogBox"
import "irene.window.algui.AlGuiSoundEffect"
import "irene.window.algui.AlGuiWindowView"
import "irene.window.algui.Tools.VariousTools"

local neonColors = { [0]=0xFFff00cc, [1]=0xFFffcc00, [2]=0xFF00ffcc, [3]=0xFFff0066 }
luajava.runOnUiThread(function()
    if AlGui.algui then AlGui.algui.clearBall() AlGui.algui.clearMenu() AlGuiWindowView.clearAllViews(context) gui = AlGui.newGUI(context)
    else gui = AlGui.GUI(context) end
    if AlGuiBubbleNotification.bn then Inform = AlGuiBubbleNotification.newInform(context)
    else Inform = AlGuiBubbleNotification.Inform(context) end
    AlGuiWindowView.showNeonLightText(context, "YZ科技", neonColors, 15, nil, Gravity.START|Gravity.BOTTOM, 50, 100)
end)

function showCloudNotify(title, msg, isSuccess)
    luajava.runOnUiThread(function()
        if isSuccess then
            Inform.showSuccessNotification_Simplicity(nil, title, msg, 3000)
        else
            Inform.showMessageNotification_Simplicity(nil, title, msg, 3000)
        end
    end)
end

-- ==================== v2.2 视奸模式(单次执行,开关式) ====================
local SHIJIAN_BUSY = false

-- 视奸模式 - 切磋(只改当前值为1的地址)
function doQieCuo()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber(1135494768, gg.TYPE_DWORD)
    local cnt = gg.getResultsCount()
    if cnt and cnt > 0 then
        local results = gg.getResults(math.min(cnt, 500))
        local editList = {}
        for _, v in ipairs(results) do
            if v.address and v.address ~= 0 then
                local targetAddr = v.address + 408
                local curVal = gg.getValues({{address = targetAddr, flags = gg.TYPE_DWORD}})
                if curVal and curVal[1] and curVal[1].value == 1 then
                    table.insert(editList, {address = targetAddr, flags = gg.TYPE_DWORD, value = 257})
                end
            end
        end
        if #editList > 0 then
            gg.setValues(editList)
        end
    end
    gg.clearResults()
end

-- 视奸模式 - 状态(只改当前值为1的地址)
function doZhuangTai()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber(1223231026, gg.TYPE_DWORD)
    local cnt = gg.getResultsCount()
    if cnt and cnt > 0 then
        local results = gg.getResults(math.min(cnt, 500))
        local editList = {}
        for _, v in ipairs(results) do
            if v.address and v.address ~= 0 then
                local targetAddr = v.address - 312
                local curVal = gg.getValues({{address = targetAddr, flags = gg.TYPE_DWORD}})
                if curVal and curVal[1] and curVal[1].value == 1 then
                    table.insert(editList, {address = targetAddr, flags = gg.TYPE_DWORD, value = 257})
                end
            end
        end
        if #editList > 0 then
            gg.setValues(editList)
        end
    end
    gg.clearResults()
end

-- 视奸模式 - 私聊(只改当前值为1的地址)
function doSiLiao()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber(-1670169661, gg.TYPE_DWORD)
    local cnt = gg.getResultsCount()
    if cnt and cnt > 0 then
        local results = gg.getResults(math.min(cnt, 500))
        local editList = {}
        for _, v in ipairs(results) do
            if v.address and v.address ~= 0 then
                local targetAddr = v.address + 0x34
                local curVal = gg.getValues({{address = targetAddr, flags = gg.TYPE_DWORD}})
                if curVal and curVal[1] and curVal[1].value == 1 then
                    table.insert(editList, {address = targetAddr, flags = gg.TYPE_DWORD, value = 257})
                end
            end
        end
        if #editList > 0 then
            gg.setValues(editList)
        end
    end
    gg.clearResults()
end

function Shijian_On()
    if SHIJIAN_BUSY then
        showCloudNotify("视奸模式", "正在执行中,请稍后...", false)
        return
    end
    SHIJIAN_BUSY = true
    showCloudNotify("视奸模式", "正在执行...", false)
    
    doQieCuo()
    doZhuangTai()
    doSiLiao()
    
    showCloudNotify("视奸模式", "执行完成", true)
    SHIJIAN_BUSY = false
end

function Shijian_Off()
    showCloudNotify("视奸模式", "无需关闭,再次开启可重新执行", false)
end

-- ============ 通用变量声明 ============
local LAST_MODIFY_DATA = nil
local LAST_SEARCH_VALUE = nil
local LAST_MODIFY_COUNT = 0
local sj = {}
local LOOP_INTERVAL = 4
local IS_LOOP_ACTIVE = false
local TERRAIN_LOOP_ACTIVE = false
local TERRAIN_LOOP_INTERVAL = 4
local GLOBAL_SPEED_DATA = nil
local GLOBAL_SPEED_MULTIPLIER = 3.0
local GAME_SPEED_ACTIVE = false
local GAME_SPEED_VALUE = 3.0
local GAME_SPEED_TIMER = nil
local zuilong_gather_data = nil
local step_active = false
local BUDDHA_LIGHT_DATA = nil
local BUDDHA_LIGHT_ACTIVE = false
local INFINITE_JUMP_ACTIVE = false
local INFINITE_JUMP_LIST = nil
local MONKEY_INVINCIBLE_KILL_DATA = nil
local WUKONG_STRONG_REPLACE_ACTIVE = false
local WUKONG_STRONG_REPLACE_VALUE = 8660
local WUKONG_STRONG_REPLACE_DATA = nil
local MONKEY_SKILL_DATA = nil
local FLAME_MOUNTAIN_DATA = nil
local FLAME_MOUNTAIN_ID = 1032
local MODEL_PENETRATION_DATA = nil
local ALL_NO_COOLDOWN_DATA = nil
local NO_MANA_LIST_ITEMS = nil
local ZUILONG_ROLE_INVINCIBLE_ACTIVE = false
local ZUILONG_ROLE_INVINCIBLE_DATA = nil
local MONSTER_FIX_ACTIVE = false
local MONSTER_FIX_INTERVAL = 0.1
local POOL_MODIFY_ADDRS = nil
local WHACK_A_MOLE_DATA = nil
local WIDE_SCREEN_DATA = nil
local SPEED_BUTTON_DATA = nil
_72Bian_Active = false
_72Bian_Data = {}
_72Bian_TargetID = 40
local EAT_ZONGZI_DATA = nil
local GM_DATA = nil
local WaiZhuan64_GM_DATA = nil
local SHUA_WENDIE_DATA = nil
local ALL_INVINCIBLE_DATA = nil
local leftRoleData = nil
local rightRoleData = nil
local leftRoleFeatureData = nil
local rightRoleFeatureData = nil
local SANSHENGCHUI_DATA = nil
ALL_SECOND_KILL_LOOP_ACTIVE = false
local MAI_DONGXI_ACTIVE = false
local MAI_DONGXI_DATA = nil

-- ==================== 外传64 GM 功能(开关式) ====================
function WaiZhuan64_GM_Enable()
    if WaiZhuan64_GM_DATA then
        return
    end
    gg.clearResults()
    search(101, 4, -2080896)
    if #sj == 0 then
        showCloudNotify("外传64 GM", "未找到特征值 101", false)
        gg.clearResults()
        return
    end
    py1(11, 4, -16)
    if #sj == 0 then
        showCloudNotify("外传64 GM", "筛选值 11 失败", false)
        gg.clearResults()
        return
    end
    py1(-425984, 4, 172)
    if #sj == 0 then
        showCloudNotify("外传64 GM", "筛选值 -425984 失败", false)
        gg.clearResults()
        return
    end

    local modifyList = {}
    local recordList = {}
    for _, v in ipairs(sj) do
        local targetAddr = v.address + 168
        local orig = gg.getValues({{address = targetAddr, flags = 4}})[1].value
        table.insert(recordList, {address = targetAddr, flags = 4, originalValue = orig})
        table.insert(modifyList, {address = targetAddr, flags = 4, value = 0})
    end

    if #modifyList == 0 then
        showCloudNotify("外传64 GM", "无有效修改项", false)
        gg.clearResults()
        return
    end

    gg.setValues(modifyList)
    WaiZhuan64_GM_DATA = recordList
    gg.clearResults()
end

function WaiZhuan64_GM_Disable()
    if not WaiZhuan64_GM_DATA then
        return
    end
    local restoreList = {}
    for _, item in ipairs(WaiZhuan64_GM_DATA) do
        table.insert(restoreList, {address = item.address, flags = item.flags, value = item.originalValue})
    end
    gg.setValues(restoreList)
    WaiZhuan64_GM_DATA = nil
end

function GM_On_Internal()
    gg.clearResults()
    search(101, 4, 4)
    if #sj == 0 then
        showCloudNotify("GM模式", "未找到特征值 101", false)
        return
    end

    py1(11, 4, -16)
    if #sj == 0 then
        showCloudNotify("GM模式", "筛选值 11 失败", false)
        return
    end

    py1(-425984, 4, 172)
    if #sj == 0 then
        showCloudNotify("GM模式", "筛选值 -425984 失败", false)
        return
    end

    local modifyList = {}
    local recordList = {}

    for _, v in ipairs(sj) do
        local targetAddr = v.address + 168
        local orig = gg.getValues({{address = targetAddr, flags = 4}})[1].value
        table.insert(recordList, {address = targetAddr, flags = 4, originalValue = orig})
        table.insert(modifyList, {address = targetAddr, flags = 4, value = 0})
    end

    if #modifyList == 0 then
        showCloudNotify("GM模式", "无有效修改项", false)
        return
    end

    gg.setValues(modifyList)
    GM_DATA = recordList
    gg.clearResults()
end

function GM_Off_Internal()
    if not GM_DATA then
        return
    end

    local restoreList = {}
    for _, item in ipairs(GM_DATA) do
        table.insert(restoreList, {address = item.address, flags = item.flags, value = item.originalValue})
    end
    gg.setValues(restoreList)

    GM_DATA = nil
end

function GM_On()
    if GM_DATA or WaiZhuan64_GM_DATA then
        showCloudNotify("GM模式", "已开启,无需重复操作", false)
        return
    end

    WaiZhuan64_GM_Enable()
    GM_On_Internal()

    if GM_DATA or WaiZhuan64_GM_DATA then
        showCloudNotify("GM模式", "已开启(外传64 + 原版)", true)
    else
        showCloudNotify("GM模式", "开启失败,请检查环境", false)
    end
end

function GM_Off()
    if not GM_DATA and not WaiZhuan64_GM_DATA then
        showCloudNotify("GM模式", "未开启,无需关闭", false)
        return
    end

    WaiZhuan64_GM_Disable()
    GM_Off_Internal()

    showCloudNotify("GM模式", "已关闭(已恢复两个GM)", true)
end

-- ==================== 卖道具功能(自定义输入,写值-1) ====================
function MaiDongXi_On()
    if MAI_DONGXI_ACTIVE then
        showCloudNotify("卖道具", "已开启,无需重复操作", false)
        return
    end
    
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.clearResults()
    
    -- 搜索特征值 -425984
    gg.searchNumber("-425984", gg.TYPE_DWORD)
    local results = gg.getResults(gg.getResultsCount())
    if results == nil or #results == 0 then
        showCloudNotify("卖道具", "未找到匹配结果", false)
        gg.clearResults()
        return
    end
    
    -- 批量读取偏移20和24的值
    local readList = {}
    for i, v in ipairs(results) do
        table.insert(readList, {address = v.address + 20, flags = gg.TYPE_DWORD})
        table.insert(readList, {address = v.address + 24, flags = gg.TYPE_DWORD})
    end
    
    local readValues = gg.getValues(readList)
    if not readValues then
        showCloudNotify("卖道具", "读取内存失败", false)
        gg.clearResults()
        return
    end
    
    -- 验证条件
    local validAddresses = {}
    for i = 1, #results do
        local idx20 = (i - 1) * 2 + 1
        local idx24 = (i - 1) * 2 + 2
        local val20 = readValues[idx20] and readValues[idx20].value
        local val24 = readValues[idx24] and readValues[idx24].value
        
        if val20 and val24 then
            if val20 >= 1 and val20 <= 30 and val24 == -491520 then
                table.insert(validAddresses, results[i].address)
            end
        end
    end
    
    gg.clearResults()
    
    if #validAddresses == 0 then
        showCloudNotify("卖道具", "未找到符合条件的地址", false)
        return
    end
    
    -- 弹出输入框让用户输入自定义数值
    local input = gg.prompt(
        { "请输入要修改的值(将自动写入 输入值-1):" },
        { [1] = "1" },
        { [1] = "number" }
    )
    if input == nil then
        showCloudNotify("卖道具", "已取消", false)
        return
    end
    
    local userInput = tonumber(input[1])
    if userInput == nil then
        showCloudNotify("卖道具", "输入无效,请输入数字", false)
        return
    end
    
    -- 写入值为 用户输入的值 - 1
    local modifyValue = userInput - 1
    local setList = {}
    local recordList = {}
    
    for _, addr in ipairs(validAddresses) do
        local targetAddr = addr + 20
        local orig = gg.getValues({{address = targetAddr, flags = gg.TYPE_DWORD}})[1].value
        table.insert(recordList, {address = targetAddr, flags = gg.TYPE_DWORD, originalValue = orig})
        table.insert(setList, {address = targetAddr, flags = gg.TYPE_DWORD, value = modifyValue})
    end
    
    gg.setValues(setList)
    MAI_DONGXI_ACTIVE = true
    MAI_DONGXI_DATA = recordList
    showCloudNotify("卖道具", string.format("已开启,共修改 %d 个地址,写入值: %d", #setList, modifyValue), true)
end

function MaiDongXi_Off()
    if not MAI_DONGXI_ACTIVE or not MAI_DONGXI_DATA then
        showCloudNotify("卖道具", "未开启,无需关闭", false)
        return
    end
    
    local restoreList = {}
    for _, item in ipairs(MAI_DONGXI_DATA) do
        table.insert(restoreList, {
            address = item.address,
            flags = item.flags,
            value = item.originalValue
        })
    end
    gg.setValues(restoreList)
    
    MAI_DONGXI_ACTIVE = false
    MAI_DONGXI_DATA = nil
    showCloudNotify("卖道具", "已关闭,数值已恢复", true)
end

function ShowMaiDongXiInstructions()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "卖道具使用说明",
                "1. 进入游戏商城或道具购买界面\n" ..
                "2. 开启本开关后输入自定义数值\n" ..
                "3. 脚本会自动搜索并验证条件(偏移20在[1,30]且偏移24为-491520)\n" ..
                "4. 将偏移20处的值修改为【您输入的值-1】\n\n" ..
                "示例:输入 5,则写入 4\n" ..
                "示例:输入 1,则写入 0\n\n" ..
                "⚠️ 注意:开关式功能,退出商城后建议关闭恢复",
                "知道了")
        end)
    end)
end

function EatZongzi_On()
    if EAT_ZONGZI_DATA then
        showCloudNotify("吃粽子刷分", "已开启,无需重复操作", false)
        return
    end

    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber('4262', gg.TYPE_DWORD)
    local results = gg.getResults(gg.getResultCount())
    if #results == 0 then
        showCloudNotify("吃粽子刷分", "未找到特征数据,请确保在粽子活动界面内", false)
        gg.clearResults()
        return
    end

    local targetList = {}
    local modifyList = {}

    for i, v in ipairs(results) do
        local check1 = gg.getValues({{address = v.address + 8, flags = gg.TYPE_DWORD}})
        if check1[1].value == 4263 then
            local check2 = gg.getValues({{address = v.address + 16, flags = gg.TYPE_DWORD}})
            if check2[1].value == 5 then
                local targetAddr = v.address - 16
                local orig = gg.getValues({{address = targetAddr, flags = gg.TYPE_DWORD}})[1].value
                table.insert(targetList, {
                    address = targetAddr,
                    flags = gg.TYPE_DWORD,
                    originalValue = orig
                })
                table.insert(modifyList, {
                    address = targetAddr,
                    flags = gg.TYPE_DWORD,
                    value = 211,
                    freeze = true
                })
            end
        end
    end

    if #modifyList == 0 then
        showCloudNotify("吃粽子刷分", "未找到符合条件的地址", false)
        gg.clearResults()
        return
    end

    gg.addListItems(modifyList)
    gg.setValues(modifyList)
    EAT_ZONGZI_DATA = targetList
    showCloudNotify("吃粽子刷分", "已开启(撞一次桌子得211分,建议刷到2000分即停)", true)
    gg.clearResults()
end

function EatZongzi_Off()
    if not EAT_ZONGZI_DATA then
        showCloudNotify("吃粽子刷分", "未开启,无需关闭", false)
        return
    end

    local listItems = gg.getListItems()
    for _, item in ipairs(EAT_ZONGZI_DATA) do
        for _, li in ipairs(listItems) do
            if li.address == item.address then
                gg.removeListItems({li})
                break
            end
        end
    end

    local restoreList = {}
    for _, item in ipairs(EAT_ZONGZI_DATA) do
        table.insert(restoreList, {
            address = item.address,
            flags = item.flags,
            value = item.originalValue
        })
    end
    gg.setValues(restoreList)

    EAT_ZONGZI_DATA = nil
    showCloudNotify("吃粽子刷分", "已关闭,数值已恢复", true)
end

function ShowEatZongziInstructions()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "吃粽子刷分使用说明",
                "1. 进入游戏,打开粽子活动界面\n2. 点击暂停按钮(进入暂停状态)\n3. 开启本开关\n4. 撞一次桌子即可获得211分\n5. 累计达到2000分即可拿满奖励,请勿刷太高(否则可能被检测)\n\n⚠️ 注意:退出后记得关闭,不然会闪退。",
                "知道了")
        end)
    end)
end

-- ==================== 泳池修改(单向,每次开启重新执行,基于140特征,写值40) ====================
function PoolModify_On()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.clearResults()

    gg.searchNumber(140, gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
    local results = gg.getResults(gg.getResultsCount())
    if #results == 0 then
        showCloudNotify("泳池修改", "未搜索到,请确保在泳池活动关卡内", false)
        return
    end

    local valid_addrs = {}
    for _, r in ipairs(results) do
        local addr = r.address
        local vals = gg.getValues({
            {address = addr - 28, flags = gg.TYPE_DWORD},
            {address = addr - 36, flags = gg.TYPE_DWORD}
        })
        if vals and #vals == 2 and vals[1].value and vals[2].value then
            if vals[1].value == -491520 and vals[2].value == -491520 then
                table.insert(valid_addrs, addr)
            end
        end
    end

    if #valid_addrs == 0 then
        showCloudNotify("泳池修改", "未找到有效地址", false)
        return
    end

    local writes = {}
    for _, addr in ipairs(valid_addrs) do
        table.insert(writes, {address = addr - 40, value = 80, flags = gg.TYPE_DWORD})
    end
    local write_results = gg.setValues(writes)

    local success_count = 0
    if type(write_results) == "table" then
        for _, res in ipairs(write_results) do
            if res and res.result == true then
                success_count = success_count + 1
            end
        end
    elseif write_results == true then
        success_count = #writes
    else
        success_count = 0
    end

    gg.clearResults()

    if success_count > 0 then
        showCloudNotify("泳池修改", string.format("开启成功,修改了 %d (可再次开启重复执行)", success_count), true)
    else
        showCloudNotify("泳池修改", "写入失败,请检查权限或游戏保护", false)
    end
end

function PoolModify_Off()
    showCloudNotify("泳池修改", "此功能为单向修改,无需关闭(退出关卡后数值恢复)", false)
end

function ShowPoolModifyInstructions()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "泳池修改使用说明",
                "1. 进入泳池活动关卡\n2. 暂停游戏(建议暂停后操作)\n3. 改分数为:点击「开启」修改分数为 800\n4. 改体力为:开启时体力变为无限,关闭后立即结算(建议先开体力再改分数)\n\n⚠️ 注意:进泳池后10s内暂停开启,最佳时间为进图后5s。",
                "知道了")
        end)
    end)
end

-- ==================== 刷成就(单次执行,点击即生效,无需关闭) ====================
function Achievement_Once()
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber("500", gg.TYPE_DWORD)
    local results = gg.getResults(9999999)
    if #results == 0 then
        showCloudNotify("刷成就", "未搜索到特征数据,请确保在游戏关卡内", false)
        gg.clearResults()
        return
    end

    local validAddresses = {}
    for i, v in ipairs(results) do
        local reads = {
            {address = v.address - 560, flags = gg.TYPE_DWORD},
            {address = v.address - 72,  flags = gg.TYPE_DWORD},
            {address = v.address - 496, flags = gg.TYPE_DWORD}
        }
        local values = gg.getValues(reads)
        if values and #values == 3 then
            if values[1].value == 1 and values[2].value == 1 and values[3].value == 40 then
                table.insert(validAddresses, v)
            end
        end
        if i % 500 == 0 then gg.sleep(0) end
    end

    if #validAddresses == 0 then
        showCloudNotify("刷成就", "未找到符合条件的地址", false)
        gg.clearResults()
        return
    end

    local modifyList = {}
    for _, v in ipairs(validAddresses) do
        local addr448 = v.address - 448
        local addr432 = v.address - 432
        local addr408 = v.address - 408
        local addr148 = v.address - 328
        local addr352 = v.address - 352
        table.insert(modifyList, {address = addr448, flags = gg.TYPE_DWORD, value = 100})
        table.insert(modifyList, {address = addr432, flags = gg.TYPE_DWORD, value = 100})
        table.insert(modifyList, {address = addr408, flags = gg.TYPE_DWORD, value = 5})
        table.insert(modifyList, {address = addr148, flags = gg.TYPE_DWORD, value = 40})
        table.insert(modifyList, {address = addr352, flags = gg.TYPE_DWORD, value = 3})
    end

    gg.setValues(modifyList)
    showCloudNotify("刷成就", "已执行(效果:MVP、助攻、野怪王子、斩龙)", true)
    gg.clearResults()
end

-- ==================== 内存操作函数 ====================
function search(ss,lx,nc,dz1,dz2)
    if ss~=nil then
        if lx~=nil then
            if nc==nil then nc = gg.REGION_C_ALLOC | gg.REGION_OTHER end
            gg.setRanges(nc)
            if dz1==nil then dz1="-1" end
            if dz2==nil then dz1="0" end
            gg.searchNumber(ss,lx,false,536870912,dz1,dz2)
            local sl = gg.getResultCount()
            if sl~=0 then
                sj = gg.getResults(sl)
                gg.clearResults()
            else
                showCloudNotify("提示","未找到结果",false)
            end
        end
    end
end

function py1(value,lx,py)
    if #sj~=nil then
        local z1={}
        local z2={}
        for i=1,#sj do
            z1[i]={}
            z1[i].address=sj[i].address+py
            z1[i].flags=lx
        end
        z1=gg.getValues(z1)
        for i=1,#sj do
            if z1[i].value==value then
                z2[#z2+1]=sj[i]
            end
        end
        sj=z2
    else
        showCloudNotify("提示","没有搜索结果",false)
    end
end

function xg1(value,lx,py,dj)
    if #sj~=nil then
        local z={}
        for i=1,#sj do
            z[i]={}
            z[i].address=sj[i].address+py
            z[i].flags=lx
            z[i].value=value
            if dj==true then
                z[i].freeze=true
            end
        end
        if dj==true then
            gg.addListItems(z)
        else
            gg.clearList()
            gg.setValues(z)
        end
    else
        showCloudNotify("提示","没有可修改的结果",false)
    end
end

function S_Pointer(t_So, t_Offset, _bit)
    local function getRanges()
        local ranges = {}
        local t = gg.getRangesList('^/data/*.so*$')
        for i, v in pairs(t) do
            if v.type:sub(2,2) == 'w' then
                table.insert(ranges, v)
            end
        end
        return ranges
    end
    local function Get_Address(N_So, Offset, ti_bit)
        local ti = gg.getTargetInfo()
        local S_list = getRanges()
        local t = {}
        local _t
        local _S = nil
        if ti_bit then
            _t = 32
        else
            _t = 4
        end
        for i in pairs(S_list) do
            local _N = S_list[i].internalName:gsub('^.*/','')
            if N_So[1] == _N and N_So[2] == S_list[i].state then
                _S = S_list[i]
                break
            end
        end
        if _S then
            t[#t+1] = {}
            t[#t].address = _S.start + Offset[1]
            t[#t].flags = _t
            if #Offset ~= 1 then
                for i = 2, #Offset do
                    local S = gg.getValues(t)
                    t = {}
                    for _ in pairs(S) do
                        if not ti.x64 then
                            S[_].value = S[_].value & 0xFFFFFFFF
                        end
                        t[#t+1] = {}
                        t[#t].address = S[_].value + Offset[i]
                        t[#t].flags = _t
                    end
                end
            end
            _S = t[#t].address
        end
        return _S
    end
    local _A = string.format('0x%X', Get_Address(t_So, t_Offset, _bit))
    return _A
end

-- ==================== 稳定秒过 ====================
function StableInstantPass()
    gg.clearResults()
    local extendedRanges = gg.REGION_C_ALLOC | gg.REGION_OTHER | gg.REGION_ANONYMOUS
    gg.setRanges(extendedRanges)
    gg.searchNumber("900000", gg.TYPE_DWORD)
    local cnt = gg.getResultCount()
    if cnt > 0 then
        local results = gg.getResults(cnt)
        local addrs = {}
        for i, v in ipairs(results) do
            addrs[i] = {address = v.address + 80, flags = gg.TYPE_DWORD}
        end
        local vals = gg.getValues(addrs)
        local filtered = {}
        for i, val in ipairs(vals) do
            if val.value == 700 then
                table.insert(filtered, results[i])
            end
        end
        if #filtered > 0 then
            local modifyList = {}
            for _, v in ipairs(filtered) do
                table.insert(modifyList, {address = v.address - 312, flags = gg.TYPE_DWORD, value = 0})
                table.insert(modifyList, {address = v.address - 268, flags = gg.TYPE_DWORD, value = 0})
                table.insert(modifyList, {address = v.address - 24,  flags = gg.TYPE_DWORD, value = 1})
                table.insert(modifyList, {address = v.address - 248, flags = gg.TYPE_DWORD, value = 0})
                table.insert(modifyList, {address = v.address - 272, flags = gg.TYPE_DWORD, value = 1})
                table.insert(modifyList, {address = v.address - 152, flags = gg.TYPE_DWORD, value = 1})
                table.insert(modifyList, {address = v.address,      flags = gg.TYPE_DWORD, value = 2000000})
            end
            gg.setValues(modifyList)
        end
    end
    gg.clearResults()
    
    search(-121, 4, extendedRanges)
    if #sj > 0 then
        py1(-127, 4, 8)
        py1(-125, 4, 16)
        py1(-127, 4, -8)
        py1(-125, 4, -208)
        py1(-125, 4, -240)
        py1(-127, 4, -264)
        if #sj > 0 then
            xg1(0, 4, -244, false)
            xg1(0, 4, -212, false)
            xg1(1, 4, -116, false)
            xg1(1, 4, -236, false)
        end
    end
    
    gg.clearResults()
    search(-294912, 4, extendedRanges)
    if #sj > 0 then
        py1(-491520, 4, 8)
        py1(-425984, 4, 16)
        py1(-491520, 4, -8)
        py1(-425984, 4, -208)
        py1(-425984, 4, -240)
        py1(-491520, 4, -264)
        xg1(0, 4, -244, false)
        xg1(0, 4, -212, false)
        xg1(1, 4, -116, false)
        xg1(1, 4, -236, false)
    end
    
    gg.clearResults()
end

function TerrainIgnorePass()
    StableInstantPass()
    showCloudNotify("无视地形秒过","增强版已执行(必定触发入侵奖励)",true)
end

function SetTerrainLoopInterval()
    local input = gg.prompt({"请输入循环间隔时间(秒):"},{tostring(TERRAIN_LOOP_INTERVAL)},{"number"})
    if input and input[1] then
        local interval = tonumber(input[1])
        if interval and interval > 0 then
            TERRAIN_LOOP_INTERVAL = interval
            showCloudNotify("设置","间隔已设为"..interval.."秒",true)
        else
            showCloudNotify("错误","请输入正数",false)
        end
    else
        showCloudNotify("提示","已取消",false)
    end
end

function StartLoopTerrainIgnorePass()
    if TERRAIN_LOOP_ACTIVE then
        showCloudNotify("提示","循环已在运行",false)
        return
    end
    TERRAIN_LOOP_ACTIVE = true
    showCloudNotify("无视地形循环","已开启,间隔"..TERRAIN_LOOP_INTERVAL.."秒",true)
    local loop_thread = function()
        while TERRAIN_LOOP_ACTIVE do
            StableInstantPass()
            if TERRAIN_LOOP_ACTIVE then
                local start_time = os.time()
                while os.time() - start_time < TERRAIN_LOOP_INTERVAL and TERRAIN_LOOP_ACTIVE do
                    gg.sleep(1000)
                end
            end
        end
        showCloudNotify("无视地形循环","已停止",true)
    end
    pcall(loop_thread)
end

function StopLoopTerrainIgnorePass()
    if not TERRAIN_LOOP_ACTIVE then
        showCloudNotify("提示","循环未运行",false)
        return
    end
    TERRAIN_LOOP_ACTIVE = false
    showCloudNotify("无视地形循环","已停止",true)
end

function InstantPass()
    gg.clearResults()
    search(8000,4)
    py1(-1,4,48)
    py1(10,4,24)
    xg1(9000,4,56,true)
    search(900000,4)
    py1(700,4,80)
    xg1(0,4,-312,false)
    xg1(0,4,-268,false)
    xg1(1,4,-24,false)
    xg1(0,4,-248,false)
    xg1(1,4,-272,false)
    xg1(1,4,-152,false)
    xg1(2000000,4,0,false)
    gg.clearResults()
    showCloudNotify("秒过","单次秒过成功",true)
end

function SetLoopInterval()
    local input = gg.prompt({"请输入循环间隔时间(秒):"},{tostring(LOOP_INTERVAL)},{"number"})
    if input and input[1] then
        local interval = tonumber(input[1])
        if interval and interval > 0 then
            LOOP_INTERVAL = interval
            showCloudNotify("设置","间隔已设为"..interval.."秒",true)
        else
            showCloudNotify("错误","请输入正数",false)
        end
    else
        showCloudNotify("提示","已取消",false)
    end
end

function StartLoopInstantPass()
    if IS_LOOP_ACTIVE then
        showCloudNotify("提示","循环已在运行",false)
        return
    end
    IS_LOOP_ACTIVE = true
    showCloudNotify("秒过循环","已开启,间隔"..LOOP_INTERVAL.."秒",true)
    local loop_thread = function()
        while IS_LOOP_ACTIVE do
            gg.clearResults()
            search(8000,4)
            py1(-1,4,48)
            py1(10,4,24)
            xg1(9000,4,56,true)
            search(900000,4)
            py1(700,4,80)
            xg1(0,4,-312,false)
            xg1(0,4,-268,false)
            xg1(1,4,-24,false)
            xg1(0,4,-248,false)
            xg1(1,4,-272,false)
            xg1(1,4,-152,false)
            xg1(2000000,4,0,false)
            gg.clearResults()
            if IS_LOOP_ACTIVE then
                local start_time = os.time()
                while os.time() - start_time < LOOP_INTERVAL and IS_LOOP_ACTIVE do gg.sleep(1000) end
            end
        end
        showCloudNotify("秒过循环","已停止",true)
    end
    pcall(loop_thread)
end

function StopLoopInstantPass()
    if not IS_LOOP_ACTIVE then
        showCloudNotify("提示","循环未运行",false)
        return
    end
    IS_LOOP_ACTIVE = false
    showCloudNotify("秒过循环","已停止",true)
end

-- 万能修改
function UniversalModify()
    local searchValue = gg.prompt({"请输入要搜索的值:"},{"100.0"},{"number"})
    if searchValue == nil then
        showCloudNotify("万能修改","已取消",false)
        return
    end
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC|gg.REGION_OTHER)
    gg.searchNumber(searchValue[1], gg.TYPE_DOUBLE)
    local results = gg.getResults(10000)
    local resultCount = #results
    if resultCount == 0 then
        showCloudNotify("万能修改","未找到匹配数值",false)
        return
    end
    local modifyCountInput = gg.prompt({"请输入要修改的数量(1-"..resultCount.."):"},{tostring(math.min(150, resultCount))},{"number"})
    if modifyCountInput == nil then
        showCloudNotify("万能修改","已取消",false)
        return
    end
    local modifyCount = tonumber(modifyCountInput[1])
    if modifyCount < 1 or modifyCount > resultCount then
        modifyCount = math.min(150, resultCount)
    end
    local selectedResults = {}
    for i = 1, modifyCount do
        selectedResults[i] = results[i]
    end
    local newValue = gg.prompt({"请输入新数值:"},{"999.0"},{"number"})
    if newValue == nil then
        showCloudNotify("万能修改","已取消",false)
        return
    end
    local actionChoice = gg.choice({"✅仅修改数值","❄️修改并冻结","🚫取消"},nil,"请选择操作方式:")
    if actionChoice == nil or actionChoice == 3 then
        showCloudNotify("万能修改","已取消",false)
        return
    end
    local originalData = {}
    for i = 1, modifyCount do
        originalData[i] = {address = selectedResults[i].address, originalValue = selectedResults[i].value, frozen = (actionChoice == 2)}
    end
    for i = 1, modifyCount do
        selectedResults[i].value = tonumber(newValue[1])
        if actionChoice == 2 then
            selectedResults[i].freeze = true
        else
            selectedResults[i].freeze = false
        end
    end
    gg.setValues(selectedResults)
    if actionChoice == 2 then
        gg.addListItems(selectedResults)
    end
    LAST_MODIFY_DATA = originalData
    LAST_SEARCH_VALUE = tonumber(searchValue[1])
    LAST_MODIFY_COUNT = modifyCount
    local actionText = {"修改","修改并冻结"}
    showCloudNotify("万能修改","成功"..actionText[actionChoice]..modifyCount.."个数值",true)
end

function RestoreLastModify()
    if LAST_MODIFY_DATA == nil then
        showCloudNotify("恢复","没有可恢复的记录",false)
        return
    end
    local choice = gg.choice({"✅确认恢复","❌取消"},nil,"恢复上次修改?")
    if choice == 1 then
        local restoreResults = {}
        for i = 1, #LAST_MODIFY_DATA do
            restoreResults[i] = {address = LAST_MODIFY_DATA[i].address, value = LAST_MODIFY_DATA[i].originalValue, flags = gg.TYPE_DOUBLE, freeze = false}
        end
        gg.setValues(restoreResults)
        local frozenItems = gg.getListItems()
        if #frozenItems > 0 then
            for i = 1, #frozenItems do
                for j = 1, #LAST_MODIFY_DATA do
                    if frozenItems[i].address == LAST_MODIFY_DATA[j].address then
                        gg.removeListItems({frozenItems[i]})
                        break
                    end
                end
            end
        end
        showCloudNotify("恢复","已恢复"..LAST_MODIFY_COUNT.."个数值",true)
        LAST_MODIFY_DATA = nil
    else
        showCloudNotify("恢复","已取消",false)
    end
end

function ShowUniversalModifyInstructions()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "万能修改攻略",
                "八戒第四次普攻提高伤害(图内开):2.1\n有效值(修改人物属性魔抗等):0.008 0.002 0.013 0.001 0.05",
                "知道了")
        end)
    end)
end

-- 穿图
function StepByStep_Enable()
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC|gg.REGION_OTHER)
    local function simpleSearch(v,t) gg.clearResults() gg.setRanges(gg.REGION_C_ALLOC|gg.REGION_OTHER) gg.searchNumber(v,t) return gg.getResultsCount() end
    local function editAll(v,t) local r = gg.getResults(gg.getResultsCount()) for i=1,#r do r[i].value=v r[i].freeze=false end gg.setValues(r) return #r end
    if simpleSearch("0.1",gg.TYPE_FLOAT)>0 then
        editAll("-999",gg.TYPE_FLOAT)
        step_active = true
        showCloudNotify("穿图","已开启",true)
    else
        showCloudNotify("穿图","开启失败",false)
    end
    gg.clearResults()
end

function StepByStep_Disable()
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC|gg.REGION_OTHER)
    local function simpleSearch(v,t) gg.clearResults() gg.setRanges(gg.REGION_C_ALLOC|gg.REGION_OTHER) gg.searchNumber(v,t) return gg.getResultsCount() end
    local function editAll(v,t) local r = gg.getResults(gg.getResultsCount()) for i=1,#r do r[i].value=v r[i].freeze=false end gg.setValues(r) return #r end
    if simpleSearch("-999",gg.TYPE_FLOAT)>0 then
        editAll("0.1",gg.TYPE_FLOAT)
        step_active = false
        showCloudNotify("穿图","已关闭",true)
    else
        showCloudNotify("穿图","关闭失败",false)
    end
    gg.clearResults()
end

-- 内购三生锤
function InternalBloodsucker()
    gg.clearResults()
    gg.setRanges(gg.REGION_OTHER)   -- 仅搜索 other 区

    -- 特征码数据(基于您提供的文件)
    local MAIN_VAL = 2260
    local SUB1_VAL = 2270
    local SUB2_VAL = 1362
    local OFF_SUB1 = 0x4C0
    local OFF_SUB2 = 0x500
    local OFF_TARGET = 0x340

    -- 搜索主特征码
    gg.searchNumber(MAIN_VAL, gg.TYPE_DWORD)
    local cnt = gg.getResultCount()
    if cnt == 0 then
        showCloudNotify("内购三生锤", "未找到主特征码 2260", false)
        gg.clearResults()
        return
    end

    local results = gg.getResults(cnt)
    local modifyList = {}
    local validCount = 0

    for _, v in ipairs(results) do
        -- 验证副特征码1和2
        local check = gg.getValues({
            {address = v.address + OFF_SUB1, flags = gg.TYPE_DWORD},
            {address = v.address + OFF_SUB2, flags = gg.TYPE_DWORD}
        })
        if check[1].value == SUB1_VAL and check[2].value == SUB2_VAL then
            local targetAddr = v.address + OFF_TARGET
            table.insert(modifyList, {
                address = targetAddr,
                flags = gg.TYPE_DWORD,
                value = -99999999
            })
            validCount = validCount + 1
        end
    end

    if #modifyList > 0 then
        gg.setValues(modifyList)
        showCloudNotify("内购三生锤", "开启成功,修改 " .. #modifyList .. " 处", true)
    else
        showCloudNotify("内购三生锤", "未找到同时匹配副特征码的地址", false)
    end
    gg.clearResults()
end
-- ==================== 法宝秒怪 ====================
local function modifyFabaosearch(targetValue, newValue)
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber(tostring(targetValue), gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
    gg.searchNumber(tostring(targetValue), gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
    gg.getResults(100)
    gg.editAll(tostring(newValue), gg.TYPE_DWORD)
    showCloudNotify("法宝秒怪","开启成功",true)
end

function FaBao_ZhenHunXiaoYiJie() modifyFabaosearch(100310, 20786) end
function FaBao_ZhenHunXiaoErJie() modifyFabaosearch(100320, 20786) end
function FaBao_YunYangBanYiJie() modifyFabaosearch(100250, 20786) end
function FaBao_YunYangBanErJie() modifyFabaosearch(100260, 20786) end
function FaBao_KuYeLingYiJie() modifyFabaosearch(100160, 20786) end
function FaBao_KuYeLingErJie() modifyFabaosearch(100170, 20786) end
function FaBao_KuiHuaLanYiJie() modifyFabaosearch(100330, 20786) end
function FaBao_KuiHuaLanErJie() modifyFabaosearch(100340, 20786) end

-- ==================== v2.5 三生锤无敌属性(开关式) ====================
function SanShengChui_On()
    if SANSHENGCHUI_DATA then
        showCloudNotify("三生锤无敌属性", "已开启,无需重复操作", false)
        return
    end

    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)

    local MAIN_VAL = 1070176665
    local SUB1_VAL = 1069128089
    local SUB2_VAL = 40
    local OFF_SUB1 = 320
    local OFF_SUB2 = 204
    local BASE_OFF = 188
    local STEP = 8
    local COUNT = 12
    local NEW_VAL = 99999

    gg.searchNumber(MAIN_VAL, gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1, 0)
    local cnt = gg.getResultsCount()
    if cnt == 0 then
        showCloudNotify("三生锤无敌属性", "未找到主特征码,请确认游戏内存区域", false)
        gg.clearResults()
        return
    end
    local results = gg.getResults(cnt)

    local targetAddrs = {}
    for _, r in ipairs(results) do
        local addr = r.address
        local check = gg.getValues({
            { address = addr + OFF_SUB1, flags = gg.TYPE_DWORD },
            { address = addr + OFF_SUB2, flags = gg.TYPE_DWORD }
        })
        if check[1].value == SUB1_VAL and check[2].value == SUB2_VAL then
            table.insert(targetAddrs, addr)
        end
    end

    if #targetAddrs == 0 then
        showCloudNotify("三生锤无敌属性", "未找到同时匹配副特征码的地址,可能偏移或数值有变化", false)
        gg.clearResults()
        return
    end

    local setList = {}
    local saveList = {}
    local recordList = {}
    for _, baseAddr in ipairs(targetAddrs) do
        for i = 0, COUNT - 1 do
            local curAddr = baseAddr + BASE_OFF + i * STEP
            local orig = gg.getValues({{ address = curAddr, flags = gg.TYPE_DWORD }})[1].value
            table.insert(recordList, { address = curAddr, flags = gg.TYPE_DWORD, originalValue = orig })
            local entry = { address = curAddr, flags = gg.TYPE_DWORD, value = NEW_VAL }
            table.insert(setList, entry)
            table.insert(saveList, entry)
        end
    end

    gg.setValues(setList)
    gg.addListItems(saveList)
    SANSHENGCHUI_DATA = recordList
    gg.clearResults()

    local total = #targetAddrs * COUNT
    showCloudNotify("三生锤无敌属性", string.format("已开启,修改 %d 个地址(%d 个主地址 × %d 个偏移),已保存至保存列表", total, #targetAddrs, COUNT), true)
end

function SanShengChui_Off()
    if not SANSHENGCHUI_DATA then
        showCloudNotify("三生锤无敌属性", "未开启,无需关闭", false)
        return
    end

    local restoreList = {}
    for _, item in ipairs(SANSHENGCHUI_DATA) do
        table.insert(restoreList, { address = item.address, flags = item.flags, value = item.originalValue })
    end
    gg.setValues(restoreList)

    local listItems = gg.getListItems()
    for _, item in ipairs(SANSHENGCHUI_DATA) do
        for _, li in ipairs(listItems) do
            if li.address == item.address and li.flags == item.flags then
                gg.removeListItems({ li })
                break
            end
        end
    end

    SANSHENGCHUI_DATA = nil
    showCloudNotify("三生锤无敌属性", "已关闭,所有数值已恢复", true)
end

-- 游戏加速
function GameSpeed_On()
    if GAME_SPEED_ACTIVE then
        showCloudNotify("游戏加速","已开启",false)
        return
    end
    GAME_SPEED_ACTIVE = true
    gg.setSpeed(GAME_SPEED_VALUE)
    if GAME_SPEED_TIMER then gg.clearTimer(GAME_SPEED_TIMER) end
    GAME_SPEED_TIMER = gg.timer(2000, function() if GAME_SPEED_ACTIVE then gg.setSpeed(GAME_SPEED_VALUE) end end)
    showCloudNotify("游戏加速","已开启(倍速:"..GAME_SPEED_VALUE..")",true)
end

function GameSpeed_Off()
    if not GAME_SPEED_ACTIVE then
        showCloudNotify("游戏加速","未开启",false)
        return
    end
    GAME_SPEED_ACTIVE = false
    if GAME_SPEED_TIMER then gg.clearTimer(GAME_SPEED_TIMER) GAME_SPEED_TIMER = nil end
    gg.setSpeed(1.0)
    showCloudNotify("游戏加速","已关闭",true)
end

function SetGameSpeedValue()
    local input = gg.prompt({"请输入游戏加速倍速(建议1~5倍):"},{tostring(GAME_SPEED_VALUE)},{"number"})
    if input == nil then
        showCloudNotify("设置","已取消",false)
        return
    end
    local newSpeed = tonumber(input[1])
    if not newSpeed or newSpeed <= 0 then
        showCloudNotify("错误","倍速必须大于0",false)
        return
    end
    if newSpeed > 5 then
        local confirm = gg.choice({"继续使用","重新输入"},nil,"⚠️倍速超过5倍可能不稳定")
        if confirm == 2 or confirm == nil then return end
    end
    GAME_SPEED_VALUE = newSpeed
    if GAME_SPEED_ACTIVE then
        gg.setSpeed(GAME_SPEED_VALUE)
        showCloudNotify("游戏加速","倍速已更新为"..GAME_SPEED_VALUE.."倍",true)
    else
        showCloudNotify("游戏加速","倍速已保存为"..GAME_SPEED_VALUE.."倍",true)
    end
end

-- 全局加速
function SetGlobalSpeedMultiplier()
    local input = gg.prompt({"请输入全局加速倍速(建议1~6倍):"},{tostring(GLOBAL_SPEED_MULTIPLIER)},{"number"})
    if input == nil then
        showCloudNotify("设置","已取消",false)
        return
    end
    local newSpeed = tonumber(input[1])
    if not newSpeed or newSpeed <= 0 then
        showCloudNotify("错误","倍速必须大于0",false)
        return
    end
    if newSpeed > 6 then
        local confirm = gg.choice({"继续使用","重新输入"},nil,"⚠️倍速超过6倍可能不稳定")
        if confirm == 2 or confirm == nil then return end
    end
    GLOBAL_SPEED_MULTIPLIER = newSpeed
    if GLOBAL_SPEED_DATA then
        gg.setValues({{address = GLOBAL_SPEED_DATA.address, flags = GLOBAL_SPEED_DATA.flags, value = GLOBAL_SPEED_MULTIPLIER}})
        showCloudNotify("全局加速","倍速已更新为"..GLOBAL_SPEED_MULTIPLIER.."倍",true)
    else
        showCloudNotify("全局加速","倍速已保存为"..GLOBAL_SPEED_MULTIPLIER.."倍",true)
    end
end

function GlobalSpeed_On()
    if GLOBAL_SPEED_DATA then
        showCloudNotify("全局加速","已开启",false)
        return
    end
    local t = {'libcocos2djs.so:bss', 'Cb'}
    local tt = {0xA4698, 0x118, 0x24}
    local ttt = S_Pointer(t, tt, true)
    if ttt == nil or ttt == "0x0" then
        showCloudNotify("全局加速","无法定位地址",false)
        return
    end
    local addr = tonumber(ttt)
    local flags = gg.TYPE_FLOAT
    local orig = gg.getValues({{address = addr, flags = flags}})[1].value
    GLOBAL_SPEED_DATA = {address = addr, flags = flags, originalValue = orig}
    gg.setValues({{address = addr, flags = flags, value = GLOBAL_SPEED_MULTIPLIER}})
    showCloudNotify("全局加速","已开启(倍速:"..GLOBAL_SPEED_MULTIPLIER..")",true)
end

function GlobalSpeed_Off()
    if not GLOBAL_SPEED_DATA then
        showCloudNotify("全局加速","未开启",false)
        return
    end
    gg.setValues({{address = GLOBAL_SPEED_DATA.address, flags = GLOBAL_SPEED_DATA.flags, value = GLOBAL_SPEED_DATA.originalValue}})
    GLOBAL_SPEED_DATA = nil
    showCloudNotify("全局加速","已关闭",true)
end

-- 猴子无敌秒
function MonkeyInvincibleKill_On()
    if MONKEY_INVINCIBLE_KILL_DATA then
        showCloudNotify("猴子无敌秒","已开启",false)
        return
    end
    gg.clearResults()
    local modifyList = {}
    local saveData = {}
    local extendedRanges = gg.REGION_C_ALLOC | gg.REGION_OTHER
    search(1074921472, 4, extendedRanges)
    if #sj == 0 then
        showCloudNotify("猴子无敌秒","未找到无敌特征",false)
        gg.clearResults()
        return
    end
    py1(-425984, 4, 8)
    if #sj == 0 then
        showCloudNotify("猴子无敌秒","无敌特征筛选失败",false)
        gg.clearResults()
        return
    end
    for _, v in ipairs(sj) do
        local targetAddr = v.address + 12
        local orig = gg.getValues({{address = targetAddr, flags = 4}})[1].value
        table.insert(saveData, {address = targetAddr, flags = 4, originalValue = orig})
        table.insert(modifyList, {address = targetAddr, flags = 4, value = 1})
    end
    search(1078198272, 4, extendedRanges)
    if #sj == 0 then
        showCloudNotify("猴子无敌秒","未找到秒杀特征",false)
        gg.clearResults()
        return
    end
    py1(-491520, 4, 8)
    if #sj == 0 then
        showCloudNotify("猴子无敌秒","秒杀特征筛选失败",false)
        gg.clearResults()
        return
    end
    for _, v in ipairs(sj) do
        local targetAddr = v.address + 4
        local orig = gg.getValues({{address = targetAddr, flags = 4}})[1].value
        table.insert(saveData, {address = targetAddr, flags = 4, originalValue = orig})
        table.insert(modifyList, {address = targetAddr, flags = 4, value = 20786})
    end
    if #modifyList == 0 then
        showCloudNotify("猴子无敌秒","未生成修改项",false)
        return
    end
    gg.setValues(modifyList)
    MONKEY_INVINCIBLE_KILL_DATA = saveData
    showCloudNotify("猴子无敌秒","已开启(无敌+秒杀)",true)
    gg.clearResults()
end

function MonkeyInvincibleKill_Off()
    if not MONKEY_INVINCIBLE_KILL_DATA then
        showCloudNotify("猴子无敌秒","未开启",false)
        return
    end
    local restoreList = {}
    for _, item in ipairs(MONKEY_INVINCIBLE_KILL_DATA) do
        table.insert(restoreList, {address = item.address, flags = item.flags, value = item.originalValue})
    end
    gg.setValues(restoreList)
    MONKEY_INVINCIBLE_KILL_DATA = nil
    showCloudNotify("猴子无敌秒","已关闭",true)
    gg.clearResults()
end

-- 悟空强普替换
function WukongStrongReplace_On()
    if WUKONG_STRONG_REPLACE_ACTIVE then
        showCloudNotify("悟空强普替换","已开启",false)
        return
    end
    gg.clearResults()
    search(1078198272, 4)
    if #sj == 0 then
        showCloudNotify("悟空强普替换","未找到特征数据",false)
        return
    end
    py1(1015, 4, 4)
    if #sj == 0 then
        showCloudNotify("悟空强普替换","未找到匹配的技能地址",false)
        return
    end
    local targetAddr = sj[1].address + 4
    local orig = gg.getValues({{address = targetAddr, flags = 4}})[1].value
    local freezeItem = {address = targetAddr, flags = 4, value = WUKONG_STRONG_REPLACE_VALUE, freeze = true}
    gg.addListItems({freezeItem})
    WUKONG_STRONG_REPLACE_DATA = {address = targetAddr, originalValue = orig, flags = 4}
    WUKONG_STRONG_REPLACE_ACTIVE = true
    showCloudNotify("悟空强普替换","已开启(技能代码:"..WUKONG_STRONG_REPLACE_VALUE..")",true)
    gg.clearResults()
end

function WukongStrongReplace_Off()
    if not WUKONG_STRONG_REPLACE_ACTIVE then
        showCloudNotify("悟空强普替换","未开启",false)
        return
    end
    if WUKONG_STRONG_REPLACE_DATA then
        local listItems = gg.getListItems()
        for _, li in ipairs(listItems) do
            if li.address == WUKONG_STRONG_REPLACE_DATA.address then
                gg.removeListItems({li})
                break
            end
        end
        gg.setValues({{address = WUKONG_STRONG_REPLACE_DATA.address, flags = WUKONG_STRONG_REPLACE_DATA.flags, value = WUKONG_STRONG_REPLACE_DATA.originalValue}})
        WUKONG_STRONG_REPLACE_DATA = nil
    end
    WUKONG_STRONG_REPLACE_ACTIVE = false
    showCloudNotify("悟空强普替换","已关闭",true)
end

function SetWukongStrongReplaceValue()
    local input = gg.prompt({"请输入技能代码(默认8660)"},{tostring(WUKONG_STRONG_REPLACE_VALUE)},{"number"})
    if input == nil then
        showCloudNotify("设置","已取消",false)
        return
    end
    local newCode = tonumber(input[1])
    if not newCode then
        showCloudNotify("错误","请输入有效数字",false)
        return
    end
    WUKONG_STRONG_REPLACE_VALUE = newCode
    showCloudNotify("悟空强普","技能代码已设置为"..newCode,true)
    if WUKONG_STRONG_REPLACE_ACTIVE then
        WukongStrongReplace_Off()
        WukongStrongReplace_On()
    end
end

-- 通天神猴
function MonkeySkillReplace_On()
    if MONKEY_SKILL_DATA then
        showCloudNotify("通天神猴","已开启",false)
        return
    end
    gg.clearResults()
    local modifyRecords = {}
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber("942956337", gg.TYPE_DWORD)
    local cnt = gg.getResultCount()
    if cnt == 0 then
        showCloudNotify("通天神猴","未找到普攻特征",false)
        return
    end
    local results1 = gg.getResults(cnt)
    local filtered1 = {}
    for _, v in ipairs(results1) do
        local checkAddr = v.address + 4
        local val = gg.getValues({{address = checkAddr, flags = 4}})[1].value
        if val == 12848 then
            filtered1[#filtered1 + 1] = v
        end
    end
    if #filtered1 == 0 then
        showCloudNotify("通天神猴","普攻特征筛选失败",false)
        return
    end
    local mods1 = {
        {offset = 400, newVal = 1735290740, flags = 4},{offset = 404, newVal = 1851877748, flags = 4},
        {offset = 408, newVal = 1868654954, flags = 4},{offset = 412, newVal = 1601529978, flags = 4},
        {offset = 416, newVal = 1818848115, flags = 4},{offset = 420, newVal = 13420, flags = 4},
        {offset = 492, newVal = 22, flags = 4},{offset = 496, newVal = 1735290740, flags = 4},
        {offset = 500, newVal = 1851877748, flags = 4},{offset = 504, newVal = 1868654954, flags = 4},
        {offset = 508, newVal = 1601529978, flags = 4},{offset = 512, newVal = 1818848115, flags = 4},
        {offset = 516, newVal = 13676, flags = 4},{offset = 588, newVal = 22, flags = 4},
        {offset = 592, newVal = 2054516580, flags = 4},{offset = 596, newVal = 1936613736, flags = 4},
        {offset = 600, newVal = 1735288168, flags = 4},{offset = 604, newVal = 1935634278, flags = 4},
        {offset = 608, newVal = 1819044203, flags = 4},{offset = 612, newVal = 12849, flags = 4},
        {offset = 684, newVal = 22, flags = 4},{offset = 688, newVal = 1634497125, flags = 4},
        {offset = 692, newVal = 1752393582, flags = 4},{offset = 696, newVal = 1935634021, flags = 4},
        {offset = 700, newVal = 1819044203, flags = 4},{offset = 704, newVal = 909336374, flags = 4},
        {offset = 708, newVal = 12848, flags = 4},{offset = 780, newVal = 23, flags = 4},
        {offset = 784, newVal = 1735290740, flags = 4},{offset = 788, newVal = 1851877748, flags = 4},
        {offset = 792, newVal = 1868654954, flags = 4},{offset = 796, newVal = 1601529978, flags = 4},
        {offset = 800, newVal = 1818848115, flags = 4},{offset = 804, newVal = 3158380, flags = 4},
        {offset = 972, newVal = 17, flags = 4},{offset = 976, newVal = 1634497125, flags = 4},
        {offset = 980, newVal = 1752393582, flags = 4},{offset = 984, newVal = 1935634021, flags = 4},
        {offset = 988, newVal = 1819044203, flags = 4},{offset = 992, newVal = 50, flags = 4},
        {offset = 996, newVal = 0, flags = 4},{offset = 396, newVal = 22, flags = 4},
    }
    for _, r in ipairs(filtered1) do
        for _, m in ipairs(mods1) do
            local targetAddr = r.address + m.offset
            local orig = gg.getValues({{address = targetAddr, flags = m.flags}})[1].value
            table.insert(modifyRecords, {address = targetAddr, flags = m.flags, originalValue = orig})
            gg.setValues({{address = targetAddr, flags = m.flags, value = m.newVal}})
        end
    end
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber("909128031", gg.TYPE_DWORD)
    local cnt2 = gg.getResultCount()
    if cnt2 == 0 then
        showCloudNotify("通天神猴","未找到技能特征,普攻已改",false)
        for _, rec in ipairs(modifyRecords) do
            gg.setValues({{address = rec.address, flags = rec.flags, value = rec.originalValue}})
        end
        return
    end
    local results2 = gg.getResults(cnt2)
    local filtered2 = {}
    for _, v in ipairs(results2) do
        local checkAddr = v.address - 4
        local val = gg.getValues({{address = checkAddr, flags = 4}})[1].value
        if val == 862743657 then
            filtered2[#filtered2 + 1] = v
        end
    end
    if #filtered2 == 0 then
        showCloudNotify("通天神猴","技能特征筛选失败,普攻已改",false)
        for _, rec in ipairs(modifyRecords) do
            gg.setValues({{address = rec.address, flags = rec.flags, value = rec.originalValue}})
        end
        return
    end
    local mods2 = {
        {offset = 112, newVal = 1735290740, flags = 4},{offset = 116, newVal = 1851877748, flags = 4},
        {offset = 120, newVal = 1868654954, flags = 4},{offset = 124, newVal = 1601529978, flags = 4},
        {offset = 128, newVal = 1818848115, flags = 4},{offset = 132, newVal = 3223916, flags = 4},
        {offset = -372, newVal = 17, flags = 4},{offset = -368, newVal = 1702193516, flags = 4},
        {offset = -364, newVal = 1936671346, flags = 4},{offset = -360, newVal = 1802723187, flags = 4},
        {offset = -356, newVal = 829189225, flags = 4},{offset = -352, newVal = 48, flags = 4},
        {offset = -348, newVal = 0, flags = 4},{offset = 108, newVal = 23, flags = 4},
    }
    for _, r in ipairs(filtered2) do
        for _, m in ipairs(mods2) do
            local targetAddr = r.address + m.offset
            local orig = gg.getValues({{address = targetAddr, flags = m.flags}})[1].value
            table.insert(modifyRecords, {address = targetAddr, flags = m.flags, originalValue = orig})
            gg.setValues({{address = targetAddr, flags = m.flags, value = m.newVal}})
        end
    end
    if #modifyRecords == 0 then
        showCloudNotify("通天神猴","未生成修改项",false)
        return
    end
    MONKEY_SKILL_DATA = modifyRecords
    showCloudNotify("通天神猴","已开启(替换普攻+技能)",true)
    gg.clearResults()
end

function MonkeySkillReplace_Off()
    if not MONKEY_SKILL_DATA then
        showCloudNotify("通天神猴","未开启",false)
        return
    end
    local restoreList = {}
    for _, item in ipairs(MONKEY_SKILL_DATA) do
        restoreList[#restoreList + 1] = {address = item.address, flags = item.flags, value = item.originalValue}
    end
    gg.setValues(restoreList)
    MONKEY_SKILL_DATA = nil
    showCloudNotify("通天神猴","已关闭",true)
    gg.clearResults()
end

-- 模型透视
function ModelPenetration_On()
    if MODEL_PENETRATION_DATA then
        showCloudNotify("模型透视","已开启",false)
        return
    end
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber("876899620", gg.TYPE_DWORD)
    local count = gg.getResultCount()
    if count == 0 then
        showCloudNotify("模型透视","未找到特征",false)
        gg.clearResults()
        return
    end
    local results = gg.getResults(count)
    gg.clearResults()
    local filtered = {}
    local checkAddrs = {}
    for i, v in ipairs(results) do
        checkAddrs[i] = {address = v.address + 4, flags = gg.TYPE_DWORD}
    end
    local checkVals = gg.getValues(checkAddrs)
    for i, val in ipairs(checkVals) do
        if val.value == 0 then
            table.insert(filtered, results[i])
        end
    end
    if #filtered == 0 then
        showCloudNotify("模型透视","特征匹配失败",false)
        return
    end
    local modifyList = {}
    local recordList = {}
    for _, addrInfo in ipairs(filtered) do
        local targetAddr = addrInfo.address + 52
        local orig = gg.getValues({{address = targetAddr, flags = gg.TYPE_DWORD}})[1].value
        table.insert(recordList, {address = targetAddr, flags = gg.TYPE_DWORD, originalValue = orig})
        table.insert(modifyList, {address = targetAddr, flags = gg.TYPE_DWORD, value = 257, freeze = true})
    end
    gg.addListItems(modifyList)
    gg.setValues(modifyList)
    MODEL_PENETRATION_DATA = recordList
    showCloudNotify("模型透视","已开启,修改"..#modifyList.."处",true)
end

function ModelPenetration_Off()
    if not MODEL_PENETRATION_DATA then
        showCloudNotify("模型透视","未开启",false)
        return
    end
    local restoreList = {}
    for _, item in ipairs(MODEL_PENETRATION_DATA) do
        table.insert(restoreList, {address = item.address, flags = item.flags, value = item.originalValue})
    end
    gg.setValues(restoreList)
    local currentList = gg.getListItems()
    for _, item in ipairs(MODEL_PENETRATION_DATA) do
        for _, li in ipairs(currentList) do
            if li.address == item.address and li.flags == item.flags then
                gg.removeListItems({li})
                break
            end
        end
    end
    MODEL_PENETRATION_DATA = nil
    showCloudNotify("模型透视","已关闭",true)
    gg.clearResults()
end

-- 全员技能无冷却
function AllNoCooldown_On()
    if ALL_NO_COOLDOWN_DATA then
        showCloudNotify("全员无冷却","已开启",false)
        return
    end
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber("2680", gg.TYPE_DWORD)
    local resultCount = gg.getResultCount()
    if resultCount == 0 then
        showCloudNotify("全员无冷却","未找到冷却特征",false)
        gg.clearResults()
        return
    end
    local results = gg.getResults(resultCount)
    local modifyList = {}
    local recordList = {}
    for _, v in ipairs(results) do
        local addr2680 = v.address
        local verifyAddr = addr2680 - 16
        local verifyVal = gg.getValues({{address = verifyAddr, flags = gg.TYPE_DWORD}})[1].value
        if verifyVal == 1000 then
            local checkAddr = addr2680 + 24
            local checkVal = gg.getValues({{address = checkAddr, flags = gg.TYPE_DWORD}})[1].value
            if checkVal == 4 then
                local targetAddr = addr2680 - 8
                local origVal = gg.getValues({{address = targetAddr, flags = gg.TYPE_DWORD}})[1].value
                table.insert(recordList, {address = targetAddr, flags = gg.TYPE_DWORD, originalValue = origVal})
                table.insert(modifyList, {address = targetAddr, flags = gg.TYPE_DWORD, value = 0})
            end
        end
    end
    if #modifyList == 0 then
        showCloudNotify("全员无冷却","没有满足条件的地址",false)
        gg.clearResults()
        return
    end
    gg.setValues(modifyList)
    ALL_NO_COOLDOWN_DATA = recordList
    showCloudNotify("全员无冷却","已开启,共修改"..#modifyList.."处",true)
    gg.clearResults()
end

function AllNoCooldown_Off()
    if not ALL_NO_COOLDOWN_DATA then
        showCloudNotify("全员无冷却","未开启",false)
        return
    end
    local restoreList = {}
    for _, item in ipairs(ALL_NO_COOLDOWN_DATA) do
        table.insert(restoreList, {address = item.address, flags = item.flags, value = item.originalValue})
    end
    gg.setValues(restoreList)
    ALL_NO_COOLDOWN_DATA = nil
    showCloudNotify("全员无冷却","已关闭",true)
    gg.clearResults()
end

-- 角色无蓝耗
function NoManaCost_On()
    if NO_MANA_LIST_ITEMS then
        showCloudNotify("无蓝耗","已开启",false)
        return
    end
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber("500", gg.TYPE_DWORD)
    local count = gg.getResultCount()
    if count == 0 then
        showCloudNotify("无蓝耗","未找到数据",false)
        gg.clearResults()
        return
    end
    local results = gg.getResults(count)
    gg.clearResults()
    local filters = {{"-425984", "12"}, {"-425984", "20"}, {"-425984", "28"}}
    for _, f in ipairs(filters) do
        local tmp = {}
        for _, v in ipairs(results) do
            tmp[#tmp+1] = {address = v.address + tonumber(f[2]), flags = gg.TYPE_DWORD}
        end
        tmp = gg.getValues(tmp)
        local filtered = {}
        for i, val in ipairs(tmp) do
            if tostring(val.value) == f[1] then
                filtered[#filtered+1] = results[i]
            end
        end
        results = filtered
        if #results == 0 then break end
    end
    if #results == 0 then
        showCloudNotify("无蓝耗","特征匹配失败",false)
        return
    end
    local itemsToAdd = {}
    local backup = {}
    for _, addrInfo in ipairs(results) do
        local targetAddr = addrInfo.address + 24
        local orig = gg.getValues({{address = targetAddr, flags = gg.TYPE_DWORD}})[1].value
        table.insert(backup, {address = targetAddr, original = orig, flags = gg.TYPE_DWORD})
        table.insert(itemsToAdd, {address = targetAddr, flags = gg.TYPE_DWORD, value = 1, freeze = false})
    end
    local writeList = {}
    for _, item in ipairs(itemsToAdd) do
        writeList[#writeList+1] = {address = item.address, flags = item.flags, value = item.value}
    end
    gg.setValues(writeList)
    gg.addListItems(itemsToAdd)
    NO_MANA_LIST_ITEMS = {addedItems = itemsToAdd, backup = backup}
    showCloudNotify("无蓝耗","已开启,共"..#itemsToAdd.."项",true)
    gg.clearResults()
end

function NoManaCost_Off()
    if not NO_MANA_LIST_ITEMS then
        showCloudNotify("无蓝耗","未开启",false)
        return
    end
    local currentList = gg.getListItems()
    for _, added in ipairs(NO_MANA_LIST_ITEMS.addedItems) do
        for _, li in ipairs(currentList) do
            if li.address == added.address and li.flags == added.flags then
                gg.removeListItems({li})
                break
            end
        end
    end
    local restoreList = {}
    for _, bk in ipairs(NO_MANA_LIST_ITEMS.backup) do
        restoreList[#restoreList+1] = {address = bk.address, flags = bk.flags, value = bk.original}
    end
    gg.setValues(restoreList)
    NO_MANA_LIST_ITEMS = nil
    showCloudNotify("无蓝耗","已关闭",true)
end

local function BothOn()
    NoManaCost_On()
    AllNoCooldown_On()
end
local function BothOff()
    NoManaCost_Off()
    AllNoCooldown_Off()
end

-- 坠龙角色无敌
function ZuilongRoleInvincible_On()
    if ZUILONG_ROLE_INVINCIBLE_ACTIVE then
        showCloudNotify("坠龙角色无敌","已开启",false)
        return
    end
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber("500", gg.TYPE_DWORD)
    local count = gg.getResultCount()
    if count == 0 then
        showCloudNotify("坠龙角色无敌","未找到特征",false)
        gg.clearResults()
        return
    end
    local results = gg.getResults(count)
    local validAddrs = {}
    local origData = {}
    for _, v in ipairs(results) do
        local addr = v.address
        local check = gg.getValues({
            {address = addr + 4,   flags = gg.TYPE_DWORD},
            {address = addr - 4,   flags = gg.TYPE_DWORD},
            {address = addr - 76,  flags = gg.TYPE_DWORD},
            {address = addr + 12,  flags = gg.TYPE_DWORD},
            {address = addr - 12,  flags = gg.TYPE_DWORD},
            {address = addr - 16,  flags = gg.TYPE_DWORD}
        })
        local c1, c2, c3, c4, c5, c6 = check[1].value, check[2].value, check[3].value, check[4].value, check[5].value, check[6].value
        if c1 == -491520 and c2 == -262026 and c3 == -262026 and c4 == -425984 and c5 == -425984 and c6 == 0 then
            table.insert(validAddrs, addr)
            local targetAddr = addr + 16
            local origVal = gg.getValues({{address = targetAddr, flags = gg.TYPE_DWORD}})[1].value
            table.insert(origData, {address = targetAddr, originalValue = origVal, flags = gg.TYPE_DWORD})
        end
    end
    if #validAddrs == 0 then
        showCloudNotify("坠龙角色无敌","未找到满足条件的地址",false)
        gg.clearResults()
        return
    end
    local modifyList = {}
    for _, addr in ipairs(validAddrs) do
        table.insert(modifyList, {address = addr + 16, flags = gg.TYPE_DWORD, value = 1})
    end
    gg.setValues(modifyList)
    ZUILONG_ROLE_INVINCIBLE_DATA = origData
    ZUILONG_ROLE_INVINCIBLE_ACTIVE = true
    showCloudNotify("坠龙角色无敌","已开启,共修改"..#modifyList.."处",true)
    gg.clearResults()
end

function ZuilongRoleInvincible_Off()
    if not ZUILONG_ROLE_INVINCIBLE_ACTIVE then
        showCloudNotify("坠龙角色无敌","未开启",false)
        return
    end
    if ZUILONG_ROLE_INVINCIBLE_DATA and #ZUILONG_ROLE_INVINCIBLE_DATA > 0 then
        local restoreList = {}
        for _, item in ipairs(ZUILONG_ROLE_INVINCIBLE_DATA) do
            table.insert(restoreList, {address = item.address, flags = item.flags, value = item.originalValue})
        end
        gg.setValues(restoreList)
        showCloudNotify("坠龙角色无敌","已关闭,已恢复"..#restoreList.."处",true)
    else
        showCloudNotify("坠龙角色无敌","未找到可恢复数据",false)
    end
    ZUILONG_ROLE_INVINCIBLE_ACTIVE = false
    ZUILONG_ROLE_INVINCIBLE_DATA = nil
    gg.clearResults()
end

-- 火焰山替换主线关卡(单次执行,保留开关,每次开启重新执行)
function FlameMountain_On()
    gg.clearResults()
    local modifyList = {}
    local ranges = gg.REGION_C_ALLOC | gg.REGION_OTHER
    gg.setRanges(ranges)

    -- 搜索特征 9010
    gg.searchNumber("9010", gg.TYPE_DWORD)
    local cnt1 = gg.getResultCount()
    if cnt1 > 0 then
        local results1 = gg.getResults(cnt1)
        for _, v in ipairs(results1) do
            local addr = v.address
            local val1 = gg.getValues({{address = addr + 4, flags = gg.TYPE_DWORD}})[1].value
            if val1 == -491520 then
                local val2 = gg.getValues({{address = addr + 16, flags = gg.TYPE_DWORD}})[1].value
                if val2 == -1 then
                    local val3 = gg.getValues({{address = addr + 20, flags = gg.TYPE_DWORD}})[1].value
                    if val3 == -491520 then
                        table.insert(modifyList, {address = addr, flags = gg.TYPE_DWORD, value = FLAME_MOUNTAIN_ID})
                    end
                end
            end
        end
    end

    -- 搜索特征 3005
    gg.clearResults()
    gg.setRanges(ranges)
    gg.searchNumber("3005", gg.TYPE_DWORD)
    local cnt2 = gg.getResultCount()
    if cnt2 > 0 then
        local results2 = gg.getResults(cnt2)
        for _, v in ipairs(results2) do
            local addr = v.address
            local val1 = gg.getValues({{address = addr + 4, flags = gg.TYPE_DWORD}})[1].value
            if val1 == -491520 then
                local val2 = gg.getValues({{address = addr + 16, flags = gg.TYPE_DWORD}})[1].value
                if val2 == -1 then
                    local val3 = gg.getValues({{address = addr + 20, flags = gg.TYPE_DWORD}})[1].value
                    if val3 == -491520 then
                        table.insert(modifyList, {address = addr, flags = gg.TYPE_DWORD, value = FLAME_MOUNTAIN_ID})
                    end
                end
            end
        end
    end

    if #modifyList == 0 then
        showCloudNotify("火焰山替换", "未找到组队特征,请确保在组队界面开启", false)
        gg.clearResults()
        return
    end

    gg.setValues(modifyList)
    gg.clearResults()
    showCloudNotify("火焰山替换", string.format("已执行,修改 %d 处,关卡ID: %d(可重复开启)", #modifyList, FLAME_MOUNTAIN_ID), true)
end

function FlameMountain_Off()
    -- 单次执行功能,关闭时不恢复数据
    showCloudNotify("火焰山替换", "单次执行功能,关闭无影响(再次开启可重新执行)", false)
end

function SetFlameMountainID()
    local input = gg.prompt({"请输入关卡ID(默认1032代表火焰山)"},{tostring(FLAME_MOUNTAIN_ID)},{"number"})
    if input == nil then
        showCloudNotify("设置","已取消",false)
        return
    end
    local newID = tonumber(input[1])
    if not newID then
        showCloudNotify("错误","请输入有效数字",false)
        return
    end
    FLAME_MOUNTAIN_ID = newID
    showCloudNotify("火焰山","关卡ID已设置为 "..newID..",请重新开启开关生效",true)
end

-- 坠龙聚怪、秒水晶
function Zuilong_Gather_On()
    if zuilong_gather_data then
        showCloudNotify("聚怪","已开启",false)
        return
    end
    gg.clearResults()
    search(2139095040,4)
    if #sj == 0 then
        showCloudNotify("聚怪","未找到聚怪数据",false)
        return
    end
    py1(1065353216,4,-8)
    py1(1065353216,4,-4)
    py1(0,4,4)
    py1(0,4,8)
    py1(0,4,12)
    xg1(1222,16,20,true)
    xg1(3563,16,16,true)
    local records = {}
    for i, v in ipairs(sj) do
        table.insert(records, {address=v.address+20, value=1222, flags=16, freeze=true})
        table.insert(records, {address=v.address+16, value=3563, flags=16, freeze=true})
    end
    zuilong_gather_data = records
    showCloudNotify("聚怪","已开启",true)
    gg.clearResults()
end

function Zuilong_Gather_Off()
    if not zuilong_gather_data then
        showCloudNotify("聚怪","未开启",false)
        return
    end
    for _, item in ipairs(zuilong_gather_data) do
        gg.removeListItems({item})
    end
    zuilong_gather_data = nil
    showCloudNotify("聚怪","已关闭",true)
end

function Zuilong_LeftKill_On()
    gg.clearResults()
    search(50000, 4)
    if #sj == 0 then
        showCloudNotify("秒左","未找到水晶血量",false)
        return
    end
    py1(1, 4, 8)
    py1(60, 4, 920)
    xg1(0, 4, -32, false)
    search(2139095040, 4)
    if #sj == 0 then
        showCloudNotify("秒左","未找到顺左数据",false)
        return
    end
    py1(1065353216, 4, -8)
    py1(1065353216, 4, -4)
    py1(0, 4, 4)
    py1(0, 4, 8)
    py1(0, 4, 12)
    xg1(529, 16, 20, false)
    xg1(882, 16, 16, false)
    showCloudNotify("秒左","已执行",true)
    gg.clearResults()
end

function Zuilong_RightKill_On()
    gg.clearResults()
    search(50000, 4)
    if #sj == 0 then
        showCloudNotify("秒右","未找到水晶血量",false)
        return
    end
    py1(1, 4, 8)
    py1(60, 4, 920)
    xg1(0, 4, -32, false)
    search(2139095040, 4)
    if #sj == 0 then
        showCloudNotify("秒右","未找到顺右数据",false)
        return
    end
    py1(1065353216, 4, -8)
    py1(1065353216, 4, -4)
    py1(0, 4, 4)
    py1(0, 4, 8)
    py1(0, 4, 12)
    xg1(530, 16, 20, false)
    xg1(6239, 16, 16, false)
    showCloudNotify("秒右","已执行",true)
    gg.clearResults()
end

-- ==================== 72变功能(特征码版 - 基于101) ====================
local _72BIAN_SEARCH = 101
local _72BIAN_OFFSET_CHECK1 = -40
local _72BIAN_CHECK1_MIN = 1
local _72BIAN_CHECK1_MAX = 130
local _72BIAN_OFFSET_CHECK2 = -36
local _72BIAN_CHECK2_VALUE = -491520
local _72BIAN_OFFSET_TARGET = -40   -- 目标地址 = 搜索结果地址 + 这个偏移

function _72Bian_Enable(targetID)
    if _72Bian_Active then
        _72Bian_Disable()
    end

    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)

    -- 搜索特征码 101
    gg.searchNumber(tostring(_72BIAN_SEARCH), gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
    local mainCount = gg.getResultsCount()
    if mainCount == 0 then
        showCloudNotify("72变", "未找到特征码 101,请确保在训练营或关卡内", false)
        gg.clearResults()
        return false
    end
    local mainResults = gg.getResults(mainCount)

    -- 批量读取两个偏移处的值
    local checkList = {}
    for i, v in ipairs(mainResults) do
        local addr = v.address
        table.insert(checkList, {address = addr + _72BIAN_OFFSET_CHECK1, flags = gg.TYPE_DWORD})
        table.insert(checkList, {address = addr + _72BIAN_OFFSET_CHECK2, flags = gg.TYPE_DWORD})
    end
    local checkValues = gg.getValues(checkList)

    -- 筛选符合条件的地址,并收集目标地址
    local targetAddrs = {}
    local idx = 1
    for i = 1, #mainResults do
        local val1 = checkValues[idx].value
        local val2 = checkValues[idx + 1].value
        idx = idx + 2
        -- 验证条件:val1 在 1~130 之间,val2 等于 -491520
        if val1 >= _72BIAN_CHECK1_MIN and val1 <= _72BIAN_CHECK1_MAX and val2 == _72BIAN_CHECK2_VALUE then
            local targetAddr = mainResults[i].address + _72BIAN_OFFSET_TARGET
            table.insert(targetAddrs, targetAddr)
        end
    end

    if #targetAddrs == 0 then
        showCloudNotify("72变", "未找到满足条件的地址(偏移-40不在1~130或-36不为-491520)", false)
        gg.clearResults()
        return false
    end

    -- 修改目标地址的值(英雄ID)
    local edits = {}
    _72Bian_Data = {}
    for _, addr in ipairs(targetAddrs) do
        local orig = gg.getValues({{address = addr, flags = gg.TYPE_DWORD}})[1].value
        table.insert(_72Bian_Data, {address = addr, flags = gg.TYPE_DWORD, originalValue = orig})
        table.insert(edits, {address = addr, flags = gg.TYPE_DWORD, value = targetID})
    end
    gg.setValues(edits)
    _72Bian_Active = true
    _72Bian_TargetID = targetID
    showCloudNotify("72变", string.format("已开启(特征码101模式),英雄ID修改为 %d,共修改 %d 处", targetID, #edits), true)
    gg.clearResults()
    return true
end

function _72Bian_Disable()
    if not _72Bian_Active then
        showCloudNotify("72变", "未开启,无需关闭", false)
        return
    end
    if #_72Bian_Data == 0 then
        _72Bian_Active = false
        showCloudNotify("72变", "无数据可恢复", false)
        return
    end
    local restoreList = {}
    for _, item in ipairs(_72Bian_Data) do
        table.insert(restoreList, {address = item.address, flags = item.flags, value = item.originalValue})
    end
    gg.setValues(restoreList)
    _72Bian_Data = {}
    _72Bian_Active = false
    showCloudNotify("72变", "已关闭,已恢复原始英雄", true)
end

function SeventyTwo_Modify(targetID)
    return _72Bian_Enable(targetID)
end

function SeventyTwo_Restore()
    _72Bian_Disable()
end

function new72Bian_set(targetID)
    if _72Bian_Active and _72Bian_TargetID == targetID then
        showCloudNotify("72变", "已是该英雄,无需重复修改", false)
        return true
    end
    if _72Bian_Active then
        _72Bian_Disable()
    end
    return _72Bian_Enable(targetID)
end

function SeventyTwo_Custom()
    local input = gg.prompt({"请输入英雄ID(数字)"}, {""}, {"number"})
    if input and input[1] then
        local id = tonumber(input[1])
        if id then
            _72Bian_TargetID = id
            if _72Bian_Active then
                _72Bian_Enable(id)
            else
                showCloudNotify("72变", "目标ID已保存为 " .. id .. ",请开启开关生效", true)
            end
        else
            showCloudNotify("72变", "输入无效", false)
        end
    end
end

function ShowHeroIDTable()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "英雄ID参考表(完整版)",
                "━━━ 初始角色 ━━━\n" ..
                "1-孙悟空(原皮)  2-唐僧  3-猪八戒  4-沙悟净\n\n" ..
                "━━━ 传说/限定英雄 ━━━\n" ..
                "40-通天教主  41-通天教主(皮肤)  51-斗战胜佛  52-斗战胜佛(皮肤)\n" ..
                "61-后羿  62-后羿(皮肤)  71-六耳猕猴  72-六耳猕猴(皮肤)\n" ..
                "80-真武大帝  81-真武大帝(皮肤)  89-东皇太一  90-东皇太一(皮肤)\n" ..
                "98-帝俊  99-帝俊(皮肤)\n\n" ..
                "━━━ 其他英雄 ━━━\n" ..
                "103-鹿  104-鹿(皮肤)  107-伏羲  108-女土蝠  109-女土蝠(皮肤)\n\n" ..
                "━━━ 使用说明 ━━━\n" ..
                "1️⃣ 必须在训练营或关卡内使用\n" ..
                "2️⃣ 孙悟空必须穿原皮肤\n" ..
                "3️⃣ 修改后切图或下一关会失效,需重新开启\n" ..
                "4️⃣ 点击【恢复原始英雄】可改回孙悟空(1)",
                "知道了")
        end)
    end)
end

function ShowSeventyTwoInstructions()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "72变功能使用说明",
                "━━━ 功能原理 ━━━\n" ..
                "通过修改内存中的英雄ID数据,实现角色替换\n\n" ..
                "━━━ 使用步骤 ━━━\n" ..
                "1️⃣ 进入训练营或任意关卡\n" ..
                "2️⃣ 孙悟空必须装备【原皮肤】(重要!)\n" ..
                "3️⃣ 点击「自定义修改」输入英雄ID\n" ..
                "   或直接点击快捷开关(如:变通天教主)\n" ..
                "4️⃣ 修改成功后立即生效\n\n" ..
                "━━━ 注意事项 ━━━\n" ..
                "⚠️ 修改后切图、下一关或死亡后会失效\n" ..
                "⚠️ 失效后重新点击开关即可\n" ..
                "⚠️ 本功能不冻结、不保存地址\n" ..
                "⚠️ 关闭脚本或重启游戏自动恢复\n" ..
                "⚠️ 部分英雄技能可能不完整,属正常现象\n\n" ..
                "━━━ 恢复方法 ━━━\n" ..
                "点击【恢复原始英雄】即可变回孙悟空(1)",
                "知道了")
        end)
    end)
end

-- 佛光美化
local DEFAULT_BUDDHA_SKILL = 13678
local JIANGMO_SKILL = 13166

function BuddhaLight_On()
    if BUDDHA_LIGHT_ACTIVE then
        showCloudNotify("佛光美化","已开启",false)
        return
    end
    gg.clearResults()
    gg.setRanges(2080896)
    gg.searchNumber("1635084391", gg.TYPE_DWORD)
    local count = gg.getResultCount()
    if count == 0 then
        showCloudNotify("佛光美化","未找到佛光数据",false)
        gg.clearResults()
        return
    end
    local results = gg.getResults(count)
    gg.clearResults()
    local filtered = {}
    local tmp = {}
    for i, v in ipairs(results) do
        table.insert(tmp, {address = v.address + 4, flags = gg.TYPE_DWORD})
    end
    tmp = gg.getValues(tmp)
    for i, val in ipairs(tmp) do
        if val.value == JIANGMO_SKILL then
            table.insert(filtered, results[i])
        end
    end
    if #filtered == 0 then
        showCloudNotify("佛光美化","未找到降魔之光技能",false)
        gg.clearResults()
        return
    end
    BUDDHA_LIGHT_DATA = {}
    for i, v in ipairs(filtered) do
        table.insert(BUDDHA_LIGHT_DATA, {address = v.address + 4, originalValue = JIANGMO_SKILL, flags = gg.TYPE_DWORD})
    end
    local modifyList = {}
    for i, item in ipairs(BUDDHA_LIGHT_DATA) do
        table.insert(modifyList, {address = item.address, flags = item.flags, value = DEFAULT_BUDDHA_SKILL})
    end
    gg.setValues(modifyList)
    BUDDHA_LIGHT_ACTIVE = true
    showCloudNotify("佛光美化","已开启(降魔→双龙)",true)
    gg.clearResults()
end

function BuddhaLight_Off()
    if not BUDDHA_LIGHT_ACTIVE then
        showCloudNotify("佛光美化","未开启",false)
        return
    end
    if not BUDDHA_LIGHT_DATA then
        showCloudNotify("佛光美化","未找到原始数据",false)
        BUDDHA_LIGHT_ACTIVE = false
        return
    end
    local restoreList = {}
    for i, item in ipairs(BUDDHA_LIGHT_DATA) do
        table.insert(restoreList, {address = item.address, flags = item.flags, value = item.originalValue})
    end
    gg.setValues(restoreList)
    BUDDHA_LIGHT_DATA = nil
    BUDDHA_LIGHT_ACTIVE = false
    showCloudNotify("佛光美化","已关闭",true)
end

function BuddhaLight_Custom()
    local input = gg.prompt({"请输入技能代码(双龙戏珠13678,琉璃法环14190,菩提圣印14446,万法归宗14702)"},{tostring(DEFAULT_BUDDHA_SKILL)},{"number"})
    if input == nil then
        showCloudNotify("自定义","已取消",false)
        return
    end
    local newCode = tonumber(input[1])
    if not newCode then
        showCloudNotify("错误","请输入有效数字",false)
        return
    end
    if not BUDDHA_LIGHT_ACTIVE then
        showCloudNotify("错误","请先开启佛光美化",false)
        return
    end
    if not BUDDHA_LIGHT_DATA then
        showCloudNotify("错误","未找到佛光数据",false)
        return
    end
    local modifyList = {}
    for i, item in ipairs(BUDDHA_LIGHT_DATA) do
        table.insert(modifyList, {address = item.address, flags = item.flags, value = newCode})
    end
    gg.setValues(modifyList)
    showCloudNotify("佛光美化","技能已自定义为"..newCode,true)
end

-- 无限跳跃
function InfiniteJump_On()
    if INFINITE_JUMP_ACTIVE then
        showCloudNotify("无限跳跃","已开启",false)
        return
    end
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber(750, 4)
    local count = gg.getResultCount()
    if count == 0 then
        showCloudNotify("无限跳跃","未找到特征",false)
        gg.clearResults()
        return
    end
    local results = gg.getResults(count)
    local addrs = {}
    for _, r in ipairs(results) do
        addrs[#addrs + 1] = {address = r.address - 32, flags = 4}
    end
    local values = gg.getValues(addrs)
    local filtered = {}
    for i, v in ipairs(values) do
        if v.value == 10 then
            filtered[#filtered + 1] = results[i]
        end
    end
    if #filtered == 0 then
        showCloudNotify("无限跳跃","特征匹配失败",false)
        gg.clearResults()
        return
    end
    INFINITE_JUMP_LIST = {}
    local freezeItems = {}
    for _, addrInfo in ipairs(filtered) do
        local targetAddr = addrInfo.address - 56
        local item = {address = targetAddr, flags = 4, value = 0, freeze = true}
        freezeItems[#freezeItems + 1] = item
        INFINITE_JUMP_LIST[#INFINITE_JUMP_LIST + 1] = item
    end
    gg.addListItems(freezeItems)
    INFINITE_JUMP_ACTIVE = true
    showCloudNotify("无限跳跃","已开启(冻结"..#freezeItems.."处)",true)
    gg.clearResults()
end

function InfiniteJump_Off()
    if not INFINITE_JUMP_ACTIVE then
        showCloudNotify("无限跳跃","未开启",false)
        return
    end
    if INFINITE_JUMP_LIST then
        for _, item in ipairs(INFINITE_JUMP_LIST) do
            gg.removeListItems({item})
        end
        INFINITE_JUMP_LIST = nil
    end
    INFINITE_JUMP_ACTIVE = false
    showCloudNotify("无限跳跃","已关闭",true)
end

-- 定怪功能
function MonsterFix_Once()
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber(750, 4)
    local count = gg.getResultCount()
    if count == 0 then
        gg.clearResults()
        return
    end
    local results = gg.getResults(count)
    local validAddrs = {}
    for _, v in ipairs(results) do
        local val = gg.getValues({{address = v.address - 32, flags = gg.TYPE_DWORD}})[1].value
        if val == 10 then
            val = gg.getValues({{address = v.address + 4, flags = gg.TYPE_DWORD}})[1].value
            if val == -491520 then
                val = gg.getValues({{address = v.address + 132, flags = gg.TYPE_DWORD}})[1].value
                if val == -425984 then
                    table.insert(validAddrs, v.address)
                end
            end
        end
    end
    if #validAddrs == 0 then
        gg.clearResults()
        return
    end
    local writeList = {}
    for _, addr in ipairs(validAddrs) do
        table.insert(writeList, {address = addr + 496, flags = gg.TYPE_DWORD, value = 1})
    end
    gg.setValues(writeList)
    gg.clearResults()
end

function StartMonsterFixLoop()
    if MONSTER_FIX_ACTIVE then
        showCloudNotify("定怪","循环已在运行",false)
        return
    end
    MONSTER_FIX_ACTIVE = true
    showCloudNotify("定怪","已开启,每"..MONSTER_FIX_INTERVAL.."秒执行",true)
    local loop_thread = function()
        while MONSTER_FIX_ACTIVE do
            MonsterFix_Once()
            if MONSTER_FIX_ACTIVE then
                gg.sleep(MONSTER_FIX_INTERVAL * 1000)
            end
        end
        showCloudNotify("定怪","已停止",true)
    end
    pcall(loop_thread)
end

function StopMonsterFixLoop()
    if not MONSTER_FIX_ACTIVE then
        showCloudNotify("定怪","未运行",false)
        return
    end
    MONSTER_FIX_ACTIVE = false
    showCloudNotify("定怪","已关闭",true)
end


-- ==================== 活动专区 ====================
-- 打地鼠增加时长(原极速版,正式版)
function WhackAMole_On()
    if WHACK_A_MOLE_DATA then
        showCloudNotify("打地鼠增加时长", "已开启,无需重复操作", false)
        return
    end

    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)

    local searchValue = -1829587348619263
    local verifyValue = -2111062325329920
    local modifyValue = -8000

    gg.searchNumber(tostring(searchValue), gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
    local results = gg.getResults(9999990)
    if #results == 0 then
        showCloudNotify("打地鼠增加时长", "未找到匹配值", false)
        gg.clearResults()
        return
    end

    local saveList = {}
    local modifyList = {}

    for _, result in ipairs(results) do
        local verifyAddr = result.address + 40
        local verifyVal = gg.getValues({{address = verifyAddr, flags = gg.TYPE_QWORD}})[1].value
        if verifyVal == verifyValue then
            local targetAddr = result.address + 64
            local currentVal = gg.getValues({{address = targetAddr, flags = gg.TYPE_DWORD}})[1].value

            if currentVal > 1 and currentVal < 2000 then
                table.insert(saveList, {
                    address = targetAddr,
                    flags = gg.TYPE_DWORD,
                    originalValue = currentVal
                })
                table.insert(modifyList, {
                    address = targetAddr,
                    flags = gg.TYPE_DWORD,
                    value = modifyValue
                })
            end
        end
    end

    gg.clearResults()

    if #modifyList == 0 then
        showCloudNotify("打地鼠增加时长", "验证通过但无符合条件地址(需 >1 且 <2000)", false)
        return
    end

    gg.setValues(modifyList)
    WHACK_A_MOLE_DATA = saveList
    showCloudNotify("打地鼠增加时长", "已开启,修改 " .. #modifyList .. " 处(不冻结)", true)
end

function WhackAMole_Off()
    if not WHACK_A_MOLE_DATA then
        showCloudNotify("打地鼠增加时长", "未开启,无需关闭", false)
        return
    end

    local restoreList = {}
    for _, item in ipairs(WHACK_A_MOLE_DATA) do
        table.insert(restoreList, {
            address = item.address,
            flags = item.flags,
            value = item.originalValue
        })
    end
    gg.setValues(restoreList)
    WHACK_A_MOLE_DATA = nil
    showCloudNotify("打地鼠增加时长", "已关闭,已恢复原始值", true)
end

-- ==================== v1.8 新增:显示宽屏按键(不冻结) ====================
function WideScreen_On()
    if WIDE_SCREEN_DATA then
        showCloudNotify("显示宽屏按键", "已开启,无需重复操作", false)
        return
    end

    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber('904136849', gg.TYPE_DWORD)
    local resultCount = gg.getResultCount()
    if resultCount == 0 then
        showCloudNotify("显示宽屏按键", "未找到任何结果,请确保在坠龙战斗内开启", false)
        return
    end

    local results = gg.getResults(resultCount)
    local modifyList = {}
    local recordList = {}

    for i, v in ipairs(results) do
        local targetAddr = v.address + 56
        local orig = gg.getValues({{address = targetAddr, flags = gg.TYPE_DWORD}})[1].value
        table.insert(recordList, {address = targetAddr, flags = gg.TYPE_DWORD, originalValue = orig})
        table.insert(modifyList, {address = targetAddr, flags = gg.TYPE_DWORD, value = 257})
    end

    if #modifyList == 0 then
        showCloudNotify("显示宽屏按键", "未生成有效修改项", false)
        return
    end

    gg.setValues(modifyList)
    WIDE_SCREEN_DATA = recordList
    showCloudNotify("显示宽屏按键", "已开启,共修改 " .. #modifyList .. " 处", true)
    gg.clearResults()
end

function WideScreen_Off()
    if not WIDE_SCREEN_DATA then
        showCloudNotify("显示宽屏按键", "未开启,无需关闭", false)
        return
    end

    local restoreList = {}
    for _, item in ipairs(WIDE_SCREEN_DATA) do
        table.insert(restoreList, {address = item.address, flags = item.flags, value = item.originalValue})
    end
    gg.setValues(restoreList)

    WIDE_SCREEN_DATA = nil
    showCloudNotify("显示宽屏按键", "已关闭,数值已恢复", true)
end

-- ==================== v1.9 新增:显示变速按键(冒险关卡) ====================
function SpeedButton_On()
    if SPEED_BUTTON_DATA then
        showCloudNotify("显示变速按键", "已开启,无需重复操作", false)
        return
    end

    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber('848467071', gg.TYPE_DWORD)
    local resultCount = gg.getResultCount()
    if resultCount == 0 then
        showCloudNotify("显示变速按键", "未找到任何结果,请确保在冒险关卡内开启", false)
        return
    end

    local results = gg.getResults(resultCount)
    local modifyList = {}
    local recordList = {}

    for i, v in ipairs(results) do
        local targetAddr = v.address + 68
        local orig = gg.getValues({{address = targetAddr, flags = gg.TYPE_DWORD}})[1].value
        table.insert(recordList, {address = targetAddr, flags = gg.TYPE_DWORD, originalValue = orig})
        table.insert(modifyList, {address = targetAddr, flags = gg.TYPE_DWORD, value = 257})
    end

    if #modifyList == 0 then
        showCloudNotify("显示变速按键", "未生成有效修改项", false)
        return
    end

    gg.setValues(modifyList)
    SPEED_BUTTON_DATA = recordList
    showCloudNotify("显示变速按键", "已开启,共修改 " .. #modifyList .. " 处", true)
    gg.clearResults()
end

function SpeedButton_Off()
    if not SPEED_BUTTON_DATA then
        showCloudNotify("显示变速按键", "未开启,无需关闭", false)
        return
    end

    local restoreList = {}
    for _, item in ipairs(SPEED_BUTTON_DATA) do
        table.insert(restoreList, {address = item.address, flags = item.flags, value = item.originalValue})
    end
    gg.setValues(restoreList)

    SPEED_BUTTON_DATA = nil
    showCloudNotify("显示变速按键", "已关闭,数值已恢复", true)
end

-- ==================== 刷文碟(单次执行,不保存列表) ====================
function ShuaWenDie_On()
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber('4294541312', gg.TYPE_QWORD)
    local count = gg.getResultCount()
    if count == 0 then
        showCloudNotify("刷文碟", "未找到特征值 4294541312", false)
        gg.clearResults()
        return
    end

    local results = gg.getResults(count)
    local modified = 0

    for _, v in ipairs(results) do
        local addr = v.address

        local check1 = gg.getValues({{address = addr - 500, flags = gg.TYPE_QWORD}})
        if check1[1].value == -2111062325329920 then
            local check2 = gg.getValues({{address = addr + 440, flags = gg.TYPE_QWORD}})
            if check2[1].value == 8589443072 then
                gg.setValues({{address = addr + 436, flags = gg.TYPE_DWORD, value = 16}})
                modified = modified + 1
            end
        end
    end

    gg.clearResults()

    if modified > 0 then
        showCloudNotify("刷文碟", "已修改 " .. modified .. " 处(单次执行,无需关闭)", true)
    else
        showCloudNotify("刷文碟", "没有符合条件的地址(验证1或2不通过)", false)
    end
end

function ShuaWenDie_Off()
    showCloudNotify("刷文碟", "此功能为单次执行,无需关闭", false)
end

-- ==================== v2.3 新增:全员无敌(开关式) ====================
function AllInvincible_On()
    if ALL_INVINCIBLE_DATA then
        showCloudNotify("全员无敌", "已开启,无需重复操作", false)
        return
    end
    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber(750, gg.TYPE_DWORD)
    if gg.getResultCount() == 0 then
        showCloudNotify("全员无敌", "未找到特征数据,请确保在关卡内", false)
        gg.clearResults()
        return
    end
    local results = gg.getResults(gg.getResultCount())
    local addrs = {}
    for i, v in ipairs(results) do
        addrs[i] = { address = v.address + 736, flags = gg.TYPE_DWORD }
    end
    local values = gg.getValues(addrs)
    local validResults = {}
    for i, val in ipairs(values) do
        if val.value == 1 then
            table.insert(validResults, results[i])
        end
    end
    if #validResults == 0 then
        showCloudNotify("全员无敌", "未找到符合条件的地址(偏移+736处不为1)", false)
        gg.clearResults()
        return
    end
    local savedData = {}
    local modifyList = {}
    for _, res in ipairs(validResults) do
        local addr = res.address + 736
        local orig = gg.getValues({{ address = addr, flags = gg.TYPE_DWORD }})[1].value
        table.insert(savedData, { address = addr, originalValue = orig, flags = gg.TYPE_DWORD })
        table.insert(modifyList, { address = addr, flags = gg.TYPE_DWORD, value = 2 })
    end
    gg.setValues(modifyList)
    ALL_INVINCIBLE_DATA = savedData
    showCloudNotify("全员无敌", "已开启,修改了 " .. #modifyList .. " 处", true)
    gg.clearResults()
end

function AllInvincible_Off()
    if not ALL_INVINCIBLE_DATA then
        showCloudNotify("全员无敌", "未开启,无需关闭", false)
        return
    end
    if #ALL_INVINCIBLE_DATA > 0 then
        local restoreList = {}
        for _, item in ipairs(ALL_INVINCIBLE_DATA) do
            table.insert(restoreList, { address = item.address, flags = item.flags, value = item.originalValue })
        end
        gg.setValues(restoreList)
        showCloudNotify("全员无敌", "已关闭,恢复了 " .. #restoreList .. " 处", true)
    else
        showCloudNotify("全员无敌", "没有可恢复的数据", false)
    end
    ALL_INVINCIBLE_DATA = nil
    gg.clearResults()
end

-- ==================== v2.6 全员秒杀无冷却(循环模式,500ms) ====================
function AllSecondKill_On()
    if ALL_SECOND_KILL_LOOP_ACTIVE then
        showCloudNotify("全员秒杀无冷却", "循环已在运行,无需重复开启", false)
        return
    end

    ALL_SECOND_KILL_LOOP_ACTIVE = true
    showCloudNotify("全员秒杀无冷却", "循环已启动,每500ms执行一次", true)

    local loop_thread = function()
        while ALL_SECOND_KILL_LOOP_ACTIVE do
            gg.clearResults()
            gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)

            gg.searchNumber("30000", gg.TYPE_DWORD)
            if gg.getResultCount() > 0 then
                local results = gg.getResults(gg.getResultCount())
                local validAddrs = {}

                for _, v in ipairs(results) do
                    local chk = gg.getValues({{address = v.address + 8, flags = gg.TYPE_DWORD}})
                    if chk[1].value == 20000 then
                        table.insert(validAddrs, v.address)
                    end
                end

                if #validAddrs > 0 then
                    local modifyList = {}
                    for _, addr in ipairs(validAddrs) do
                        table.insert(modifyList, {address = addr - 112, flags = gg.TYPE_DWORD, value = 9999})
                        table.insert(modifyList, {address = addr - 128, flags = gg.TYPE_DWORD, value = 1})
                    end
                    gg.setValues(modifyList)
                end
            end
            gg.clearResults()

            if ALL_SECOND_KILL_LOOP_ACTIVE then
                gg.sleep(500)
            end
        end
        showCloudNotify("全员秒杀无冷却", "循环已停止", true)
    end

    pcall(loop_thread)
end

function AllSecondKill_Off()
    if not ALL_SECOND_KILL_LOOP_ACTIVE then
        showCloudNotify("全员秒杀无冷却", "循环未运行,无需关闭", false)
        return
    end

    ALL_SECOND_KILL_LOOP_ACTIVE = false
    showCloudNotify("全员秒杀无冷却", "正在停止循环...", false)
end

-- ==================== 竞技专区 ====================
-- 特征码模式函数(左入坑-小数组)
function LeftRoleFeature_On()
    if leftRoleFeatureData then
        showCloudNotify("左边角色入坑", "特征码模式已开启,无需重复", false)
        return true
    end

    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber("2139095040", gg.TYPE_DWORD)
    local count = gg.getResultCount()
    if count == 0 then
        return false
    end

    local results = gg.getResults(math.min(count, 2000))
    local validEntries = {}

    local readList = {}
    for i, v in ipairs(results) do
        local addr = v.address
        table.insert(readList, {address = addr + 0x3C, flags = gg.TYPE_DWORD})
        table.insert(readList, {address = addr + 0x34, flags = gg.TYPE_DWORD})
        table.insert(readList, {address = addr + 0x10, flags = gg.TYPE_DWORD})
    end
    local allVals = gg.getValues(readList)
    if not allVals then return false end

    local idx = 1
    for i = 1, #results do
        local sub1 = allVals[idx].value
        local sub2 = allVals[idx+1].value
        local target = allVals[idx+2].value
        idx = idx + 3
        if sub1 == -2147483648 and sub2 == 1065353216 then
            table.insert(validEntries, {
                address = results[i].address + 0x10,
                currentValue = target
            })
        end
    end

    gg.clearResults()
    if #validEntries == 0 then return false end

    table.sort(validEntries, function(a, b) return a.currentValue < b.currentValue end)
    local total = #validEntries
    local splitIndex = math.floor(total / 2)
    local smallGroup = {}
    for i = 1, splitIndex do
        table.insert(smallGroup, validEntries[i])
    end
    if #smallGroup == 0 then return false end

    local modifyList = {}
    local recordList = {}
    for _, entry in ipairs(smallGroup) do
        table.insert(recordList, {
            address = entry.address,
            flags = gg.TYPE_DWORD,
            originalValue = entry.currentValue
        })
        table.insert(modifyList, {
            address = entry.address,
            flags = gg.TYPE_DWORD,
            value = 1145111210,
            freeze = true
        })
    end

    gg.setValues(modifyList)
    gg.addListItems(modifyList)
    leftRoleFeatureData = recordList
    showCloudNotify("左边角色入坑", string.format("特征码模式(小数组)已开启,修改 %d 处并冻结", #modifyList), true)
    return true
end

function LeftRoleFeature_Off()
    if not leftRoleFeatureData then
        return
    end

    local restoreList = {}
    for _, item in ipairs(leftRoleFeatureData) do
        table.insert(restoreList, {
            address = item.address,
            flags = item.flags,
            value = item.originalValue,
            freeze = false
        })
    end
    gg.setValues(restoreList)

    local currentList = gg.getListItems()
    for _, item in ipairs(leftRoleFeatureData) do
        for _, li in ipairs(currentList) do
            if li.address == item.address and li.flags == item.flags then
                gg.removeListItems({li})
                break
            end
        end
    end

    leftRoleFeatureData = nil
    showCloudNotify("左边角色入坑", "特征码模式已关闭,已恢复原值并移除冻结", true)
end

-- 特征码模式函数(右入坑-大数组)
function RightRoleFeature_On()
    if rightRoleFeatureData then
        showCloudNotify("右边角色入坑", "特征码模式已开启,无需重复", false)
        return true
    end

    gg.clearResults()
    gg.setRanges(gg.REGION_C_ALLOC | gg.REGION_OTHER)
    gg.searchNumber("2139095040", gg.TYPE_DWORD)
    local count = gg.getResultCount()
    if count == 0 then
        return false
    end

    local results = gg.getResults(math.min(count, 2000))
    local validEntries = {}

    local readList = {}
    for i, v in ipairs(results) do
        local addr = v.address
        table.insert(readList, {address = addr + 0x3C, flags = gg.TYPE_DWORD})
        table.insert(readList, {address = addr + 0x34, flags = gg.TYPE_DWORD})
        table.insert(readList, {address = addr + 0x10, flags = gg.TYPE_DWORD})
    end
    local allVals = gg.getValues(readList)
    if not allVals then return false end

    local idx = 1
    for i = 1, #results do
        local sub1 = allVals[idx].value
        local sub2 = allVals[idx+1].value
        local target = allVals[idx+2].value
        idx = idx + 3
        if sub1 == -2147483648 and sub2 == 1065353216 then
            table.insert(validEntries, {
                address = results[i].address + 0x10,
                currentValue = target
            })
        end
    end

    gg.clearResults()
    if #validEntries == 0 then return false end

    table.sort(validEntries, function(a, b) return a.currentValue < b.currentValue end)
    local total = #validEntries
    local splitIndex = math.floor(total / 2)
    local bigGroup = {}
    for i = splitIndex + 1, total do
        table.insert(bigGroup, validEntries[i])
    end
    if #bigGroup == 0 then return false end

    local modifyList = {}
    local recordList = {}
    for _, entry in ipairs(bigGroup) do
        table.insert(recordList, {
            address = entry.address,
            flags = gg.TYPE_DWORD,
            originalValue = entry.currentValue
        })
        table.insert(modifyList, {
            address = entry.address,
            flags = gg.TYPE_DWORD,
            value = 1145111210,
            freeze = true
        })
    end

    gg.setValues(modifyList)
    gg.addListItems(modifyList)
    rightRoleFeatureData = recordList
    showCloudNotify("右边角色入坑", string.format("特征码模式(大数组)已开启,修改 %d 处并冻结", #modifyList), true)
    return true
end

function RightRoleFeature_Off()
    if not rightRoleFeatureData then
        return
    end

    local restoreList = {}
    for _, item in ipairs(rightRoleFeatureData) do
        table.insert(restoreList, {
            address = item.address,
            flags = item.flags,
            value = item.originalValue,
            freeze = false
        })
    end
    gg.setValues(restoreList)

    local currentList = gg.getListItems()
    for _, item in ipairs(rightRoleFeatureData) do
        for _, li in ipairs(currentList) do
            if li.address == item.address and li.flags == item.flags then
                gg.removeListItems({li})
                break
            end
        end
    end

    rightRoleFeatureData = nil
    showCloudNotify("右边角色入坑", "特征码模式已关闭,已恢复原值并移除冻结", true)
end

-- 指针模式函数(左入坑)
function LeftRolePointer_On()
    local module_name = "libcocos2djs.so"
    local offsets = {0x8B50, 0x40, 0x38, 0x8, 0x0, 0x28}
    local target_value = 1145111210
    local val_flag = gg.TYPE_DWORD

    local ranges = gg.getRangesList(module_name)
    local bss_start = nil
    if ranges and #ranges > 0 then
        for _, v in ipairs(ranges) do
            if string.find(v.name, "bss") then
                bss_start = v.start
                break
            end
        end
    end

    if bss_start then
        local is_64bit = false
        for _, v in ipairs(ranges) do
            if string.find(v.name, "64") or v.start > 0xFFFFFFFF then
                is_64bit = true
                break
            end
        end
        local ptr_flag = is_64bit and gg.TYPE_QWORD or gg.TYPE_DWORD

        local current_addr = bss_start + offsets[1]
        local pointer_ok = true
        for i = 2, #offsets do
            local result = gg.getValues({{address = current_addr, flags = ptr_flag}})
            if not result or not result[1] then
                pointer_ok = false
                break
            end
            local ptr = result[1].value
            if ptr == 0 or ptr == nil then
                pointer_ok = false
                break
            end
            current_addr = ptr + offsets[i]
        end

        if pointer_ok then
            local orig = gg.getValues({{address = current_addr, flags = val_flag}})[1].value
            leftRoleData = {address = current_addr, flags = val_flag, originalValue = orig}
            local mod = {address = current_addr, flags = val_flag, value = target_value, freeze = true}
            gg.setValues({mod})
            gg.addListItems({mod})
            showCloudNotify("左边角色入坑", "指针模式已修改", true)
            return true
        end
    end
    return false
end

-- 指针模式函数(右入坑)
function RightRolePointer_On()
    local module_name = "libcocos2djs.so"
    local offsets = {0x8B50, 0x40, 0x38, 0x8, 0x8, 0x28}
    local target_value = 1145111210
    local val_flag = gg.TYPE_DWORD

    local ranges = gg.getRangesList(module_name)
    local bss_start = nil
    if ranges and #ranges > 0 then
        for _, v in ipairs(ranges) do
            if string.find(v.name, "bss") then
                bss_start = v.start
                break
            end
        end
    end

    if bss_start then
        local is_64bit = false
        for _, v in ipairs(ranges) do
            if string.find(v.name, "64") or v.start > 0xFFFFFFFF then
                is_64bit = true
                break
            end
        end
        local ptr_flag = is_64bit and gg.TYPE_QWORD or gg.TYPE_DWORD

        local current_addr = bss_start + offsets[1]
        local pointer_ok = true
        for i = 2, #offsets do
            local result = gg.getValues({{address = current_addr, flags = ptr_flag}})
            if not result or not result[1] then
                pointer_ok = false
                break
            end
            local ptr = result[1].value
            if ptr == 0 or ptr == nil then
                pointer_ok = false
                break
            end
            current_addr = ptr + offsets[i]
        end

        if pointer_ok then
            local orig = gg.getValues({{address = current_addr, flags = val_flag}})[1].value
            rightRoleData = {address = current_addr, flags = val_flag, originalValue = orig}
            local mod = {address = current_addr, flags = val_flag, value = target_value, freeze = true}
            gg.setValues({mod})
            gg.addListItems({mod})
            showCloudNotify("右边角色入坑", "指针模式已修改", true)
            return true
        end
    end
    return false
end

-- 主开关函数(根据模式变量执行)
function LeftRoleEnter_On()
    local executed = false
    if PC_MODE_ENABLED then
        if LeftRoleFeature_On() then executed = true end
    end
    if MOBILE_MODE_ENABLED then
        if LeftRolePointer_On() then executed = true end
    end
    if executed then
        showCloudNotify("左边角色入坑", "已执行选中的搜索模式", true)
    else
        showCloudNotify("左边角色入坑", "未找到有效修改,请检查开关或环境", false)
    end
end

function LeftRoleEnter_Off()
    local restored = false

    if leftRoleData then
        gg.setValues({{address = leftRoleData.address, flags = leftRoleData.flags, value = leftRoleData.originalValue, freeze = false}})

        local currentList = gg.getListItems()
        for _, li in ipairs(currentList) do
            if li.address == leftRoleData.address and li.flags == leftRoleData.flags then
                gg.removeListItems({li})
                break
            end
        end

        leftRoleData = nil
        restored = true
    end

    if leftRoleFeatureData then
        LeftRoleFeature_Off()
        restored = true
    end

    if restored then
        showCloudNotify("左边角色入坑", "已关闭,所有修改已恢复并移除冻结", true)
    else
        showCloudNotify("左边角色入坑", "未开启,无需关闭", false)
    end
end

function RightRoleEnter_On()
    local executed = false
    if PC_MODE_ENABLED then
        if RightRoleFeature_On() then executed = true end
    end
    if MOBILE_MODE_ENABLED then
        if RightRolePointer_On() then executed = true end
    end
    if executed then
        showCloudNotify("右边角色入坑", "已执行选中的搜索模式", true)
    else
        showCloudNotify("右边角色入坑", "未找到有效修改,请检查开关或环境", false)
    end
end

function RightRoleEnter_Off()
    local restored = false

    if rightRoleData then
        gg.setValues({{address = rightRoleData.address, flags = rightRoleData.flags, value = rightRoleData.originalValue, freeze = false}})

        local currentList = gg.getListItems()
        for _, li in ipairs(currentList) do
            if li.address == rightRoleData.address and li.flags == rightRoleData.flags then
                gg.removeListItems({li})
                break
            end
        end

        rightRoleData = nil
        restored = true
    end

    if rightRoleFeatureData then
        RightRoleFeature_Off()
        restored = true
    end

    if restored then
        showCloudNotify("右边角色入坑", "已关闭,所有修改已恢复并移除冻结", true)
    else
        showCloudNotify("右边角色入坑", "未开启,无需关闭", false)
    end
end

-- ==================== 竞技专区查看详细说明 ====================
function ShowJingJiInstructions()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "竞技专区使用说明",
                "━━━ 左边角色入坑 ━━━\n" ..
                "进去后再开\n" ..
                "开启后左边角色掉入坑。\n\n" ..
                "━━━ 右边角色入坑 ━━━\n" ..
                "进去后再开\n" ..
                "开启后右边角色掉入坑。\n\n" ..
                "━━━ 模式切换 ━━━\n" ..
                "通过上方复选框选择「电脑模式」或「手机模式」\n" ..
                "电脑模式=电脑上用,手机模式=手机上用\n\n" ..
                "━━━ 全员秒杀无冷却 ━━━\n" ..
                "循环模式:开启后每隔500ms自动修改,关闭停止。")
        end)
    end)
end

-- ==================== 使用说明(原有) ====================
function ShowWukongInstructions()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "悟空功能说明",
                "秒杀在准备战斗时开启,无敌在地图内开启,新秒杀进入战斗后开\n" ..
                "强普技能替换(开关式):开启后替换普攻为指定技能代码(默认8660),可自定义。",
                "知道了")
        end)
    end)
end

function ShowFaBaoInstructions()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "法宝秒怪说明",
                "装备对应法宝后点击按钮即可,一局一开",
                "知道了")
        end)
    end)
end

function ShowZuilongInstructions()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "坠龙之地说明",
                "模型透视:拖动地图可见敌人模型\n秒水晶:秒左边/右边水晶\n聚怪:所有怪物聚集在龙坑\n" ..
                "穿图:分机效果\n宽屏按键:进坠龙战斗后开(训练营无效),开启后屏幕下方会多出一个宽屏缩放按键\n" ..
                "法宝无冷却\n技能无蓝耗+无冷却(合并开关)\n坠龙角色无敌\n" ..
                "72变改英雄:训练营使用,悟空必须带原皮\n内购三生锤:价格变为-999999\n" ..
                "刷成就:修改击杀数和助攻数,用来刷mvp和助攻的成就,不会分机",
                "知道了")
        end)
    end)
end

function ShowInstantPassInstructions()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "冒险专区",
                "秒过功能:只能过部分主线,特殊地形\n" ..
                "猴子无敌秒:悟空带分身被动,开启后猴子无法被攻击,最后一次普攻秒全图\n" ..
                "通天神猴:准备战斗界面开启,开启后全图生效\n" ..
                "悟空强普替换:悟空带分身被动,默认8660,伏羲大招,悟空最后一次普攻触发\n" ..
                "全员技能无冷却:图内开,开启后全员技能和法宝无冷却\n" ..
                "定怪:图内图外都可以开,开启后怪物不会攻击\n" ..
                "全员无敌:开关式,在关卡内开启,令所有角色(包括敌人?)无敌,适用于需要全员生存的场景。\n\n" ..
                "━━━ 全员秒杀无冷却 ━━━\n" ..
                "循环模式:开启后每隔500ms自动搜索并修改,关闭停止。")
        end)
    end)
end

function ShowAdventureInstructions()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "无视地形秒过说明",
                "无视地形秒过能秒过全部主线\n" ..
                "直接开\n" ..
                "支持元素、镇妖塔、试炼房等\n\n" ..
                "⚡增强版新特性:必定触发入侵奖励",
                "知道了")
        end)
    end)
end

function ShowEntertainmentInstructions()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "娱乐功能说明",
                "游戏加速用于活动\n全局加速过检测稳定\n佛光美化(降魔之光改双龙戏珠)\n" ..
                "无限跳跃(关卡内开启后可以无限跳跃)\n火焰山替换主线关卡:双人组队替换关卡,请在组队界面再开启\n" ..
                "显示变速按键:冒险关卡内开启,显示变速按钮\n" ..
                "GM模式:开启后进入GM状态\n" ..
                "卖道具:自定义输入值后,自动写入(输入值-1)到道具价格\n" ..
                "视奸模式(单次执行):点击开启后,执行一次修改,实现查看陌生人状态、可切磋、强制私聊效果",
                "知道了")
        end)
    end)
end

function ShowGeneralInstructions()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "脚本使用说明",
                "造梦西游外传 v2.8(新增卖道具功能)\n适配 iQOO、vivo 等直装设备\n" ..
                "功能分页:公告、悬浮窗功能、秒过功能、冒险专区、竞技专区、法宝功能、坠龙之地、活动专区、娱乐功能、万能修改、设置\n" ..
                "请勿在竞技模式下使用",
                "知道了")
        end)
    end)
end

-- ==================== 修改体力值(开关式) ====================
function PoolEnergy_On()
    if POOL_ENERGY_ADDRS and #POOL_ENERGY_ADDRS > 0 then
        showCloudNotify("修改体力值", "已开启,无需重复", false)
        return
    end

    gg.clearResults()
    gg.setRanges(gg.REGION_OTHER)
    gg.searchNumber("50~60", gg.TYPE_DWORD)
    local resultCount = gg.getResultsCount()
    if resultCount == 0 then
        showCloudNotify("修改体力值", "未找到匹配数值(50~60)", false)
        return
    end

    local results = gg.getResults(resultCount)
    if not results or #results == 0 then
        showCloudNotify("修改体力值", "获取结果失败", false)
        return
    end

    local readList = {}
    for i, v in ipairs(results) do
        table.insert(readList, {address = v.address - 4, flags = gg.TYPE_DWORD})
        table.insert(readList, {address = v.address + 4, flags = gg.TYPE_DWORD})
    end
    local readValues = gg.getValues(readList)
    if not readValues then
        showCloudNotify("修改体力值", "读取内存失败", false)
        return
    end

    local modifyList = {}
    local addrList = {}
    for i = 1, #results do
        local idx1 = (i - 1) * 2 + 1
        local idx2 = (i - 1) * 2 + 2
        local val1 = readValues[idx1]
        local val2 = readValues[idx2]
        if val1 and val2 then
            local check1 = val1.value
            local check2 = val2.value
            if check1 >= -262050 and check1 <= -200000 and check2 == -491520 then
                local targetAddr = results[i].address
                table.insert(modifyList, {address = targetAddr, flags = gg.TYPE_DWORD, value = 9999})
                table.insert(addrList, {address = targetAddr, flags = gg.TYPE_DWORD})
            end
        end
    end

    if #modifyList == 0 then
        showCloudNotify("修改体力值", "未找到完全符合偏移条件的地址", false)
        return
    end

    local setResult = gg.setValues(modifyList)
    if setResult then
        POOL_ENERGY_ADDRS = addrList
        showCloudNotify("修改体力值", "已开启,修改 " .. #modifyList .. " 处为 9999", true)
    else
        showCloudNotify("修改体力值", "写入失败,请检查权限", false)
    end
    gg.clearResults()
end

function PoolEnergy_Off()
    if not POOL_ENERGY_ADDRS or #POOL_ENERGY_ADDRS == 0 then
        showCloudNotify("修改体力值", "未开启,无需关闭", false)
        return
    end

    local restoreList = {}
    for _, item in ipairs(POOL_ENERGY_ADDRS) do
        table.insert(restoreList, {address = item.address, flags = item.flags, value = 0})
    end
    gg.setValues(restoreList)
    POOL_ENERGY_ADDRS = nil
    showCloudNotify("修改体力值", "已关闭,所有地址改回 0", true)
end

-- ==================== 更新后的公告(ShowNotice) ====================
function ShowNotice()
    luajava.runOnUiThread(function()
        pcall(function()
            AlGuiDialogBox.showTextDiaLog(context, "公告",
                "造梦西游外传多功能脚本 v2.8\n\n✨ 更新 v2.8:\n" ..
                "✅ 新增「卖道具」功能(娱乐功能分页)\n" ..
                "✅ 自定义输入数值,自动写入(输入值-1)\n" ..
                "✅ 泳池修改重构\n" ..
                "✅ 新增「修改体力值」开关(活动专区)\n" ..
                "✅ 新增「泳池二合一」总开关(活动专区),一键同时执行体力+分数修改\n" ..
                "✅ 优化使用说明\n\n" ..
                "🔧 其他功能保持稳定",
                "知道了")
        end)
    end)
end

-- 自动过检测
function AutoBypass()
    gg.clearResults()
    gg.setRanges(gg.REGION_OTHER)
    gg.searchNumber("1749250921;7627109", gg.TYPE_DWORD)
    local count = gg.getResultCount()
    if count == 0 then
        showCloudNotify("自动过检测","未找到特征值",false)
        return
    end
    local results = gg.getResults(count)
    for i = 1, #results do
        results[i].value = 0
        results[i].freeze = false
    end
    gg.setValues(results)
    gg.clearResults()
    showCloudNotify("自动过检测","已执行,修改 "..count.." 个值",true)
end

-- ==================== 更新后的启动弹窗公告(MaterialAlert) ====================
local function MaterialAlert()
    local alertBuilder = MaterialAlertDialogBuilder(context)
    alertBuilder.setTitle("公告")
    alertBuilder.setMessage([[
造梦西游外传 v2.8 (64位流畅版) - 新增卖道具功能

🌟 核心优点:更流畅、更稳定
🔧 专为64位游戏优化,运行丝滑
✨ 悬浮窗功能:秒左、秒右、透视、聚怪、穿图
✨ 泳池分数修改:开启后直接变成800分
✨ 新增「修改体力值」:开启改9999,关闭改0
✨ 新增「泳池二合一」总开关(活动专区)

请勿破坏游戏平衡
]])
    alertBuilder.setPositiveButton("确定")
    local LayoutParams = luajava.bindClass('android.view.WindowManager$LayoutParams')
    local alert = alertBuilder.create()
    alert.getWindow().setType(gg.ANDROID_SDK_INT >= 26 and LayoutParams.TYPE_APPLICATION_OVERLAY or LayoutParams.TYPE_PHONE)  
    alert.show()
end

luajava.runOnUiThread(MaterialAlert)
gg.sleep(500)
AutoBypass()

-- ==================== UI 配置 ====================
_ENV["悬浮窗图标"] = 'https://patchwiki.biligame.com/images/ys/2/29/4k98v9sdrrkrxw8vxfdxll42bdi3czo.png'
_ENV["标题"] = '造梦西游外传 v2.8'

_ENV["分页"] = {
    '公告', '悬浮窗功能', '秒过功能', '冒险专区', '竞技专区',
    '法宝功能', '坠龙之地', '活动专区', '娱乐功能', '万能修改', '设置'
}

init()
uistart({
    -- 公告页
    {
         CAtext('造梦西游外传多功能脚本 v2.8', '#FF6B35', '16sp', true),
        CAbutton('手动过检测', AutoBypass, '#2196F3'),
         CAtext('━━ 最新更新 ━━', '#FF9800', '12sp', true),
         CAtext('✅ 新增「卖道具」功能(娱乐功能页)', '#4CAF50', '12sp'),
         CAtext('✅ 泳池修改重构', '#4CAF50', '12sp'),
        CAtext('✅ 新增「修改体力值」开关(活动专区)', '#4CAF50', '12sp'),
        CAtext('✅ 新增「泳池二合一」总开关(活动专区)', '#4CAF50', '12sp'),
        CAtext('✅ 新增「全员秒杀无冷却」循环模式(竞技&冒险)', '#4CAF50', '12sp'),
        CAtext('✅ 新增「三生锤无敌属性」开关(坠龙之地)', '#4CAF50', '12sp'),
        CAtext('✅ 新增「竞技专区」分页(左右角色入坑)', '#4CAF50', '12sp'),
        CAtext('✅ 新增「全员无敌」开关(冒险专区)', '#4CAF50', '12sp'),
        CAtext('✅ 新增「视奸模式」开关(娱乐功能页)', '#4CAF50', '12sp'),
        CAtext('✅ 新增「刷文碟」开关(活动专区)', '#4CAF50', '12sp'),
        CAtext('✅ 新增「GM模式」开关(娱乐功能页)', '#4CAF50', '12sp'),
        CAtext('━━ 注意事项 ━━', '#FF9800', '12sp', true),
        CAtext('⚠️ 请勿在竞技模式下使用', '#F44336', '12sp'),
        CAbutton('查看详细公告', ShowNotice, '#4CAF50'),
    },
    -- 悬浮窗功能页
    {
        CAtext('🖥️ 快捷悬浮窗控制', '#673AB7', '16sp', true),
        CAtext('每个开关独立控制对应悬浮窗的显示/隐藏,悬浮窗可拖拽,点击切换功能状态', '#666666', '12sp'),
        CAtext('━━ 水晶秒杀 ━━', '#FF9800', '12sp', true),
        CAswitch('显示「秒左」悬浮窗', function() showSwitch("秒左") end, function() hideSwitch("秒左") end),
        CAswitch('显示「秒右」悬浮窗', function() showSwitch("秒右") end, function() hideSwitch("秒右") end),
        CAtext('━━ 常用功能 ━━', '#FF9800', '12sp', true),
        CAswitch('显示「透视」悬浮窗', function() showSwitch("透视") end, function() hideSwitch("透视") end),
        CAswitch('显示「聚怪」悬浮窗', function() showSwitch("聚怪") end, function() hideSwitch("聚怪") end),
        CAswitch('显示「穿图」悬浮窗', function() showSwitch("穿图") end, function() hideSwitch("穿图") end),
        CAtext('━━ 模式切换悬浮窗 ━━', '#FF9800', '12sp', true),
        CAswitch('显示「电脑模式」悬浮窗', function() showSwitch("电脑模式") end, function() hideSwitch("电脑模式") end),
        CAswitch('显示「手机模式」悬浮窗', function() showSwitch("手机模式") end, function() hideSwitch("手机模式") end),
        CAtext('━━ 提示 ━━', '#4CAF50', '12sp', true),
        CAtext('注意:悬浮窗需要悬浮权限,如不显示请检查权限', '#2196F3', '12sp'),
        CAbutton('隐藏全部悬浮窗', function() hideAllSwitches() end, '#F44336'),
    },
    -- 秒过功能页
    {
        CAtext('🏔️ 稳定秒过', '#4CAF50', '16sp', true),
        CAbutton('无视地形秒过', TerrainIgnorePass, '#4CAF50'),
        CAtext('━━ 循环功能 ━━', '#FF9800', '12sp', true),
        CAswitch('循环无视地形秒过', StartLoopTerrainIgnorePass, StopLoopTerrainIgnorePass),
        CAbutton('设置循环间隔', SetTerrainLoopInterval, '#9C27B0'),
        CAbutton('查看详细说明', ShowAdventureInstructions, '#4CAF50'),
    },
    -- 冒险专区
    {
        CAtext('⚡ 冒险专区', '#8BC34A', '16sp', true),
        CAbutton('秒过功能', InstantPass, '#4CAF50'),
        CAswitch('循环秒过', StartLoopInstantPass, StopLoopInstantPass),
        CAbutton('设置循环时间', SetLoopInterval, '#9C27B0'),
        CAswitch('猴子无敌秒(无敌+秒杀)', MonkeyInvincibleKill_On, MonkeyInvincibleKill_Off),
        CAtext('━━ 通天神猴 ━━', '#FF9800', '12sp', true),
        CAswitch('🐒 通天神猴', MonkeySkillReplace_On, MonkeySkillReplace_Off),
        CAtext('提示:开启后替换普攻和技能为通天效果,退出关卡后依然有效。关闭则恢复原技能。', '#666666', '10sp'),
        CAtext('━━ 悟空功能 ━━', '#FF9800', '12sp', true),
        CAswitch('悟空强普替换', WukongStrongReplace_On, WukongStrongReplace_Off),
        CAbutton('⚙️ 自定义技能代码', SetWukongStrongReplaceValue, '#9C27B0'),
        CAtext('当前代码: ' .. WUKONG_STRONG_REPLACE_VALUE, '#2196F3', '12sp'),
        CAbutton('📖 悟空功能说明', ShowWukongInstructions, '#4CAF50'),
        CAtext('━━ 全技能无冷却 ━━', '#FF9800', '12sp', true),
        CAswitch('全员技能无冷却', AllNoCooldown_On, AllNoCooldown_Off),
        CAtext('━━ 定怪功能 ━━', '#FF9800', '12sp', true),
        CAswitch('定怪', StartMonsterFixLoop, StopMonsterFixLoop, '冻结怪物无法行动'),
        CAtext('━━ 全员无敌 ━━', '#FF9800', '12sp', true),
        CAswitch('全员无敌(开关式)', AllInvincible_On, AllInvincible_Off, '在关卡内开启,所有角色无敌'),
        CAtext('━━ 秒杀辅助 ━━', '#FF9800', '12sp', true),
        CAswitch('全员秒杀无冷却(循环)', AllSecondKill_On, AllSecondKill_Off),
        CAbutton('查看详细说明', ShowInstantPassInstructions, '#4CAF50'),
    },
    -- ==================== 竞技专区 ====================
    {
        CAtext('🏆 竞技专区', '#FF5722', '16sp', true),
        CAtext('━━ 搜索模式(勾选启用) ━━', '#FF9800', '12sp', true),
        CAcheck({
            {
                "💻 电脑模式",
                function()
                    PC_MODE_ENABLED = true
                    showCloudNotify("模式", "电脑模式已开启", true)
                    local s = allSwitches["电脑模式"]
                    if s then s.setState(true) end
                end,
                function()
                    PC_MODE_ENABLED = false
                    showCloudNotify("模式", "电脑模式已关闭", true)
                    local s = allSwitches["电脑模式"]
                    if s then s.setState(false) end
                end
            },
            {
                "📱 手机模式",
                function()
                    MOBILE_MODE_ENABLED = true
                    showCloudNotify("模式", "手机模式已开启", true)
                    local s = allSwitches["手机模式"]
                    if s then s.setState(true) end
                end,
                function()
                    MOBILE_MODE_ENABLED = false
                    showCloudNotify("模式", "手机模式已关闭", true)
                    local s = allSwitches["手机模式"]
                    if s then s.setState(false) end
                end
            },
        }),
        CAtext('━━ 角色入坑 ━━', '#FF9800', '12sp', true),
        CAswitch('左边入坑', LeftRoleEnter_On, LeftRoleEnter_Off),
        CAswitch('右边入坑', RightRoleEnter_On, RightRoleEnter_Off),
        CAtext('━━ 秒杀辅助 ━━', '#FF9800', '12sp', true),
        CAswitch('全员秒杀无冷却(循环)', AllSecondKill_On, AllSecondKill_Off),
        CAbutton('查看详细说明', ShowJingJiInstructions, '#4CAF50'),
    },
    -- 法宝功能
    {
        CAtext('✨ 法宝秒怪', '#9C27B0', '16sp', true),
        CAbutton('镇魂萧二阶秒怪', FaBao_ZhenHunXiaoErJie, '#4CAF50'),
        CAbutton('镇魂萧一阶秒怪', FaBao_ZhenHunXiaoYiJie, '#4CAF50'),
        CAbutton('云阳板一阶秒怪', FaBao_YunYangBanYiJie, '#4CAF50'),
        CAbutton('云阳板二阶秒怪', FaBao_YunYangBanErJie, '#4CAF50'),
        CAbutton('枯叶灵一阶秒怪', FaBao_KuYeLingYiJie, '#4CAF50'),
        CAbutton('枯叶灵二阶秒怪', FaBao_KuYeLingErJie, '#4CAF50'),
        CAbutton('魁花篮一阶秒怪', FaBao_KuiHuaLanYiJie, '#4CAF50'),
        CAbutton('魁花篮二阶秒怪', FaBao_KuiHuaLanErJie, '#4CAF50'),
        CAbutton('查看详细说明', ShowFaBaoInstructions, '#2196F3'),
    },
    -- 坠龙之地
    {
        CAtext('⚔️ 坠龙之地', '#FF5722', '16sp', true),
        CAswitch('模型透视', ModelPenetration_On, ModelPenetration_Off, '不分机'),
        CAbutton('秒左边水晶', Zuilong_LeftKill_On, '#2196F3'),
        CAbutton('秒右边水晶', Zuilong_RightKill_On, '#2196F3'),
        CAswitch('显示宽屏按键', WideScreen_On, WideScreen_Off),
        CAtext('    开启后屏幕下方会多出一个宽屏缩放按钮', '#666666', '10sp'),
        CAswitch('聚怪', Zuilong_Gather_On, Zuilong_Gather_Off, '将怪物聚集到龙坑'),
        CAswitch('无蓝耗 + 全员无冷却', BothOn, BothOff),
        CAswitch('坠龙角色无敌', ZuilongRoleInvincible_On, ZuilongRoleInvincible_Off),
        CAbutton('内购三生锤', InternalBloodsucker, '#2196F3'),
        CAswitch('🔨 三生锤无敌属性', SanShengChui_On, SanShengChui_Off, '开关式,修改12处属性为99999'),
        CAswitch('穿图', StepByStep_Enable, StepByStep_Disable, '开启后达到分机效果'),
        CAbutton('刷成就(单次执行)', Achievement_Once, '#4CAF50'),
        CAbox({ '72变(英雄修改)',
            CAtext('当前目标ID: ' .. (_72Bian_TargetID or 40), '#FF9800', '12sp'),
            CAtext('━━ 一键变身上古英雄 ━━', '#FF9800', '12sp', true),
            CAswitch('变通天教主 (40)',
                function() new72Bian_set(40) end,
                function() if _72Bian_Active and _72Bian_TargetID == 40 then _72Bian_Disable() end end),
            CAswitch('变帝俊 (98)',
                function() new72Bian_set(98) end,
                function() if _72Bian_Active and _72Bian_TargetID == 98 then _72Bian_Disable() end end),
            CAswitch('变伏羲 (107)',
                function() new72Bian_set(107) end,
                function() if _72Bian_Active and _72Bian_TargetID == 107 then _72Bian_Disable() end end),
            CAtext('━━ 一键变身其他英雄 ━━', '#FF9800', '12sp', true),
            CAswitch('变斗战胜佛 (51)',
                function() new72Bian_set(51) end,
                function() if _72Bian_Active and _72Bian_TargetID == 51 then _72Bian_Disable() end end),
            CAswitch('变后羿 (61)',
                function() new72Bian_set(61) end,
                function() if _72Bian_Active and _72Bian_TargetID == 61 then _72Bian_Disable() end end),
            CAswitch('变六耳猕猴 (71)',
                function() new72Bian_set(71) end,
                function() if _72Bian_Active and _72Bian_TargetID == 71 then _72Bian_Disable() end end),
            CAswitch('变真武大帝 (80)',
                function() new72Bian_set(80) end,
                function() if _72Bian_Active and _72Bian_TargetID == 80 then _72Bian_Disable() end end),
            CAswitch('变东皇太一 (89)',
                function() new72Bian_set(89) end,
                function() if _72Bian_Active and _72Bian_TargetID == 89 then _72Bian_Disable() end end),
            CAswitch('变鹿 (103)',
                function() new72Bian_set(103) end,
                function() if _72Bian_Active and _72Bian_TargetID == 103 then _72Bian_Disable() end end),
            CAswitch('变女土蝠 (108)',
                function() new72Bian_set(108) end,
                function() if _72Bian_Active and _72Bian_TargetID == 108 then _72Bian_Disable() end end),
            CAtext('━━ 自定义与恢复 ━━', '#FF9800', '12sp', true),
            CAswitch('开启72变(悟空改英雄)', 
                function() 
                    local id = _72Bian_TargetID or 40
                    _72Bian_Enable(id) 
                end, 
                function() 
                    _72Bian_Disable() 
                end
            ),
            CAbutton('自定义修改(输入ID)', SeventyTwo_Custom, '#9C27B0'),
            CAbutton('恢复原始英雄 (1)', SeventyTwo_Restore, '#F44336'),
            CAbutton('英雄ID查询表', ShowHeroIDTable, '#607D8B'),
            CAbutton('📖 72变使用说明', ShowSeventyTwoInstructions, '#4CAF50'),
        }),
        CAbutton('查看详细说明', ShowZuilongInstructions, '#4CAF50'),
    },
    -- 活动专区
    {
        CAtext('🎉 活动专区', '#E91E63', '16sp', true),
        CAtext('━━ 打地鼠功能 ━━', '#FF9800', '12sp', true),
        CAswitch('⏱️ 打地鼠增加时长', WhackAMole_On, WhackAMole_Off),
        CAbutton('📖 打地鼠使用说明', function() 
            luajava.runOnUiThread(function()
                pcall(function()
                    AlGuiDialogBox.showTextDiaLog(context, "打地鼠增加时长使用说明",
                        "本功能为原极速版优化而来,开启后打地鼠时间显著增加,可轻松拿高分。\n" ..
                        "若搜索不到则说明不兼容,请重试或重启游戏。\n\n" ..
                        "⚠️ 开关式,关闭时自动恢复原始值。",
                        "知道了")
                end)
            end)
        end, '#4CAF50'),
        CAswitch('🍙 吃粽子刷分(撞桌211分)', EatZongzi_On, EatZongzi_Off),
        CAbutton('📖 查看吃粽子刷分说明', ShowEatZongziInstructions, '#2196F3'),
       CAtext('━━ 泳池修改 ━━', '#FF9800', '12sp', true),
-- 二合一总开关(放在上面)
CAswitch('🌟 泳池二合一', 
    function()
        PoolEnergy_On()
        PoolModify_On()
    end,
    function()
        PoolEnergy_Off()
    end
),
-- 下面两个并排复选框(类似竞技专区)
CAcheck({
    {
        "修改体力",
        function() PoolEnergy_On() end,
        function() PoolEnergy_Off() end
    },
    {
        "修改分数",
        function() PoolModify_On() end,
        function() PoolModify_Off() end
    }
}),
CAbutton('📖 查看泳池修改说明', ShowPoolModifyInstructions, '#2196F3'),
        CAtext('━━ 刷文碟(坠龙之地) ━━', '#FF9800', '12sp', true),
        CAswitch('刷文碟', ShuaWenDie_On, ShuaWenDie_Off),
        CAbutton('📖 刷文碟使用说明', function() 
            luajava.runOnUiThread(function()
                pcall(function()
                    AlGuiDialogBox.showTextDiaLog(context, "刷文碟使用说明",
                        "什么对局都可以,进游戏后开启功能等待通知提醒即可(可能比较久3到5分钟具体等通知,开的过程可以战斗,不会分机)",
                        "知道了")
                end)
            end)
        end, '#4CAF50'),
    },
    -- 娱乐功能
    {
        CAtext('🎮 娱乐功能', '#9C27B0', '16sp', true),
        CAswitch('游戏加速', GameSpeed_On, GameSpeed_Off, '活动使用'),
        CAtext('当前游戏加速倍速: ' .. (GAME_SPEED_VALUE or 3) .. ' 倍', '#FF9800', '12sp'),
        CAbutton('⚙️ 设置游戏加速倍速', SetGameSpeedValue, '#9C27B0'),
        CAswitch('全局加速', GlobalSpeed_On, GlobalSpeed_Off, '过检测'),
        CAtext('当前全局加速倍速: ' .. (GLOBAL_SPEED_MULTIPLIER or 3) .. ' 倍', '#FF9800', '12sp'),
        CAbutton('⚙️ 设置全局加速倍速', SetGlobalSpeedMultiplier, '#9C27B0'),
        CAswitch('无限跳跃', InfiniteJump_On, InfiniteJump_Off, '无限跳跃'),
        CAswitch('佛光美化(降魔→双龙)', BuddhaLight_On, BuddhaLight_Off),
        CAbutton('自定义佛光技能代码', BuddhaLight_Custom, '#2196F3'),
        CAswitch('火焰山替换主线关卡', FlameMountain_On, FlameMountain_Off, '替换组队关卡ID(默认1032火焰山)'),
        CAbutton('⚙️ 自定义关卡ID', SetFlameMountainID, '#9C27B0'),
        CAtext('当前关卡ID: ' .. FLAME_MOUNTAIN_ID, '#FF9800', '12sp'),
        CAswitch('显示变速按键(冒险关卡)', SpeedButton_On, SpeedButton_Off),
        CAswitch('GM模式', GM_On, GM_Off),
         CAtext('━━ 卖道具功能 ━━', '#FF9800', '12sp', true),
         CAswitch('🛒 自定义卖道具', MaiDongXi_On, MaiDongXi_Off),
         CAbutton('📖 查看使用说明', ShowMaiDongXiInstructions, '#2196F3'),
         CAtext('━━ 视奸模式 ━━', '#FF9800', '12sp', true),
        CAswitch('👀 视奸模式(单次执行)', Shijian_On, Shijian_Off, '点击开启执行一次,关闭无影响'),
        CAbutton('查看使用说明', ShowEntertainmentInstructions, '#4CAF50'),
    },
    -- 万能修改
    {
        CAtext('🛠️ 万能修改', '#607D8B', '16sp', true),
        CAbutton('启动万能修改', UniversalModify, '#2196F3'),
        CAbutton('一键恢复上次修改', RestoreLastModify, '#4CAF50'),
        CAbutton('查看攻略', ShowUniversalModifyInstructions, '#9C27B0'),
    },
    -- 设置
    {
        CAtext('⚙️ 设置', '#673AB7', '16sp', true),
        CAswitch('退出脚本', 
            function()
                if SHIJIAN_BUSY then SHIJIAN_BUSY = false end
                if GAME_SPEED_ACTIVE then GameSpeed_Off() end
                if GLOBAL_SPEED_DATA then GlobalSpeed_Off() end
                if zuilong_gather_data then Zuilong_Gather_Off() end
                if step_active then StepByStep_Disable() end
                if BUDDHA_LIGHT_ACTIVE then BuddhaLight_Off() end
                if INFINITE_JUMP_ACTIVE then InfiniteJump_Off() end
                if MONKEY_INVINCIBLE_KILL_DATA then MonkeyInvincibleKill_Off() end
                if WUKONG_STRONG_REPLACE_ACTIVE then WukongStrongReplace_Off() end
                if MONKEY_SKILL_DATA then MonkeySkillReplace_Off() end
                if ALL_NO_COOLDOWN_DATA then AllNoCooldown_Off() end
                if NO_MANA_LIST_ITEMS then NoManaCost_Off() end
                if MODEL_PENETRATION_DATA then ModelPenetration_Off() end
                if FLAME_MOUNTAIN_DATA then FlameMountain_Off() end
                if ZUILONG_ROLE_INVINCIBLE_ACTIVE then ZuilongRoleInvincible_Off() end
                if MONSTER_FIX_ACTIVE then StopMonsterFixLoop() end
                if EAT_ZONGZI_DATA then EatZongzi_Off() end
                if POOL_MODIFY_ADDRS then PoolModify_Off() end
                if WHACK_A_MOLE_DATA then WhackAMole_Off() end
                if WIDE_SCREEN_DATA then WideScreen_Off() end
                if SPEED_BUTTON_DATA then SpeedButton_Off() end
                if GM_DATA or WaiZhuan64_GM_DATA then GM_Off() end
                if SHUA_WENDIE_DATA then ShuaWenDie_Off() end
                if ALL_INVINCIBLE_DATA then AllInvincible_Off() end
                if ALL_SECOND_KILL_LOOP_ACTIVE then AllSecondKill_Off() end
                if leftRoleData then LeftRoleEnter_Off() end
                if rightRoleData then RightRoleEnter_Off() end
                if SANSHENGCHUI_DATA then SanShengChui_Off() end
                if POOL_ENERGY_ADDRS then PoolEnergy_Off() end
                LAST_MODIFY_DATA = nil
                IS_LOOP_ACTIVE = false
                TERRAIN_LOOP_ACTIVE = false
                hideAllSwitches()
                Lock.unUi()
            end,
            function() end),
        CAtext('感谢方法提供过检测技术', '#2196F3', '14sp', true),
        CAtext('请勿破坏游戏平衡', '#666666', '12sp', true),
    },
})

-- 初始化悬浮窗(默认隐藏)
initAllSwitches()

-- 启动UI
Lock.Ui(invoke, nil, function(err) print("UI错误:", err) end)