diff --git a/bettergi.d.ts b/bettergi.d.ts index e46586fac..223c976fa 100644 --- a/bettergi.d.ts +++ b/bettergi.d.ts @@ -1033,7 +1033,7 @@ declare class AutoLeyLineOutcropParam { isResinExhaustionMode: boolean; /** 耗尽模式取小值 */ openModeCountMin: boolean; - /** 是否使用冒险之证寻找地脉花 */ + /** 不使用冒险之证寻路(启用后改用内置路线,不通过冒险之证定位地脉花) */ useAdventurerHandbook: boolean; /** 好感队名称 */ friendshipTeam: string; @@ -4620,4 +4620,4 @@ declare class Task { declare Then: typeof Task.prototype.then; // ==== END AUTO-GENERATED ALIASES ==== -} +} \ No newline at end of file diff --git a/repo/js/AutoLeyLineOutcrop/README.md b/repo/js/AutoLeyLineOutcrop/README.md index a182c8a59..f86b9b26a 100644 --- a/repo/js/AutoLeyLineOutcrop/README.md +++ b/repo/js/AutoLeyLineOutcrop/README.md @@ -55,6 +55,9 @@ - **全自动运行**:配置好之后,只需要点击运行,就可以全部打完,无需任何其他操作。 - **自动寻找地脉花**:通过大地图定位地脉花位置的方式来寻找地脉花,并执行后续的路线。 - **自动开启地脉花奖励,优先使用浓缩树脂**:领取奖励时优先选择浓缩树脂,当存在双倍奖励活动(地脉移涌或星之归还)时会优先选择双倍奖励。 +- **双倍检测模式**:开启后仅在检测到双倍产出时才刷地脉,刷完后自动退出,适合只想用双倍活动的玩家。 +- **材料拾取**:领奖后自动追踪拾取怪物掉落物,搭配20树脂模式可高效获取怪物素材(会触发短暂战斗)。 +- **20树脂模式(怪物素材慢刷)**:每次仅消耗20体力,以效率换取更多怪物掉落素材机会,配合材料拾取效果更佳。 - **树脂耗尽模式**:根据设置统计当前的树脂情况,计算出需要运行的次数,运行结束后再次判断,若结束后统计到未消耗的树脂则继续执行(最多3次) - **树脂不足时自动停止**:如果领取奖励时树脂不够了,脚本会直接停止,可以配置是否使用须臾/脆弱。 - **好感队领取奖励**:领取奖励前切换到好感队,还可以领取到好感度。 @@ -77,6 +80,12 @@ 打开大地图,点击左下角设置,开启自定义标记。 脚本非正常结束运行时会出现该问题。 ## 更新日志 +### 5.1 +- 新增双倍检测模式(只刷双倍产出) +- 新增材料拾取功能(领奖后自动拾取掉落物) +- 新增20树脂模式(怪物素材慢刷,配合材料拾取使用) +- 修复浓缩树脂识别失败的问题 +- 修复树脂耗尽模式+刷取次数取小值的情况下,当OCR计算次数>手动设置刷取次数时无法正确终止脚本的bug(到达手动刷取次数会继续刷,直到体力用光) ### 5.0 - 新增至冬路线 - BGI最低版本要求改为0.63.2 diff --git a/repo/js/AutoLeyLineOutcrop/main.js b/repo/js/AutoLeyLineOutcrop/main.js index f27512278..ea5f8da4e 100644 --- a/repo/js/AutoLeyLineOutcrop/main.js +++ b/repo/js/AutoLeyLineOutcrop/main.js @@ -14,12 +14,14 @@ let currentRunTimes = 0; // 当前运行次数 let isNotification = false; // 是否发送通知 let config = {}; // 全局配置对象 let recheckCount = 0; // 树脂重新检查次数(防止无限递归) +let originalResinCount = 0; // 原始识别到的树脂可刷取次数(用于判断是否需要重检) const MAX_RECHECK_COUNT = 3; // 最大重新检查次数 let consecutiveFailureCount = 0; // 连续战斗失败次数 const MAX_CONSECUTIVE_FAILURES = 5; // 最大连续失败次数,超过后终止脚本 -const ocrRegion1 = {x: 800, y: 200, width: 300, height: 100}; // 中心区域 -const ocrRegion2 = {x: 0, y: 200, width: 300, height: 300}; // 追踪任务区域 -const ocrRegion3 = {x: 1200, y: 520, width: 300, height: 300}; // 拾取区域 +let doubleSurgeCounter = 0; // 双倍剩余次数计数器(0=未知/未初始化,>0=剩余次数) +const ocrRegion1 = { x: 800, y: 200, width: 300, height: 100 }; // 中心区域 +const ocrRegion2 = { x: 0, y: 200, width: 300, height: 300 }; // 追踪任务区域 +const ocrRegion3 = { x: 1200, y: 520, width: 300, height: 300 }; // 拾取区域 // 预定义识别对象 const openRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/icon/open.png")); @@ -55,6 +57,14 @@ const ocrRoThis = RecognitionObject.ocrThis; // 任何时候都确保自定义标记处于打开状态 await openCustomMarks(); } + + // 确保返回主界面(防止拾取等操作后停留在意外界面) + try { + await genshin.returnMainUi(); + } catch (mainUiError) { + log.warn(`返回主界面时出错: ${mainUiError.message}`); + } + log.info("全自动地脉花运行结束"); } })(); @@ -65,7 +75,14 @@ const ocrRoThis = RecognitionObject.ocrThis; */ async function runLeyLineOutcropScript() { // 初始化加载配置和设置并校验 - initialize(); + await initialize(); + + // 如果开启"只刷双倍"模式,双倍检测在两个位置进行: + // 1. 开书时快速检测(如果开启冒险之证) + // 2. 打完地脉花后在奖励界面兜底检测(带区域重试) + if (settings.onlySurgeMode) { + log.info("开启只刷双倍模式,双倍检测将在开书时进行"); + } // 处理树脂耗尽模式(如果开启) let runTimesValue = await handleResinExhaustionMode(); @@ -80,7 +97,20 @@ async function runLeyLineOutcropScript() { // 如果是树脂耗尽模式,执行完毕后再次检查是否还有树脂 if (settings.isResinExhaustionMode) { - await recheckResinAndContinue(); + // 判断是否需要重新检查: + // 1. 非取小值模式 → 需要重检(确保真刷完) + // 2. 取小值模式但设定次数≥识别次数 → 用户想刷光 → 需要重检 + // 3. 取小值模式且设定次数<识别次数 → 用户只想刷设定次数 → 不需要重检 + const needRecheck = !physical.OpenModeCountMin || settings.timesValue >= originalResinCount; + + if (needRecheck) { + await recheckResinAndContinue(); + } else { + log.info(`[取小值模式] 已完成设定的 ${settings.timesValue} 次(可刷 ${originalResinCount} 次),结束运行`); + if (isNotification) { + notification.send(`树脂耗尽模式(取小值):已完成 ${settings.timesValue} 次运行,脚本结束`); + } + } } } @@ -118,10 +148,14 @@ async function initialize() { // 2. 加载配置文件 try { config = JSON.parse(file.readTextSync("config.json")); - loadSettings(); } catch (error) { throw new Error("配置文件加载失败,请检查config.json文件是否存在"); } + try { + loadSettings(); + } catch (error) { + throw new Error(error.message); + } try { // 3. 检查脚本更新 await checkUpdate(); @@ -138,7 +172,7 @@ async function checkUpdate() { try { // 发送GET请求 const response = await http.request("GET", "https://cnb.cool/bettergi/bettergi-scripts-list/-/git/raw/release/repo/js/AutoLeyLineOutcrop/manifest.json", - JSON.stringify({"Content-Type": "text/plain; charset=utf-8"}) + JSON.stringify({ "Content-Type": "text/plain; charset=utf-8" }) ); const latestManifest = JSON.parse(response.body); const manifest = JSON.parse(file.readTextSync("manifest.json")); @@ -160,6 +194,9 @@ async function checkUpdate() { } catch (error) { throw new Error(`检查脚本更新时出错: ${error.message}`); } + + // 重置双倍次数计数器 + doubleSurgeCounter = 0; } @@ -200,6 +237,9 @@ async function handleResinExhaustionMode() { settings.timesValue = resinResult.count; } + // 保存原始识别到的树脂次数,用于后续判断是否需要重检 + originalResinCount = resinResult.count; + physical.NeedRunsCount = settings.timesValue; log.info(`树脂统计成功:`); log.info(` 原粹树脂可刷取: ${resinResult.originalResinTimes} 次`); @@ -376,7 +416,17 @@ async function runLeyLineChallenges() { // 寻找地脉花位置 // 数据保存在全局变量中 leyLineX,leyLineY if (settings.useAdventurerHandbook) { - await findLeyLineOutcropByBook(settings.country, settings.leyLineOutcropType); + // 仅在第一次循环且开启双倍模式时检测双倍 + const checkSurge = settings.onlySurgeMode && currentRunTimes === 0; + const findResult = await findLeyLineOutcropByBook(settings.country, settings.leyLineOutcropType, checkSurge); + + // 开书双倍检测未通过,提前退出 + if (findResult && findResult.noSurge) { + log.info("[双倍检测] 开书未检测到双倍产出,脚本结束"); + // 确保返回主界面(此时可能在冒险之证菜单) + try { await genshin.returnMainUi(); } catch (e) { } + return; + } } else { await findLeyLineOutcrop(settings.country, settings.leyLineOutcropType); } @@ -647,11 +697,21 @@ async function executePath(path) { await processLeyLineOutcrop(settings.timeout, targetPath); // 尝试领取奖励,如果失败则抛出异常停止执行 - const rewardSuccess = await attemptReward(); - if (!rewardSuccess) { + const rewardResult = await attemptReward(); + if (!rewardResult || !rewardResult.success) { throw new Error("无法领取奖励,树脂不足或其他原因"); } + // 根据双倍剩余次数决定是否继续 + if (settings.onlySurgeMode && rewardResult.willFinishDoubleTimes) { + log.info("[双倍次数] 双倍次数已刷完,脚本结束"); + // 设置运行次数为目标值,终止while循环 + currentRunTimes = settings.timesValue; + return; + } else if (settings.onlySurgeMode && rewardResult.doubleRemainingTimes !== undefined) { + log.info(`[双倍次数] 还有 ${rewardResult.doubleRemainingTimes} 次双倍,继续下一个地脉花`); + } + // 成功完成地脉花挑战,重置连续失败计数器 consecutiveFailureCount = 0; } diff --git a/repo/js/AutoLeyLineOutcrop/manifest.json b/repo/js/AutoLeyLineOutcrop/manifest.json index 16be8169b..2420231db 100644 --- a/repo/js/AutoLeyLineOutcrop/manifest.json +++ b/repo/js/AutoLeyLineOutcrop/manifest.json @@ -6,44 +6,47 @@ "bgi_version": "0.63.2", "description": "基于OCR图像识别的全自动刷取地脉花。\n💡更多信息请查看README! \n\n----------注意事项----------\n●仅支持BetterGI 0.63.2 及以上版本!\n●部分地脉花因特殊原因不支持全自动,具体的点位请在手册中查看。\n●树脂使用的优先级:2倍原粹树脂 > 浓缩树脂 > 原粹树脂。\n●运行时会传送到七天神像设置中设置的七天神像,需要关闭七天神像设置中的“是否就近七天神像恢复血量”,并指定七天神像。\n●战斗策略注意调度器设置中地图追踪行走配置里的“允许在JsSpript中使用”和“覆盖JS中的自动战斗配置”,只有在都打开的情况下脚本才会使用下面的战斗配置,否则会使用独立任务中的战斗策略。战斗超时时间不能大于脚本自定义配置中的时间。\n\n如果遇到问题,请先参照README中的方法进行解决。", "authors": [ - { - "name": "ddaodan", - "links": "https://github.com/ddaodan" - }, - { - "name": "平面镜", - "links": "https://github.com/Flatmirrr" - }, - { - "name": "秋云", - "links": "https://github.com/physligl" - }, - { - "name": "起个名字好难的喵", - "links": "https://github.com/MisakaAldrich" - }, - { - "name": "火山", - "links": "https://github.com/RRRR623" - }, - { - "name": "寒烟", - "links": "https://github.com/214-hanyan" - }, - { - "name": "羊汪汪", - "links": "https://github.com/ColinXHL" - }, - { - "name": "云端客", - "links": "https://github.com/Kirito520Asuna" - } + { + "name": "ddaodan", + "links": "https://github.com/ddaodan" + }, + { + "name": "平面镜", + "links": "https://github.com/Flatmirrr" + }, + { + "name": "秋云", + "links": "https://github.com/physligl" + }, + { + "name": "起个名字好难的喵", + "links": "https://github.com/MisakaAldrich" + }, + { + "name": "火山", + "links": "https://github.com/RRRR623" + }, + { + "name": "寒烟", + "links": "https://github.com/214-hanyan" + }, + { + "name": "羊汪汪", + "links": "https://github.com/ColinXHL" + }, + { + "name": "云端客", + "links": "https://github.com/Kirito520Asuna" + }, + { + "name": "lingyu", + "links": "https://github.com/aaahai00" + } ], "settings_ui": "settings.json", "main": "main.js", "http_allowed_urls": [ - "https://cnb.cool/*", - "https://*.github.com/*" + "https://cnb.cool/*", + "https://*.github.com/*" ] - } - \ No newline at end of file +} \ No newline at end of file diff --git a/repo/js/AutoLeyLineOutcrop/settings.json b/repo/js/AutoLeyLineOutcrop/settings.json index b29f3c5e5..5e296b880 100644 --- a/repo/js/AutoLeyLineOutcrop/settings.json +++ b/repo/js/AutoLeyLineOutcrop/settings.json @@ -29,21 +29,33 @@ ], "default": "稻妻" }, + { + "name": "count", + "type": "input-text", + "label": "刷取次数", + "default": "6" + }, { "name": "isResinExhaustionMode", "type": "checkbox", - "label": "树脂耗尽模式\n开启后会自动统计所有可用树脂并计算可刷取次数,替换上方设置的刷取次数\n注意:请同时设置树脂刷取次数,将在统计失败时使用" + "label": "树脂耗尽模式\n开启后,将根据当前可用树脂自动计算刷取次数\n注意:若统计失败,则使用设置的「刷取次数」" }, { "name": "openModeCountMin", "type": "checkbox", - "label": "刷取次数取小值\n开启后树脂耗尽模式中计算可刷取次数,和上方设置的刷取次数取小值" + "label": "限制刷取次数\n开启后,以设置的「刷取次数」为上限;树脂不足时则按实际可刷次数执行" }, { - "name": "count", - "type": "input-text", - "label": "刷取次数,默认6次", - "default": "6" + "name": "onlySurgeMode", + "type": "checkbox", + "label": "只刷双倍\n自动检查双倍地脉,没有就不刷,双倍次数用尽会退出(测试功能,可能不准,建议开启冒险之证找花)", + "default": false + }, + { + "name": "monsterMaterialMode", + "type": "checkbox", + "label": "20树脂模式\n优先使用20树脂,建议配合战斗后拾取材料(低效率)", + "default": false }, { "name": "useTransientResin", @@ -63,9 +75,9 @@ "label": "战斗的队伍名称,不填表示不切换队伍" }, { - "name": "friendshipTeam", - "type": "input-text", - "label": "好感队名称,不填表示不切换好感队" + "name": "friendshipTeam", + "type": "input-text", + "label": "好感队名称,不填表示不切换好感队" }, { "name": "timeout", @@ -73,10 +85,23 @@ "label": "战斗超时时间,单位秒,默认120秒", "default": 120 }, + { + "name": "pickDropsAfterReward", + "type": "checkbox", + "label": "战斗后拾取材料", + "default": false + }, + { + "name": "pickDropsSeconds", + "type": "input-text", + "label": "拾取材料时间(秒)", + "default": "25" + }, { "name": "useAdventurerHandbook", "type": "checkbox", - "label": "是否使用冒险之证寻找地脉花" + "label": "是否使用冒险之证寻找地脉花", + "default": true }, { "name": "isNotification", @@ -89,10 +114,8 @@ "label": "一条龙模式\n开启后,会跳过开始的前往七天神像以及强制更新" }, { - "name": "isGoToSynthesizer", - "type": "select", - "label": "是否前往合成台合成浓缩树脂\n 体力大于40时自动合成浓缩树脂【开发中】" + "name": "isGoToSynthesizer", + "type": "select", + "label": "是否前往合成台合成浓缩树脂\n 体力大于40时自动合成浓缩树脂【开发中】" } -] - - +] \ No newline at end of file diff --git a/repo/js/AutoLeyLineOutcrop/utils/attemptReward.js b/repo/js/AutoLeyLineOutcrop/utils/attemptReward.js index 28fd76f2d..13b2ace20 100644 --- a/repo/js/AutoLeyLineOutcrop/utils/attemptReward.js +++ b/repo/js/AutoLeyLineOutcrop/utils/attemptReward.js @@ -1,3 +1,128 @@ +/** + * 奖励领取相关工具函数 + * 注意:本文件使用 main.js 中定义的全局变量 doubleSurgeCounter(双倍剩余次数计数器) + */ + +/** + * 截图并提取OCR文本 + * @returns {Promise>} + */ +async function captureAllTexts() { + const captureRegion = captureGameRegion(); + try { + const ocrRo = RecognitionObject.Ocr(0, 0, captureRegion.width, captureRegion.height); + const textList = captureRegion.findMulti(ocrRo); + if (!textList || textList.count === 0) { + return []; + } + const result = []; + for (let i = 0; i < textList.count; i++) { + result.push({ + text: textList[i].text, + x: textList[i].x, + y: textList[i].y, + width: textList[i].width, + height: textList[i].height + }); + } + return result; + } finally { + captureRegion.dispose(); + } +} + +/** + * 检测是否包含双倍产出关键词 + * @param {Array<{text: string}>} texts + * @returns {boolean} + */ +function checkDoubleReward(texts) { + return texts.some(t => + t.text.includes("双倍") || + t.text.includes("2倍产出") || + t.text.includes("2倍") + ); +} + +/** + * 从OCR文本中解析双倍剩余次数 + * @param {Array<{text: string}>} texts + * @returns {{found: boolean, count: number}} + */ +function parseDoubleRemainingTimes(texts) { + for (let i = 0; i < texts.length; i++) { + const match = texts[i].text.match(/2倍产出次数[::]\s*(\d+)/); + if (match) { + return { found: true, count: parseInt(match[1]) }; + } + } + return { found: false, count: 0 }; +} + +/** + * 带重试的双倍检测(检测双倍 + 解析次数) + * @param {Array<{text: string}>} initialTexts - 首次OCR结果 + * @returns {Promise<{hasDoubleReward: boolean, doubleRemainingTimes: number, doubleTimesParsed: boolean}>} + */ +const DOUBLE_TIMES_OCR_REGION = { x: 1191, y: 433, width: 158, height: 39 }; + +async function detectDoubleRewardWithRetry(initialTexts) { + let hasDoubleReward = checkDoubleReward(initialTexts); + let { found: doubleTimesParsed, count: doubleRemainingTimes } = parseDoubleRemainingTimes(initialTexts); + + if (doubleTimesParsed) { + log.info(`[双倍检测] 剩余双倍次数: ${doubleRemainingTimes}`); + } + + async function retryParseDoubleTimes() { + const captureRegion = captureGameRegion(); + try { + const ocrRo = RecognitionObject.Ocr( + DOUBLE_TIMES_OCR_REGION.x, + DOUBLE_TIMES_OCR_REGION.y, + DOUBLE_TIMES_OCR_REGION.width, + DOUBLE_TIMES_OCR_REGION.height + ); + const areaTexts = captureRegion.findMulti(ocrRo); + if (areaTexts.length > 0) { + const result = parseDoubleRemainingTimes(areaTexts); + if (result.found) { + doubleTimesParsed = true; + doubleRemainingTimes = result.count; + log.info(`[双倍检测] 剩余双倍次数: ${doubleRemainingTimes}`); + return true; + } + } + return false; + } finally { + captureRegion.dispose(); + } + } + + if (!hasDoubleReward) { + log.info("[双倍检测] 首次未识别到双倍,300ms后重试..."); + await sleep(300); + const retryTexts = await captureAllTexts(); + if (retryTexts.length > 0) { + hasDoubleReward = checkDoubleReward(retryTexts); + if (!doubleTimesParsed) { + await retryParseDoubleTimes(); + } + } + } + + if (hasDoubleReward && !doubleTimesParsed) { + log.warn("[双倍检测] 检测到双倍但未能解析剩余次数,500ms后重试..."); + await sleep(500); + const success = await retryParseDoubleTimes(); + if (!success) { + log.warn("[双倍检测] 仍未能解析剩余次数,将正常领取"); + } + } + + return { hasDoubleReward, doubleRemainingTimes, doubleTimesParsed }; +} + /** * 带验证的单击函数 * @param {number} x - X坐标 @@ -6,18 +131,18 @@ * @param {number} maxRetries - 最大重试次数,默认为10 * @returns {Promise} 是否成功 */ -this.clickWithVerification = async function(x, y, targetText, maxRetries = 20) { +this.clickWithVerification = async function (x, y, targetText, maxRetries = 20) { for (let i = 0; i < maxRetries; i++) { keyUp("LBUTTON"); click(x, y); - await sleep(400); - + await sleep(400); + // 验证目标文字是否消失 let captureRegion = captureGameRegion(); let resList = captureRegion.findMulti(ocrRoThis); captureRegion.dispose(); let textFound = false; - + if (resList && resList.count > 0) { for (let j = 0; j < resList.count; j++) { if (resList[j].text.includes(targetText)) { @@ -26,13 +151,13 @@ this.clickWithVerification = async function(x, y, targetText, maxRetries = 20) { } } } - + // 如果文字消失了,说明点击成功 if (!textFound) { return true; } } - + log.warn(`经过${maxRetries}次点击,文字"${targetText}"仍未消失`); return false; } @@ -42,16 +167,16 @@ this.clickWithVerification = async function(x, y, targetText, maxRetries = 20) { * 使用OCR识别"地脉之花"或"激活地脉之花"文字,不受分辨率影响 * @returns {Promise} */ -this.verifyRewardPage = async function() { +this.verifyRewardPage = async function () { let captureRegion = null; - + try { captureRegion = captureGameRegion(); - + // 使用OCR识别上半区域 let ocrRo = RecognitionObject.Ocr(0, 0, captureRegion.width, captureRegion.height / 2); let textList = captureRegion.findMulti(ocrRo); - + let isValid = false; if (textList && textList.count > 0) { for (let i = 0; i < textList.count; i++) { @@ -65,12 +190,12 @@ this.verifyRewardPage = async function() { } } } - + // 已注释:减少日志输出 // if (!isValid) { // log.info(`奖励界面验证: 失败(未识别到关键文字)`); // } - + return isValid; } catch (error) { log.error(`验证奖励界面失败: ${error.message}`); @@ -88,33 +213,16 @@ this.verifyRewardPage = async function() { * @returns {Promise} */ async function checkOriginalResinEmpty() { - let captureRegion = null; - try { - captureRegion = captureGameRegion(); - - // 使用OCR识别"补充"文字 - let ocrRo = RecognitionObject.Ocr(0, 0, captureRegion.width, captureRegion.height); - let textList = captureRegion.findMulti(ocrRo); - - if (textList && textList.count > 0) { - for (let i = 0; i < textList.count; i++) { - let text = textList[i].text; - if (text.includes("补充")) { - log.warn("检测到补充文字,原粹树脂已耗尽"); - return true; - } - } + const textList = await captureAllTexts(); + const hasSupplement = textList.some(t => t.text.includes("补充")); + if (hasSupplement) { + log.warn("检测到补充文字,原粹树脂已耗尽"); } - - return false; + return hasSupplement; } catch (error) { log.error(`检查原粹树脂状态失败: ${error.message}`); return false; - } finally { - if (captureRegion) { - captureRegion.dispose(); - } } } @@ -124,71 +232,57 @@ async function checkOriginalResinEmpty() { * @returns {Promise} */ async function findAndSortUseButtons() { - let captureRegion = null; - try { - captureRegion = captureGameRegion(); - - // 使用OCR识别所有"使用"文字 - let ocrRo = RecognitionObject.Ocr(0, 0, captureRegion.width, captureRegion.height); - let textList = captureRegion.findMulti(ocrRo); - - if (!textList || textList.count === 0) { + const textList = await captureAllTexts(); + if (textList.length === 0) { log.warn("未找到任何文本"); return []; } - + // 查找只包含"使用"两个字的文本(真正的按钮) let buttons = []; - for (let i = 0; i < textList.count; i++) { + for (let i = 0; i < textList.length; i++) { let textRegion = textList[i]; - let text = textRegion.text.trim(); // 去除首尾空格 - - // 只匹配恰好是"使用"的文本,排除描述性文字 + let text = textRegion.text.trim(); + if (text === "使用") { - // 按钮就在文本位置(OCR识别到的就是按钮本身) let buttonX = Math.round(textRegion.x + textRegion.width / 2); let buttonY = Math.round(textRegion.y + textRegion.height / 2); - let textY = textRegion.y; // 提前保存Y坐标值 - let textContent = textRegion.text; // 提前保存文本内容 - - // 创建虚拟按钮Region对象(不保存textRegion引用,避免dispose后访问失败) + let textY = textRegion.y; + let textContent = textRegion.text; + let virtualButton = { index: buttons.length, region: { x: buttonX, y: buttonY, - click: function() { + click: function () { click(buttonX, buttonY); } }, x: buttonX, - y: textY, // 用文本的Y坐标进行排序 - text: textContent // 保存文本内容而非引用 + y: textY, + text: textContent }; - + buttons.push(virtualButton); } } - + if (buttons.length === 0) { log.warn("未找到包含'使用'的文本"); return []; } - + // 按Y坐标排序 buttons.sort((a, b) => a.y - b.y); - + log.info(`找到 ${buttons.length} 个使用按钮`); - + return buttons; } catch (error) { log.error(`查找使用按钮失败: ${error.message}`); return []; - } finally { - if (captureRegion) { - captureRegion.dispose(); - } } } @@ -200,71 +294,98 @@ async function findAndSortUseButtons() { */ async function analyzeResinOptions(sortedButtons, isOriginalResinEmpty) { let captureRegion = null; - + try { - captureRegion = captureGameRegion(); - // OCR识别整个界面的文本 - let ocrRo = RecognitionObject.Ocr(0, 0, captureRegion.width, captureRegion.height); - let textList = captureRegion.findMulti(ocrRo); - - if (!textList || textList.count === 0) { + let allTexts = await captureAllTexts(); + if (allTexts.length === 0) { log.warn("OCR未识别到任何文本"); return null; } - // 收集所有识别到的文本 - let allTexts = []; - for (let i = 0; i < textList.count; i++) { - allTexts.push({ - text: textList[i].text, - y: textList[i].y - }); + // 检测双倍产出(首次快速检测,用于判断是否有双倍) + let hasDoubleReward = false; + let doubleRemainingTimes = 0; + let doubleTimesParsed = false; + + if (settings.onlySurgeMode) { + const detectResult = await detectDoubleRewardWithRetry(allTexts); + hasDoubleReward = detectResult.hasDoubleReward; + doubleRemainingTimes = detectResult.doubleRemainingTimes; + doubleTimesParsed = detectResult.doubleTimesParsed; + } else { + hasDoubleReward = checkDoubleReward(allTexts); } - - // 检测是否有双倍/多倍产出 - let hasDoubleReward = allTexts.some(t => - t.text.includes("双倍") || - t.text.includes("2倍产出") || - t.text.includes("2倍") - ); - - // 只在有双倍产出时输出 if (hasDoubleReward) { log.info("检测到双倍产出"); + } else { + log.info("未检测到双倍产出"); } // 识别树脂类型(注意:如果原粹树脂耗尽,应该忽略这些识别) - let hasOriginalResin20 = !isOriginalResinEmpty && allTexts.some(t => + let hasOriginalResin20 = !isOriginalResinEmpty && allTexts.some(t => (t.text.includes("20") && t.text.includes("原粹树脂")) || (t.text.includes("20个") && t.text.includes("原粹树脂")) ); - - let hasOriginalResin40 = !isOriginalResinEmpty && allTexts.some(t => + + let hasOriginalResin40 = !isOriginalResinEmpty && allTexts.some(t => (t.text.includes("40") && t.text.includes("原粹树脂")) || (t.text.includes("40个") && t.text.includes("原粹树脂")) ); - - let hasCondensedResin = allTexts.some(t => + + let hasCondensedResin = allTexts.some(t => t.text.includes("浓缩树脂") || t.text.includes("浓缩") ); - - let hasTransientResin = allTexts.some(t => + + let hasTransientResin = allTexts.some(t => t.text.includes("须臾树脂") || t.text.includes("须臾") ); - - let hasFragileResin = allTexts.some(t => + + let hasFragileResin = allTexts.some(t => t.text.includes("脆弱树脂") || t.text.includes("脆弱") ); - - let hasPrimogems = allTexts.some(t => + + let hasPrimogems = allTexts.some(t => t.text.includes("原石") && t.text.includes("3次") ); - + // 输出识别到的树脂类型(调试用) log.info(`识别到的树脂类型 - 原粹20:${hasOriginalResin20}, 原粹40:${hasOriginalResin40}, 浓缩:${hasCondensedResin}, 须臾:${hasTransientResin}, 脆弱:${hasFragileResin}, 原石:${hasPrimogems}, 双倍:${hasDoubleReward}`); + // 双倍检测兜底:如果开启了双倍模式但没检测到双倍,记录状态但继续执行 + // 正常流程下,开书检测已拦截无双倍情况,能到这里说明是异常 + // 报错将在拾取完成后进行 + let shouldExitForSurge = settings.onlySurgeMode && !hasDoubleReward; + + // 20树脂模式:尝试将40树脂切换成20树脂 + let monsterMaterialSwitched = false; + if (settings.monsterMaterialMode) { + if (hasOriginalResin20 && !hasOriginalResin40) { + // 界面已经是20树脂,直接使用 + monsterMaterialSwitched = true; + log.info("20树脂模式:界面已是20树脂,无需切换"); + } else if (hasOriginalResin40) { + let switchSuccess = await trySwitch40To20Resin(); + if (switchSuccess) { + log.info("20树脂模式:成功切换到20个原粹树脂"); + monsterMaterialSwitched = true; + // 重新识别树脂类型 + allTexts = await captureAllTexts(); + hasOriginalResin20 = allTexts.some(t => + (t.text.includes("20") && t.text.includes("原粹树脂")) || + (t.text.includes("20个") && t.text.includes("原粹树脂")) + ); + hasOriginalResin40 = allTexts.some(t => + (t.text.includes("40") && t.text.includes("原粹树脂")) || + (t.text.includes("40个") && t.text.includes("原粹树脂")) + ); + } else { + log.warn("20树脂模式:未能切换到20个原粹树脂,将使用40个"); + } + } + } + // 决策逻辑(根据原粹树脂是否耗尽,决策不同) let choice = null; @@ -272,28 +393,33 @@ async function analyzeResinOptions(sortedButtons, isOriginalResinEmpty) { // ===== 原粹树脂耗尽的情况 ===== // 此时第一个"使用"按钮对应的是浓缩/须臾/脆弱树脂 log.warn("原粹树脂已耗尽,检测是否有其他可用树脂"); - - if (hasCondensedResin && sortedButtons.length >= 1) { + + if (hasCondensedResin && sortedButtons.length >= 1 && !settings.onlySurgeMode) { choice = { type: "使用1个浓缩树脂(原粹耗尽)", + resinAmount: 40, button: sortedButtons[0], buttonIndex: 0 }; - } else if (hasTransientResin && sortedButtons.length >= 1 && settings.useTransientResin) { + } else if (hasTransientResin && sortedButtons.length >= 1 && settings.useTransientResin && !settings.onlySurgeMode) { choice = { type: "使用1个须臾树脂(原粹耗尽)", + resinAmount: 40, button: sortedButtons[0], buttonIndex: 0 }; - } else if (hasFragileResin && sortedButtons.length >= 1 && settings.useFragileResin) { + } else if (hasFragileResin && sortedButtons.length >= 1 && settings.useFragileResin && !settings.onlySurgeMode) { choice = { type: "使用1个脆弱树脂(原粹耗尽)", + resinAmount: 40, button: sortedButtons[0], buttonIndex: 0 }; } else { // 输出详细的调试信息 - if (hasTransientResin && !settings.useTransientResin) { + if (settings.onlySurgeMode) { + return { choice: null, shouldExitForSurge: true, willFinishDoubleTimes: false, doubleRemainingTimes: 0, surgeModeResinEmpty: true }; + } else if (hasTransientResin && !settings.useTransientResin) { log.warn(`原粹树脂耗尽,检测到须臾树脂但配置禁止使用(settings.useTransientResin=${settings.useTransientResin})`); } else if (hasFragileResin && !settings.useFragileResin) { log.warn(`原粹树脂耗尽,检测到脆弱树脂但配置禁止使用(settings.useFragileResin=${settings.useFragileResin})`); @@ -306,37 +432,88 @@ async function analyzeResinOptions(sortedButtons, isOriginalResinEmpty) { // ===== 原粹树脂充足的情况 ===== // 第一个"使用"按钮对应原粹树脂 // 第二个"使用"按钮对应浓缩/须臾/脆弱树脂 - + // 优先级1: 如果有双倍产出,优先使用原粹树脂 if (hasDoubleReward && (hasOriginalResin20 || hasOriginalResin40)) { - // 如果当前是20个原粹树脂,先尝试切换到40个 - if (hasOriginalResin20 && !hasOriginalResin40) { - let switchSuccess = await trySwitch20To40Resin(); - if (switchSuccess) { + if (settings.monsterMaterialMode) { + // ===== 20树脂模式:使用20树脂 ===== + if (!monsterMaterialSwitched && hasOriginalResin40) { + let switchSuccess = await trySwitch40To20Resin(); + if (switchSuccess) { + log.info("20树脂模式(双倍):成功切换到20个原粹树脂"); + monsterMaterialSwitched = true; + } else { + log.warn("20树脂模式(双倍):未能切换到20,将使用40个"); + } + } + choice = { + type: monsterMaterialSwitched || hasOriginalResin20 ? "使用20个原粹树脂(20树脂模式,双倍产出)" : "使用40个原粹树脂(20树脂模式,双倍产出)", + resinAmount: monsterMaterialSwitched || hasOriginalResin20 ? 20 : 40, + button: sortedButtons[0], + buttonIndex: 0 + }; + } else { + // ===== 默认模式:智能优化 ===== + let isNow40Resin = hasOriginalResin40; + + if (hasOriginalResin20 && !hasOriginalResin40) { + let switchSuccess = await trySwitch20To40Resin(); + if (switchSuccess) { + isNow40Resin = true; + log.info("默认模式(双倍):已从20切换到40个原粹树脂"); + } else { + log.warn("默认模式(双倍):无法切换到40,保持20树脂"); + } + } + + if (settings.onlySurgeMode && isNow40Resin) { + log.info(`[双倍检测] 在40树脂界面下精确识别双倍消耗次数(仅只刷双倍模式)...`); + allTexts = await captureAllTexts(); + const reDetectResult = await detectDoubleRewardWithRetry(allTexts); + doubleRemainingTimes = reDetectResult.doubleRemainingTimes; + doubleTimesParsed = reDetectResult.doubleTimesParsed; + + if (doubleTimesParsed) { + log.info(`[双倍检测] 精确识别结果: 本次将消耗${doubleRemainingTimes}次`); + } else { + log.warn("[双倍检测] 未能解析消耗次数,将使用默认值"); + } + } + + let forceUse20ForLastSurge = false; + if (settings.onlySurgeMode && isNow40Resin && doubleRemainingTimes === 1) { + log.info("[双倍优化] 检测到仅剩1次双倍,尝试切换回20树脂以节省体力"); + let switchBackSuccess = await trySwitch40To20Resin(); + if (switchBackSuccess) { + forceUse20ForLastSurge = true; + log.info("[双倍优化] 成功切回20树脂,将用20体力完成最后一次双倍"); + } else { + log.warn("[双倍优化] 无法切回20,继续使用40树脂"); + } + } + + if ((isNow40Resin || hasOriginalResin40) && !forceUse20ForLastSurge) { choice = { - type: "使用40个原粹树脂(从20切换,双倍产出)", + type: "使用40个原粹树脂(双倍产出)", + resinAmount: 40, button: sortedButtons[0], buttonIndex: 0 }; } else { choice = { - type: "使用20个原粹树脂(双倍产出)", + type: forceUse20ForLastSurge ? "使用20个原粹树脂(最后1次双倍优化)" : "使用20个原粹树脂(双倍产出)", + resinAmount: 20, button: sortedButtons[0], buttonIndex: 0 }; } - } else { - choice = { - type: hasOriginalResin40 ? "使用40个原粹树脂(双倍产出)" : "使用20个原粹树脂(双倍产出)", - button: sortedButtons[0], - buttonIndex: 0 - }; } } // 优先级2: 优先使用浓缩树脂 else if (hasCondensedResin && sortedButtons.length >= 2) { choice = { type: "使用1个浓缩树脂", + resinAmount: 40, button: sortedButtons[1], buttonIndex: 1 }; @@ -345,40 +522,106 @@ async function analyzeResinOptions(sortedButtons, isOriginalResinEmpty) { else if (hasTransientResin && settings.useTransientResin && sortedButtons.length >= 2) { choice = { type: "使用1个须臾树脂", + resinAmount: 40, button: sortedButtons[1], buttonIndex: 1 }; } // 优先级4: 使用原粹树脂 else if (hasOriginalResin20 || hasOriginalResin40) { - // 如果当前是20个原粹树脂,先尝试切换到40个 - if (hasOriginalResin20 && !hasOriginalResin40) { - let switchSuccess = await trySwitch20To40Resin(); - if (switchSuccess) { + if (settings.monsterMaterialMode) { + // ===== 20树脂模式:简单粗暴方案 ===== + // 不需要切到40识别,直接设置计数器=3,跑完就收工 + // 如果实际次数不足3次,最多多跑一个节点,会被兜底逻辑捕获 + choice = { + type: hasOriginalResin20 ? "使用20个原粹树脂(20树脂模式)" : "使用40个原粹树脂(20树脂模式)", + resinAmount: hasOriginalResin20 ? 20 : 40, + button: sortedButtons[0], + buttonIndex: 0 + }; + + // 20模式下如果当前是40,切回20 + if (!hasOriginalResin20 && hasOriginalResin40) { + let switchSuccess = await trySwitch40To20Resin(); + if (switchSuccess) { + choice.type = "使用20个原粹树脂(20树脂模式)"; + choice.resinAmount = 20; // 更新树脂量 + log.info("20树脂模式:已切换到20个原粹树脂"); + } else { + log.warn("20树脂模式:无法切换到20,继续使用40"); + } + } + + log.info(`[20树脂模式] 双倍计数器将重置为3,按每次消耗1次计算`); + } else { + // ===== 默认模式:先让原有逻辑处理切换,再统一识别 ===== + + // 步骤1: 让原有逻辑处理切换(如果是20就切到40) + let isNow40Resin = hasOriginalResin40; // 当前是否已经是40 + if (hasOriginalResin20 && !hasOriginalResin40) { + let switchSuccess = await trySwitch20To40Resin(); + if (switchSuccess) { + isNow40Resin = true; + log.info("默认模式:已从20切换到40个原粹树脂"); + } else { + log.warn("默认模式:无法切换到40(可能体力不足),保持20树脂"); + } + } else if (hasOriginalResin40) { + log.info("默认模式:界面已经是40个原粹树脂,无需切换"); + } + + // 步骤2: 【关键】不管有没有切换,都重新OCR精确识别双倍消耗次数 + // 因为"有无双倍"和"消耗几次"是两个不同区域,首次识别可能不准 + if (isNow40Resin || settings.onlySurgeMode) { + log.info(`[双倍检测] 在${isNow40Resin ? '40' : '当前'}树脂界面下精确识别双倍消耗次数...`); + allTexts = await captureAllTexts(); + const reDetectResult = await detectDoubleRewardWithRetry(allTexts); + doubleRemainingTimes = reDetectResult.doubleRemainingTimes; + doubleTimesParsed = reDetectResult.doubleTimesParsed; + + if (doubleTimesParsed) { + log.info(`[双倍检测] 精确识别结果: 本次将消耗${doubleRemainingTimes}次`); + } else { + log.warn("[双倍检测] 未能解析消耗次数,将使用默认值"); + } + } + + // 步骤3: 根据识别结果决定是否优化(只剩1次且是40时,可选切回20省体力) + let forceUse20ForLastSurge = false; + if (isNow40Resin && settings.onlySurgeMode && doubleRemainingTimes === 1) { + log.info("[双倍优化] 检测到仅剩1次双倍,尝试切换回20树脂以节省体力"); + let switchBackSuccess = await trySwitch40To20Resin(); + if (switchBackSuccess) { + forceUse20ForLastSurge = true; + log.info("[双倍优化] 成功切回20树脂,将用20体力完成最后一次双倍"); + } else { + log.warn("[双倍优化] 无法切回20,继续使用40树脂"); + } + } + + // 步骤4: 最终选择 + if ((isNow40Resin || hasOriginalResin40) && !forceUse20ForLastSurge) { choice = { - type: "使用40个原粹树脂(从20切换)", + type: "使用40个原粹树脂(默认模式)", + resinAmount: 40, button: sortedButtons[0], buttonIndex: 0 }; } else { choice = { - type: "使用20个原粹树脂", + type: forceUse20ForLastSurge ? "使用20个原粹树脂(最后1次双倍优化)" : "使用20个原粹树脂(默认模式)", + resinAmount: 20, button: sortedButtons[0], buttonIndex: 0 }; } - } else { - choice = { - type: hasOriginalResin40 ? "使用40个原粹树脂" : "使用20个原粹树脂", - button: sortedButtons[0], - buttonIndex: 0 - }; } } // 优先级5: 如果配置允许,使用脆弱树脂 else if (hasFragileResin && settings.useFragileResin && sortedButtons.length >= 2) { choice = { type: "使用1个脆弱树脂", + resinAmount: 40, button: sortedButtons[1], buttonIndex: 1 }; @@ -390,12 +633,14 @@ async function analyzeResinOptions(sortedButtons, isOriginalResinEmpty) { let switchSuccess = await trySwitch20To40Resin(); choice = { type: switchSuccess ? "默认使用40个原粹树脂(从20切换)" : "默认使用20个原粹树脂", + resinAmount: switchSuccess ? 40 : 20, button: sortedButtons[0], buttonIndex: 0 }; } else { choice = { type: "默认使用原粹树脂", + resinAmount: hasOriginalResin40 ? 40 : (hasOriginalResin20 ? 20 : 40), button: sortedButtons[0], buttonIndex: 0 }; @@ -403,11 +648,70 @@ async function analyzeResinOptions(sortedButtons, isOriginalResinEmpty) { } } - return choice; + // 根据树脂选择和双倍次数判断是否会刷完双倍(使用计数器方案) + let willFinishDoubleTimes = false; + let actualRemainingTimes = doubleRemainingTimes; // 实际剩余次数(用于返回) + + if (settings.onlySurgeMode) { + // 判断本次消耗多少双倍次数(20树脂=1次,40树脂=2次) + // 使用显式的 resinAmount 数值字段,避免字符串匹配的歧义问题 + let consumeTimes = 0; + if (choice && choice.resinAmount === 40) { + consumeTimes = 2; + } else if (choice && choice.resinAmount === 20) { + consumeTimes = 1; + } + + if (consumeTimes > 0) { + // 初始化或更新计数器 + if (doubleSurgeCounter === 0) { + if (settings.monsterMaterialMode) { + // ===== 20树脂模式:简单粗暴方案 ===== + // 直接重置为3次,不管实际多少次 + // 跑完就收工,如果实际不足3次最多多跑一个节点 + doubleSurgeCounter = 3; + log.info(`[双倍计数器] 20树脂模式: 直接设置计数器=3(简单粗暴)`); + } else { + // ===== 默认模式:基于40界面识别结果 ===== + // 此时应该已经在40树脂模式下(前面有切换逻辑) + // 40树脂界面的显示规则: + // - 显示"消耗1次" → 确实只剩1次(准确) + // - 显示"消耗2次" → 剩余可能是2次或3次(无法区分) + if (doubleRemainingTimes === 1) { + doubleSurgeCounter = 1; + log.info(`[双倍计数器] 默认模式: 40界面显示消耗1次,确认剩余1次,设置计数器=${doubleSurgeCounter}`); + } else if (doubleRemainingTimes >= 2) { + // 保守估计为3次(正常情况都是3次,只有自己手动刷过才会不足) + doubleSurgeCounter = 3; + log.info(`[双倍计数器] 默认模式: 40界面显示消耗${doubleRemainingTimes}次,保守设置计数器=${doubleSurgeCounter}(可能剩2或3次)`); + } else { + // 未识别到次数,保守设为3 + doubleSurgeCounter = 3; + log.warn(`[双倍计数器] 默认模式: 未能解析次数,保守设置计数器=3`); + } + } + } + + // 递减计数器 + if (doubleSurgeCounter > 0) { + doubleSurgeCounter -= consumeTimes; + actualRemainingTimes = Math.max(0, doubleSurgeCounter); + log.info(`[双倍计数器] 本次消耗${consumeTimes}次,剩余=${actualRemainingTimes}(计数器=${doubleSurgeCounter})`); + + // 判断是否将刷完双倍 + if (doubleSurgeCounter <= 0) { + willFinishDoubleTimes = true; + log.info(`[双倍计数器] 双倍次数已刷完`); + } + } + } + } + + return { choice, shouldExitForSurge, willFinishDoubleTimes, doubleRemainingTimes: actualRemainingTimes }; } catch (error) { log.error(`分析树脂选项失败: ${error.message}`); - return null; + return { choice: null, shouldExitForSurge: false, willFinishDoubleTimes: false, doubleRemainingTimes: 0 }; } finally { if (captureRegion) { captureRegion.dispose(); @@ -416,57 +720,114 @@ async function analyzeResinOptions(sortedButtons, isOriginalResinEmpty) { } /** - * 尝试将20个原粹树脂切换到40个原粹树脂 - * @returns {Promise} 是否成功切换 + * 从OCR文本中识别当前原粹树脂数量 + * @param {Array<{text: string}>} texts + * @returns {number|null} 20、40 或 null */ -async function trySwitch20To40Resin() { +function parseCurrentResinAmount(texts) { + for (let i = 0; i < texts.length; i++) { + const text = texts[i].text; + if ((text.includes("20") || text.includes("20个")) && text.includes("原粹树脂")) { + return 20; + } + if ((text.includes("40") || text.includes("40个")) && text.includes("原粹树脂")) { + return 40; + } + } + return null; +} + +/** + * 验证OCR文本中是否包含目标树脂数量 + * @param {Array<{text: string}>} texts + * @param {number} targetAmount + * @returns {boolean} + */ +function verifyResinAmount(texts, targetAmount) { + return texts.some(t => + (t.text.includes(targetAmount.toString()) && t.text.includes("原粹")) || + (t.text.includes(`${targetAmount}个`) && t.text.includes("树脂")) + ); +} + +/** + * 尝试切换原粹树脂数量到目标值 + * @param {number} targetAmount - 目标树脂数量(20或40) + * @returns {Promise} 是否成功切换到目标值 + */ +async function trySwitchResin(targetAmount) { let switchButtonIcon = null; let switchButtonRo = null; let currentCaptureRegion = null; let newCaptureRegion = null; - + const otherAmount = targetAmount === 20 ? 40 : 20; + try { - log.info("检测到20个原粹树脂,尝试切换到40个"); - + // 步骤1: 先检查当前是否已经是目标值 currentCaptureRegion = captureGameRegion(); - - // 检测切换按钮 + let textList = await captureAllTexts(); + let currentAmount = parseCurrentResinAmount(textList); + + // 如果已经是目标值,直接返回成功 + if (currentAmount === targetAmount) { + log.info(`当前已是${targetAmount}个原粹树脂,无需切换`); + return true; + } + + // 如果识别失败,继续尝试切换(兼容旧逻辑) + if (currentAmount === null) { + log.warn(`未能识别当前树脂数量,尝试切换到${targetAmount}个`); + } else { + log.info(`当前是${currentAmount}个原粹树脂,尝试切换到${targetAmount}个`); + } + + // 步骤2: 检测切换按钮 switchButtonIcon = file.ReadImageMatSync("assets/icon/switch_button.png"); switchButtonRo = RecognitionObject.TemplateMatch(switchButtonIcon); - switchButtonRo.threshold = 0.7; // 设置合适的阈值 - - // 查找切换按钮 + switchButtonRo.threshold = 0.7; + let switchButtonPos = currentCaptureRegion.find(switchButtonRo); - + if (!switchButtonPos || switchButtonPos.isEmpty()) { - log.info("未找到切换按钮(树脂不足40或按钮不可用),保持使用20个原粹树脂"); + log.info(`未找到切换按钮(树脂不足${targetAmount}),保持使用${currentAmount || otherAmount}个原粹树脂`); return false; } - - // 找到可用的切换按钮,点击切换 - log.info(`找到切换按钮,点击切换到40个原粹树脂`); + + // 步骤3: 点击切换按钮 + log.info(`找到切换按钮,点击切换到${targetAmount}个原粹树脂`); switchButtonPos.click(); - await sleep(800); - - // 验证是否切换成功 - newCaptureRegion = captureGameRegion(); - let ocrRo = RecognitionObject.Ocr(0, 0, newCaptureRegion.width, newCaptureRegion.height); - let textList = newCaptureRegion.findMulti(ocrRo); - - if (textList && textList.count > 0) { - for (let i = 0; i < textList.count; i++) { - let text = textList[i].text; - if ((text.includes("40") && text.includes("原粹")) || - (text.includes("40个") && text.includes("树脂"))) { - log.info("成功切换到40个原粹树脂"); - return true; - } + await sleep(800); // 等待UI更新 + + // 步骤4: 验证是否切换成功(带重试) + let switchSuccess = false; + for (let retry = 0; retry < 2; retry++) { + newCaptureRegion = captureGameRegion(); + let verifyTextList = await captureAllTexts(); + + if (verifyTextList.length > 0 && verifyResinAmount(verifyTextList, targetAmount)) { + log.info(`成功切换到${targetAmount}个原粹树脂`); + switchSuccess = true; + break; + } + + if (retry === 0) { + log.info(`[切换验证] 首次未识别到${targetAmount},500ms后重试...`); + await sleep(500); + } + + if (newCaptureRegion) { + newCaptureRegion.dispose(); + newCaptureRegion = null; } } - - log.warn("点击切换按钮后,未能确认切换到40个原粹树脂"); - return false; - + + if (!switchSuccess) { + log.warn(`点击切换按钮后,未能确认切换到${targetAmount}个原粹树脂`); + return false; + } + + return true; + } catch (error) { log.error(`切换树脂数量失败: ${error.message}`); return false; @@ -484,6 +845,22 @@ async function trySwitch20To40Resin() { } } +/** + * 尝试将20个原粹树脂切换到40个原粹树脂 + * @returns {Promise} 是否成功切换 + */ +async function trySwitch20To40Resin() { + return await trySwitchResin(40); +} + +/** + * 尝试将40个原粹树脂切换到20个原粹树脂(20树脂模式) + * @returns {Promise} 是否成功切换 + */ +async function trySwitch40To20Resin() { + return await trySwitchResin(20); +} + /** * 切换回战斗队伍 * @returns {Promise} @@ -506,33 +883,33 @@ async function switchBackToCombatTeam() { * 循环检测并退出,直到确认不在奖励界面 * @returns {Promise} */ -this.ensureExitRewardPage = async function() { +this.ensureExitRewardPage = async function () { const MAX_ATTEMPTS = 5; // 最多尝试5次 let attempts = 0; - + try { log.info("检查是否需要退出奖励界面"); - + while (attempts < MAX_ATTEMPTS) { attempts++; - + // 检测是否在奖励界面 let isInRewardPage = await this.verifyRewardPage(); - + if (!isInRewardPage) { log.info("已确认不在奖励界面"); return; } - + // 还在奖励界面,按ESC退出 log.info(`检测到仍在奖励界面,按ESC退出 (第${attempts}次)`); keyPress("VK_ESCAPE"); await sleep(800); // 等待界面关闭动画 } - + // 超过最大尝试次数 log.warn(`已尝试${MAX_ATTEMPTS}次退出奖励界面,可能仍在界面中`); - + } catch (error) { log.error(`退出奖励界面时出错: ${error.message}`); } @@ -565,56 +942,114 @@ this.attemptReward = async function (retryCount = 0) { let isOriginalResinEmpty = false; let sortedButtons = []; let resinChoice = null; + let shouldExitForSurge = false; + let hasRewardError = false; + let rewardError = null; // 存储奖励领取阶段的错误(仅拾取模式启用时延迟抛出) + let doubleRemainingTimes = 0; // 双倍剩余次数 + let willFinishDoubleTimes = false; // 是否会刷完双倍 try { // 步骤2: 检查原粹树脂是否耗尽(通过"补充"按钮) isOriginalResinEmpty = await checkOriginalResinEmpty(); - + // 步骤3: 识别所有使用按钮并排序 sortedButtons = await findAndSortUseButtons(); - + if (sortedButtons.length === 0) { - log.error("未找到任何使用按钮"); - keyPress("VK_ESCAPE"); - await sleep(500); - await this.ensureExitRewardPage(); - return false; + throw new Error("未找到任何使用按钮"); } // 步骤4: 根据原粹树脂状态调整决策逻辑 - resinChoice = await analyzeResinOptions(sortedButtons, isOriginalResinEmpty); - + const result = await analyzeResinOptions(sortedButtons, isOriginalResinEmpty); + + if (!result) { + throw new Error("无法选择合适的树脂类型(所有树脂已耗尽)"); + } + + if (result.surgeModeResinEmpty) { + throw new Error("只刷双倍模式:原粹树脂耗尽,使用ESC退出"); + } + + resinChoice = result.choice; + shouldExitForSurge = result.shouldExitForSurge; + doubleRemainingTimes = result.doubleRemainingTimes || 0; + willFinishDoubleTimes = result.willFinishDoubleTimes || false; + if (!resinChoice) { - // 已在 analyzeResinOptions 中输出详细错误信息,这里不再重复 - keyPress("VK_ESCAPE"); - await sleep(500); - await this.ensureExitRewardPage(); - return false; + throw new Error("树脂决策结果为空"); } } catch (error) { - log.error(`处理奖励界面时出错: ${error.message}`); + log.warn(`处理奖励界面时遇到情况: ${error.message}`); keyPress("VK_ESCAPE"); await sleep(500); await this.ensureExitRewardPage(); - return false; + + // 未开启拾取模式时直接返回,不开启延迟报错 + if (!settings.pickDropsAfterReward) { + return false; + } + + // 开启拾取模式时存储错误,延迟到拾取后抛出 + rewardError = error; + hasRewardError = true; } - // 步骤5: 点击对应的使用按钮 - log.info(`选择: ${resinChoice.type},点击按钮 (X=${resinChoice.button.x}, Y=${resinChoice.button.y})`); - resinChoice.button.region.click(); - await sleep(1000); + // 步骤5: 点击对应的使用按钮(或无双倍时按ESC退出) + // 仅在无错误时执行领取奖励操作(catch中的错误已按ESC退出,无需再点击) + if (!hasRewardError) { + if (shouldExitForSurge) { + // 双倍检测兜底:未检测到双倍产出,用ESC代替领取奖励 + log.warn("[双倍兜底] 未检测到双倍产出,使用ESC关闭界面(不领取奖励)"); + keyPress("VK_ESCAPE"); + await sleep(800); + } else if (resinChoice) { + // 正常流程:点击使用按钮领取奖励 + log.info(`选择: ${resinChoice.type},点击按钮 (X=${resinChoice.button.x}, Y=${resinChoice.button.y})`); + // 点击使用按钮 + resinChoice.button.region.click(); + + await sleep(1000); + } + + // 等待领奖动画/道具到账 + await sleep(1200); + + // 确保完全退出奖励界面 + await this.ensureExitRewardPage(); + } // 步骤6: 如果需要切换回战斗队伍 if (settings.friendshipTeam) { await switchBackToCombatTeam(); } - // 等待领奖动画/道具到账 - await sleep(1200); + if (settings.pickDropsAfterReward) { + log.info(`[拾取材料] 开始执行自动拾取掉落物,拾取时间 ${settings.pickDropsSecondsValue} 秒...`); + try { + // TODO: 如果框架有专门的拾取API,建议替换此处的 AutoFightParam 实现 + // 因为没找到能单独调用寻找掉落物光柱的这个功能,所以拉起一个超时时间极短的战斗,但1秒钟会不可避免的放几个技能,这个也没办法 + const fightParam = new AutoFightParam(); + fightParam.timeout = 1; // 最低1秒超时(仅用于触发拾取逻辑,不进行实际战斗) + fightParam.pickDropsAfterFightEnabled = true; // 启用战后拾取模式 + fightParam.pickDropsAfterFightSeconds = settings.pickDropsSecondsValue; // 拾取持续时间 - // 确保完全退出奖励界面 - await this.ensureExitRewardPage(); - - return true; + await dispatcher.runAutoFightTask(fightParam); // 执行拾取任务(复用战斗任务的拾取功能) + log.info("[拾取材料] 拾取完成"); + } catch (error) { + log.warn(`[拾取材料] 拾取过程结束: ${error.message}`); + } + } + + // 延迟抛出奖励领取阶段的错误 + if (rewardError) { + throw rewardError; + } + + // 双倍检测兜底延迟报错:所有正常流程(切换队伍、拾取材料等)执行完毕后才抛出 + if (shouldExitForSurge) { + throw new Error("[双倍兜底] 开启了双倍检测但未检测到双倍产出,脚本终止"); + } + + return { success: true, doubleRemainingTimes, willFinishDoubleTimes }; } \ No newline at end of file diff --git a/repo/js/AutoLeyLineOutcrop/utils/calCountByResin.js b/repo/js/AutoLeyLineOutcrop/utils/calCountByResin.js index c74228766..a8369d6a5 100644 --- a/repo/js/AutoLeyLineOutcrop/utils/calCountByResin.js +++ b/repo/js/AutoLeyLineOutcrop/utils/calCountByResin.js @@ -17,20 +17,20 @@ const RESIN_ICONS = { // 普通数字识别对象(1-4) const NUMBER_ICONS = [ - {ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num1.png")), value: 1}, - {ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num2.png")), value: 2}, - {ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num3.png")), value: 3}, - {ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num4.png")), value: 4} + { ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num1.png")), value: 1 }, + { ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num2.png")), value: 2 }, + { ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num3.png")), value: 3 }, + { ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num4.png")), value: 4 } ]; // 白色数字识别对象(0-5,用于浓缩树脂) const WHITE_NUMBER_ICONS = [ - {ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num0_white.png")), value: 0}, - {ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num1_white.png")), value: 1}, - {ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num2_white.png")), value: 2}, - {ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num3_white.png")), value: 3}, - {ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num4_white.png")), value: 4}, - {ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num5_white.png")), value: 5} + { ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num0_white.png")), value: 0 }, + { ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num1_white.png")), value: 1 }, + { ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num2_white.png")), value: 2 }, + { ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num3_white.png")), value: 3 }, + { ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num4_white.png")), value: 4 }, + { ro: RecognitionObject.TemplateMatch(file.ReadImageMatSync("RecognitionObject/num5_white.png")), value: 5 } ]; // 配置常量 @@ -42,16 +42,16 @@ const CONFIG = { // 点击坐标 COORDINATES: { - MAP_SWITCH: {x: 1840, y: 1020}, // 地图右下角切换按钮 - MONDSTADT: {x: 1420, y: 180}, // 蒙德选择按钮 - AVOID_SELECTION: {x: 1090, y: 450} // 避免选中效果的点击位置 + MAP_SWITCH: { x: 1840, y: 1020 }, // 地图右下角切换按钮 + MONDSTADT: { x: 1420, y: 180 }, // 蒙德选择按钮 + AVOID_SELECTION: { x: 1090, y: 450 } // 避免选中效果的点击位置 }, // OCR识别区域配置 OCR_REGIONS: { - ORIGINAL_RESIN: {width: 200, height: 40}, - CONDENSED_RESIN: {width: 90, height: 40}, - OTHER_RESIN: {width: 0, height: 60} // width会根据图标宽度动态设置 + ORIGINAL_RESIN: { width: 200, height: 40 }, + CONDENSED_RESIN: { width: 90, height: 40 }, // 调用位置(L269)已改为硬编码,如果确认无用可删除 + OTHER_RESIN: { width: 0, height: 60 } // width会根据图标宽度动态设置 } }; @@ -163,7 +163,7 @@ async function recognizeNumberByOCR(ocrRegion, pattern) { captureRegion = captureGameRegion(); resList = captureRegion.findMulti(ocrRo); - if (!resList || resList.length === 0) { + if (!resList || resList.count === 0) { log.warn("OCR未识别到任何文本"); return null; } @@ -212,7 +212,7 @@ async function countOriginalResin(tryOriginalMode, opToMainUi, openMap) { } else { log.info('尝试使用优化模式'); let ocrPhysical = await physical.ocrPhysical(opToMainUi, openMap); - log.debug(`ocrPhysical: {0}`,JSON.stringify(ocrPhysical)) + log.debug(`ocrPhysical: {0}`, JSON.stringify(ocrPhysical)) await sleep(600) // ocrPhysical = false//模拟异常 if (ocrPhysical/* && ocrPhysical.ok*/) { @@ -256,6 +256,9 @@ async function countOriginalResinBackup() { * @returns {number} 浓缩树脂数量 */ async function countCondensedResin() { + keyPress("ESCAPE"); // 关闭上一步的补充原萃树脂界面 + await sleep(CONFIG.UI_DELAY); + const condensedResin = await recognizeImage(RESIN_ICONS.CONDENSED); if (!condensedResin) { log.warn(`未找到浓缩树脂图标`); @@ -263,10 +266,15 @@ async function countCondensedResin() { } const ocrRegion = { - x: condensedResin.x, - y: condensedResin.y, - width: CONFIG.OCR_REGIONS.CONDENSED_RESIN.width, - height: CONFIG.OCR_REGIONS.CONDENSED_RESIN.height + // 调用处的坐标范围不对,正常来说应该改偏移或者去源头看看问题,但是这样改简单粗暴,能用就行 + // x: condensedResin.x, + // y: condensedResin.y, + // width: CONFIG.OCR_REGIONS.CONDENSED_RESIN.width, + // height: CONFIG.OCR_REGIONS.CONDENSED_RESIN.height + x: 1140, + y: 26, + width: 45, + height: 41 }; // 首先尝试OCR识别 @@ -288,30 +296,33 @@ async function countCondensedResin() { // 点击浓缩树脂打开说明界面统计 condensedResin.click(); await sleep(CONFIG.UI_DELAY); - let captureRegion = captureGameRegion(); - let textList = null; + let captureRegion = null; try { // OCR识别整个界面的文本 + captureRegion = captureGameRegion(); let ocrRo = RecognitionObject.Ocr(0, 0, captureRegion.width, captureRegion.height); - textList = captureRegion.findMulti(ocrRo); + let textList = captureRegion.findMulti(ocrRo); - for (const res of textList) { - if (res.text.includes("当前拥有")) { - const match = res.text.match(/当前拥有\s*([0-5ss])/); - if (match && match[1]) { - const count = parseInt(match[1]); - log.info(`浓缩树脂数量(说明界面): ${count}`); - keyPress("ESCAPE"); - await sleep(CONFIG.UI_DELAY); - return count; + if (textList && textList.count > 0) { + for (let i = 0; i < textList.count; i++) { + if (textList[i].text.includes("当前拥有")) { + const match = textList[i].text.match(/当前拥有\s*([0-5ss])/); + if (match && match[1]) { + const count = parseInt(match[1]); + log.info(`浓缩树脂数量(说明界面): ${count}`); + keyPress("ESCAPE"); + await sleep(CONFIG.UI_DELAY); + return count; + } } } } + } catch (error) { + log.error(`说明界面OCR出错: ${error.message}`); } finally { - if (textList && typeof textList.dispose === 'function') { - textList.dispose(); + if (captureRegion) { + captureRegion.dispose(); } - captureRegion.dispose(); } log.warn(`未能识别浓缩树脂数量`); @@ -541,24 +552,33 @@ this.calCountByResin = async function () { let count = 0; // 计算可刷取次数 // 1. 原粹树脂:优先消耗40/次,不满40消耗20/次,不满20不消耗 + // 20树脂模式:每次消耗20/次 let originalResinTimes = 0; let remainingOriginalResin = countResult.originalResinCount; - // 先计算40树脂的次数 - if (remainingOriginalResin >= 40) { - const times40 = Math.floor(remainingOriginalResin / 40); - originalResinTimes += times40; - remainingOriginalResin = remainingOriginalResin - (times40 * 40); - } + if (settings.monsterMaterialMode) { + // 20树脂模式:每次20体力 + originalResinTimes = Math.floor(remainingOriginalResin / 20); + remainingOriginalResin = remainingOriginalResin % 20; + log.info(`原粹树脂可刷取次数(20树脂模式,20/次): ${originalResinTimes}`); + } else { + // 正常模式:优先40/次 + // 先计算40树脂的次数 + if (remainingOriginalResin >= 40) { + const times40 = Math.floor(remainingOriginalResin / 40); + originalResinTimes += times40; + remainingOriginalResin = remainingOriginalResin - (times40 * 40); + } - // 再计算20树脂的次数 - if (remainingOriginalResin >= 20) { - const times20 = Math.floor(remainingOriginalResin / 20); - originalResinTimes += times20; - remainingOriginalResin = remainingOriginalResin - (times20 * 20); - } + // 再计算20树脂的次数 + if (remainingOriginalResin >= 20) { + const times20 = Math.floor(remainingOriginalResin / 20); + originalResinTimes += times20; + remainingOriginalResin = remainingOriginalResin - (times20 * 20); + } - log.info(`原粹树脂可刷取次数: ${originalResinTimes}`); + log.info(`原粹树脂可刷取次数: ${originalResinTimes}`); + } // 2. 浓缩树脂:每个计算为1次 let condensedResinTimes = countResult.condensedResinCount; diff --git a/repo/js/AutoLeyLineOutcrop/utils/findLeyLineOutcropByBook.js b/repo/js/AutoLeyLineOutcrop/utils/findLeyLineOutcropByBook.js index f058824fa..c57544088 100644 --- a/repo/js/AutoLeyLineOutcrop/utils/findLeyLineOutcropByBook.js +++ b/repo/js/AutoLeyLineOutcrop/utils/findLeyLineOutcropByBook.js @@ -1,74 +1,142 @@ // 齿轮图标识别对象 const mapSettingButtonRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/icon/map_setting_button.bmp")); +// OCR 检测辅助函数(用于地脉移涌检测) +function wipOcrCheckText(roi1080, keywords, label) { + let ra = null; + try { + const s = genshin.scaleTo1080PRatio; + const x = Math.round(roi1080[0] * s); + const y = Math.round(roi1080[1] * s); + const w = Math.round(roi1080[2] * s); + const h = Math.round(roi1080[3] * s); + + ra = captureGameRegion(); + const resList = ra.findMulti(RecognitionObject.ocr(x, y, w, h)); + const count = resList.length !== undefined ? resList.length : resList.count; + + if (typeof enableDebug !== "undefined" && enableDebug) { + log.info(`[DEBUG][${label}] ROI(1080P)=(${roi1080.join(',')}) 当前=(${x},${y},${w},${h}) 段数=${count}`); + for (let i = 0; i < count; i++) { + const r = resList[i]; + if (r) log.info(`[DEBUG][${label}] #${i + 1} text="${r.text}" pos=(${r.x},${r.y},${r.width},${r.height})`); + } + } + + for (let i = 0; i < count; i++) { + const r = resList[i]; + if (!r || !r.text) continue; + for (let k = 0; k < keywords.length; k++) { + if (r.text.includes(keywords[k])) return r; + } + } + return null; + } catch (e) { + log.warn(`[DEBUG][${label}] OCR异常: ${e.message}`); + return null; + } finally { + if (ra) ra.dispose(); + } +} + /** * 通过冒险之证查找地脉花位置 * @param {string} country - 国家名称 * @param {string} type - 地脉花类型 - * @returns {Promise} + * @param {boolean} checkSurge - 是否检测双倍产出 + * @returns {Promise<{found: boolean, hasSurge?: boolean}>} 返回查找结果和双倍状态 */ -this.findLeyLineOutcropByBook = async function (country, type) { - await genshin.returnMainUi(); - await sleep(1000); - log.info("使用冒险之证寻找地脉花"); - - // 确保运行时位于主界面 - keyPress("F1"); - // 开书等待时间延长至2.5s - await sleep(2500); - click(300, 550); // 点击讨伐 - await sleep(1000); - click(500, 200); // 点击筛选 - await sleep(1000); - click(500, 500); // 点击其他 - await sleep(1000); - - // 选择地脉花类型 - if (type === "蓝花(经验书)") { - click(700, 350); // 点击经验花 - } else { - click(500, 350); // 点击摩拉花 - } - await sleep(1000); - click(1300, 800); // 点击推荐 - await sleep(1000); - - // 查找并点击指定国家 - await this.findAndClickCountry(country); - - // 查找并点击停止追踪按钮 - await this.findAndCancelTrackingInBook(); - - // 最多重试3次确保大地图正确打开 - for (let retry = 0; retry < 3; retry++) { +this.findLeyLineOutcropByBook = async function (country, type, checkSurge = false) { + await genshin.returnMainUi(); await sleep(1000); - click(1500, 850); - // 等待大地图打开延长至 2.5s + log.info("使用冒险之证寻找地脉花"); + + // 确保运行时位于主界面 + keyPress("F1"); + // 开书等待时间延长至2.5s await sleep(2500); - - if (await this.checkBigMapOpened()) { - log.info("识别到大地图"); - break; // 成功打开大地图 - } - - if (retry < 2) { // 不是最后一次重试 - log.info(`大地图未正确打开,第${retry + 1}次重试...`); - await genshin.returnMainUi(); - await this.findAndClickCountry(country); - await this.findAndCancelTrackingInBook(); + click(300, 550); // 点击讨伐 + await sleep(1000); + click(500, 200); // 点击筛选 + await sleep(1000); + click(500, 500); // 点击其他 + await sleep(1000); + + // 选择地脉花类型 + if (type === "蓝花(经验书)") { + click(700, 350); // 点击经验花 } else { - throw new Error("大地图打开失败,已重试3次"); + click(500, 350); // 点击摩拉花 } - } + await sleep(1000); - // 获取地脉花位置 - const center = genshin.getPositionFromBigMap(); - leyLineX = center.x; - leyLineY = center.y; - log.info(`找到地脉花的坐标:(${leyLineX}, ${leyLineY})`); + // 开书双倍检测:在选择花类型之后、点击推荐之前进行 + let doubleHit = null; + if (checkSurge) { + log.info("[双倍检测] 开始识别两倍产出..."); + const doubleLarge = [1041, 496, 170, 37]; + doubleHit = wipOcrCheckText(doubleLarge, ["2倍", "两倍", "双倍"], "双倍产出检测"); + if (!doubleHit) { + log.info('[双倍检测] 识别失败,重试1...'); + await sleep(1500); + doubleHit = wipOcrCheckText(doubleLarge, ["2倍", "两倍", "双倍"], "双倍产出检测-r1"); + } - // 取消追踪 - await this.cancelTrackingInMap(); + if (!doubleHit) { + log.warn("[双倍检测] 开书未识别到两倍产出,脚本将提前退出"); + if (isNotification) { + notification.send("⚠️ 未识别到两倍产出,脚本已终止"); + } + return { found: false, noSurge: true }; + } else { + log.info("[双倍检测] 开书识别到两倍产出,继续执行"); + if (isNotification) { + notification.send("✅ 识别到两倍产出"); + } + } + } + + click(1300, 800); // 点击推荐 + await sleep(1000); + + // 查找并点击指定国家 + await this.findAndClickCountry(country); + + // 查找并点击停止追踪按钮 + await this.findAndCancelTrackingInBook(); + + // 最多重试3次确保大地图正确打开 + for (let retry = 0; retry < 3; retry++) { + await sleep(1000); + click(1500, 850); + // 等待大地图打开延长至 2.5s + await sleep(2500); + + if (await this.checkBigMapOpened()) { + log.info("识别到大地图"); + break; // 成功打开大地图 + } + + if (retry < 2) { // 不是最后一次重试 + log.info(`大地图未正确打开,第${retry + 1}次重试...`); + await genshin.returnMainUi(); + await this.findAndClickCountry(country); + await this.findAndCancelTrackingInBook(); + } else { + throw new Error("大地图打开失败,已重试3次"); + } + } + + // 获取地脉花位置 + const center = genshin.getPositionFromBigMap(); + leyLineX = center.x; + leyLineY = center.y; + log.info(`找到地脉花的坐标:(${leyLineX}, ${leyLineY})`); + + // 取消追踪 + await this.cancelTrackingInMap(); + + return { found: true, hasSurge: checkSurge ? !!doubleHit : undefined }; }; /** @@ -76,14 +144,14 @@ this.findLeyLineOutcropByBook = async function (country, type) { * @returns {Promise} 返回是否检测到齿轮图标 * @private */ -this.checkBigMapOpened = async function() { - let captureRegion = captureGameRegion(); - try { - const imageResult = captureGameRegion().find(mapSettingButtonRo); - return imageResult.isExist(); - } finally { - captureRegion.dispose(); - } +this.checkBigMapOpened = async function () { + let captureRegion = captureGameRegion(); + try { + const imageResult = captureGameRegion().find(mapSettingButtonRo); + return imageResult.isExist(); + } finally { + captureRegion.dispose(); + } }; /** @@ -92,30 +160,30 @@ this.checkBigMapOpened = async function() { * @private */ this.findAndClickCountry = async function (country) { - // 挪德卡莱会被识别成挪德卡菜,需要特殊处理 - let match_country = country; - if (country === "挪德卡莱") { - match_country = "挪德卡"; - } - let captureRegion = captureGameRegion(); - try { - let resList = captureRegion.findMulti(ocrRoThis); - let found = false; - for (let i = 0; i < resList.count; i++) { - let res = resList[i]; - if (res.text.includes(match_country)) { - res.click(); - found = true; - break; - } + // 挪德卡莱会被识别成挪德卡菜,需要特殊处理 + let match_country = country; + if (country === "挪德卡莱") { + match_country = "挪德卡"; } - if (!found) { - // 没找到国家 - throw new Error("冒险之征中未找到国家:" + country + ",请检查该国家地图是否开启"); + let captureRegion = captureGameRegion(); + try { + let resList = captureRegion.findMulti(ocrRoThis); + let found = false; + for (let i = 0; i < resList.count; i++) { + let res = resList[i]; + if (res.text.includes(match_country)) { + res.click(); + found = true; + break; + } + } + if (!found) { + // 没找到国家 + throw new Error("冒险之征中未找到国家:" + country + ",请检查该国家地图是否开启"); + } + } finally { + captureRegion.dispose(); } - } finally { - captureRegion.dispose(); - } }; /** @@ -123,28 +191,28 @@ this.findAndClickCountry = async function (country) { * @private */ this.findAndCancelTrackingInBook = async function () { - let captureRegion = captureGameRegion(); - try { - let resList = captureRegion.findMulti(ocrRoThis); - let stop = null; - for (let i = 0; i < resList.count; i++) { - let res = resList[i]; - if (res.text.includes("停止")) { - stop = res; - break; - } - } + let captureRegion = captureGameRegion(); + try { + let resList = captureRegion.findMulti(ocrRoThis); + let stop = null; + for (let i = 0; i < resList.count; i++) { + let res = resList[i]; + if (res.text.includes("停止")) { + stop = res; + break; + } + } - if(stop) { - log.info("冒险之征中点击停止追踪并重新追踪获取坐标"); - stop.click(); - } else { - log.info("冒险之征中无需取消追踪"); + if (stop) { + log.info("冒险之征中点击停止追踪并重新追踪获取坐标"); + stop.click(); + } else { + log.info("冒险之征中无需取消追踪"); + } + } finally { + captureRegion.dispose(); } - } finally { - captureRegion.dispose(); - } - await sleep(1000); + await sleep(1000); }; /** @@ -152,39 +220,39 @@ this.findAndCancelTrackingInBook = async function () { * @private */ this.cancelTrackingInMap = async function () { - // 点击地脉花(因为从书点击追踪后花会在屏幕正中间) - click(960, 540); - await sleep(1000); - - let captureRegion = captureGameRegion(); - let stop = null; - let leyLine = null; - - try { - let resList = captureRegion.findMulti(ocrRoThis); - if (resList && resList.count > 0) { - for (let i = 0; i < resList.count; i++) { - let res = resList[i]; - if (res.text.includes("停止")) { - stop = res; - } else if (res.text.includes("地脉") || res.text.includes("衍出")) { - leyLine = res; + // 点击地脉花(因为从书点击追踪后花会在屏幕正中间) + click(960, 540); + await sleep(1000); + + let captureRegion = captureGameRegion(); + let stop = null; + let leyLine = null; + + try { + let resList = captureRegion.findMulti(ocrRoThis); + if (resList && resList.count > 0) { + for (let i = 0; i < resList.count; i++) { + let res = resList[i]; + if (res.text.includes("停止")) { + stop = res; + } else if (res.text.includes("地脉") || res.text.includes("衍出")) { + leyLine = res; + } + } } - } + } finally { + captureRegion.dispose(); + } + + + if (stop) { + log.info("地图中点击取消追踪"); + stop.click(); + } else if (leyLine) { + log.info("在地图中选择地脉花后点击取消追踪"); + leyLine.click(); + await sleep(1000); + click(1700, 1010); + await sleep(1000); } - } finally { - captureRegion.dispose(); - } - - - if (stop) { - log.info("地图中点击取消追踪"); - stop.click(); - } else if (leyLine) { - log.info("在地图中选择地脉花后点击取消追踪"); - leyLine.click(); - await sleep(1000); - click(1700, 1010); - await sleep(1000); - } }; \ No newline at end of file diff --git a/repo/js/AutoLeyLineOutcrop/utils/loadSettings.js b/repo/js/AutoLeyLineOutcrop/utils/loadSettings.js index 3a022a560..ef080200e 100644 --- a/repo/js/AutoLeyLineOutcrop/utils/loadSettings.js +++ b/repo/js/AutoLeyLineOutcrop/utils/loadSettings.js @@ -2,79 +2,108 @@ * 加载、验证、输出用户设置 * @returns {Object} 处理过的设置对象 */ -this.loadSettings = -function () { - try { - // 直接使用全局settings对象而不是重新创建 - // 这样能保留原始设置内容 +this.loadSettings = + function () { + try { + // 直接使用全局settings对象而不是重新创建 + // 这样能保留原始设置内容 - // 验证必要的设置 - if (!settings.start) { - throw new Error("请仔细阅读脚本介绍和手册,并在调度器内进行配置,如果你是直接运行的脚本,请将脚本加入调度器内运行!"); - } + // 验证必要的设置 + if (!settings.start) { + throw new Error("请仔细阅读脚本介绍和手册,并在调度器内进行配置,如果你是直接运行的脚本,请将脚本加入调度器内运行!"); + } - if (!settings.leyLineOutcropType) { - throw new Error("请选择你要刷取的地脉花类型(经验书/摩拉)"); - } + if (!settings.leyLineOutcropType) { + throw new Error("请选择你要刷取的地脉花类型(经验书/摩拉)"); + } - if (!settings.country) { - throw new Error("请在游戏中确认地脉花的第一个点的位置,然后在js设置中选择地脉花所在的国家。"); - } + if (!settings.country) { + throw new Error("请在游戏中确认地脉花的第一个点的位置,然后在js设置中选择地脉花所在的国家。"); + } - if (settings.friendshipTeam && !settings.team) { - throw new Error("未配置战斗队伍!当配置了好感队时必须配置战斗队伍!"); - } + if (settings.friendshipTeam && !settings.team) { + throw new Error("未配置战斗队伍!当配置了好感队时必须配置战斗队伍!"); + } - // 为了向后兼容,确保某些设置有默认值 - //settings.timeout = settings.timeout * 1000 || 120000; + if (settings.isResinExhaustionMode && settings.onlySurgeMode) { + throw new Error("树脂耗尽模式和只刷双倍模式是互斥选项,不能同时开启!\n请根据需求选择其中一种模式"); + } - // 处理刷取次数 - if (!settings.count || !/^-?\d+\.?\d*$/.test(settings.count)) { - log.warn(`刷取次数 ${settings.count} 不是数字,使用默认次数6次`); - settings.timesValue = 6; - } else { - // 转换为数字 - const num = parseFloat(settings.count); + // 为了向后兼容,确保某些设置有默认值 + //settings.timeout = settings.timeout * 1000 || 120000; - // 范围检查 - if (num < 1) { - settings.timesValue = 1; - log.info(`⚠️ 次数 ${num} 小于1,已调整为1`); + // 处理刷取次数 + if (!settings.count || !/^-?\d+\.?\d*$/.test(settings.count)) { + log.warn(`刷取次数 ${settings.count} 不是数字,使用默认次数6次`); + settings.timesValue = 6; } else { - // 处理小数 - if (!Number.isInteger(num)) { - settings.timesValue = Math.floor(num); - log.info(`⚠️ 次数 ${num} 不是整数,已向下取整为 ${settings.timesValue}`); + // 转换为数字 + const num = parseFloat(settings.count); + + // 范围检查 + if (num < 1) { + settings.timesValue = 1; + log.info(`⚠️ 次数 ${num} 小于1,已调整为1`); } else { - settings.timesValue = num; + // 处理小数 + if (!Number.isInteger(num)) { + settings.timesValue = Math.floor(num); + log.info(`⚠️ 次数 ${num} 不是整数,已向下取整为 ${settings.timesValue}`); + } else { + settings.timesValue = num; + } } } + + // 记录使用的设置 + log.info(`地脉花类型:${settings.leyLineOutcropType}`); + log.info(`国家:${settings.country}`); + + if (settings.friendshipTeam) { + log.info(`好感队:${settings.friendshipTeam}`); + } + if (settings.isResinExhaustionMode) { + log.warn("树脂耗尽模式已开启,若统计成功将覆盖设置的刷取次数"); + } else if (settings.onlySurgeMode) { + log.info(`只刷双倍模式已开启(双倍次数用尽后将提前退出)`); + } else { + log.info(`刷取次数:${settings.timesValue}`); + } + + // 设置通知状态 + isNotification = settings.isNotification; + + // 设置一条龙模式 + oneDragonMode = settings.oneDragonMode; + + // 设置拾取材料时间 + if (!settings.pickDropsSeconds || !/^\d+$/.test(settings.pickDropsSeconds) || parseInt(settings.pickDropsSeconds) < 1) { + settings.pickDropsSecondsValue = 25; + if (settings.pickDropsSeconds && !/^\d+$/.test(settings.pickDropsSeconds)) { + log.warn(`拾取时间 "${settings.pickDropsSeconds}" 不是有效数字,已使用默认值 25 秒`); + } else if (settings.pickDropsSeconds && parseInt(settings.pickDropsSeconds) < 1) { + log.warn(`拾取时间 ${settings.pickDropsSeconds} 小于 1,已使用默认值 25 秒`); + } + } else { + settings.pickDropsSecondsValue = parseInt(settings.pickDropsSeconds); + } + + if (settings.pickDropsAfterReward) { + log.info(`战斗后拾取材料:开启,拾取时间 ${settings.pickDropsSecondsValue} 秒`); + } + + if (settings.monsterMaterialMode) { + log.info(`20树脂模式:开启`); + } + + if (settings.onlySurgeMode && !settings.isResinExhaustionMode) { + log.info(`只刷双倍模式:开启(建议配合"使用冒险之证寻找地脉花"选项)`); + } + + if (isNotification) { + notification.send(`全自动地脉花开始运行,以下是本次运行的配置:\n\n地脉花类型:${settings.leyLineOutcropType}\n国家:${settings.country}\n刷取次数:${settings.timesValue}`); + } + } catch (error) { + throw error; } - - // 记录使用的设置 - log.info(`地脉花类型:${settings.leyLineOutcropType}`); - log.info(`国家:${settings.country}`); - - if (settings.friendshipTeam) { - log.info(`好感队:${settings.friendshipTeam}`); - } - if (settings.isResinExhaustionMode) { - log.warn("树脂耗尽模式已开启,若统计成功将覆盖设置的刷取次数"); - } else { - log.info(`刷取次数:${settings.timesValue}`); - } - - // 设置通知状态 - isNotification = settings.isNotification; - - // 设置一条龙模式 - oneDragonMode = settings.oneDragonMode; - - if (isNotification) { - notification.send(`全自动地脉花开始运行,以下是本次运行的配置:\n\n地脉花类型:${settings.leyLineOutcropType}\n国家:${settings.country}\n刷取次数:${settings.timesValue}`); - } - } catch (error) { - log.error(`加载设置失败: ${error.message}`); - throw error; - } -} \ No newline at end of file + } \ No newline at end of file