七圣召唤卡牌熟练度速刷: 适配新的联机打牌弹框样式 (#3284)

This commit is contained in:
Patrick-Ze authored and GitHub committed 2026-06-09 11:15:59 +08:00
1 parent c9171d64ce
commit 472c8cf8dd
4 files changed
+264 -109

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
/**
* @author Ayaka-Main
* @link https://github.com/Patrick-Ze
* @description 提供一些通用性的功能函数。使用方法: 将此文件放在脚本目录下的 lib 文件夹中,然后在你的脚本开头处执行下面这行:
eval(file.readTextSync("lib/lib.js"));
*/
/**
* 将路径分割为目录和文件名
* @param {string} path - 文件完整路径
* @returns {[string, string]} 返回数组,第一个元素是目录路径,第二个是文件名
* @example
* const [dir, file] = splitPath('稻妻\\绯樱绣球\\06-绯樱绣球-神里屋敷-10个.json'); // ['稻妻\\绯樱绣球', '06-绯樱绣球-神里屋敷-10个.json']
*/
function splitPath(path) {
const normalizedPath = path.replace(/\\/g, "/");
const lastSlashIndex = normalizedPath.lastIndexOf("/");
if (lastSlashIndex === -1) {
return [".", path];
}
const dir = path.slice(0, lastSlashIndex);
const file = path.slice(lastSlashIndex + 1);
return [dir, file];
}
function fileExists(fullPath) {
const [dirpath, filename] = splitPath(fullPath);
const normalizedPath = fullPath.replaceAll("/", "\\");
const files = Array.from(file.ReadPathSync(dirpath));
return files.includes(normalizedPath);
}
/**
* 重写内置函数,解决每次读取不存在的文件时必然出现的、不可抑制的Error消息问题
*
* 该问题由于 [PR#2412](https://github.com/babalae/better-genshin-impact/pull/2412) 导致,
* 并且[看起来也不会修复](https://github.com/babalae/better-genshin-impact/issues/2474)
*/
function readTextSync(fullPath) {
if (fileExists(fullPath)) {
return file.readTextSync(fullPath);
} else {
throw new Error("FileNotFound: " + fullPath);
}
}
+213 -103
View File
@@ -1,103 +1,213 @@
const defaultReplacementMap = {
监: "盐",
卵: "卯",
};
async function waitForTextAppear(targetText, ocrRegion, timeout = 5000, retryInterval = 50, replacementMap = defaultReplacementMap) {
let x, y, width, height;
if (Array.isArray(ocrRegion)) {
[x, y, width, height] = ocrRegion;
} else if (typeof ocrRegion === "object" && ocrRegion !== null) {
({ x, y, width, height } = ocrRegion);
} else {
throw new Error("Invalid parameter 'ocrRegion'");
}
const debugThreshold = timeout / retryInterval / 3;
let startTime = Date.now();
let retryCount = 0; // 重试计数
while (Date.now() - startTime < timeout) {
let captureRegion = captureGameRegion();
try {
// 尝试 OCR 识别
let resList = captureRegion.findMulti(RecognitionObject.ocr(x, y, width, height)); // 指定识别区域
// 遍历识别结果,检查是否找到目标文本
for (let res of resList) {
// 后处理:根据替换映射表检查和替换错误识别的字符
let correctedText = res.text;
for (let [wrongChar, correctChar] of Object.entries(replacementMap)) {
correctedText = correctedText.replace(new RegExp(wrongChar, "g"), correctChar);
}
if (correctedText.includes(targetText)) {
return { success: true, wait_time: Date.now() - startTime };
}
}
} catch (error) {
log.warn(`页面标志识别失败,正在进行第 ${retryCount} 次重试...`);
} finally {
retryCount++; // 增加重试计数
if (retryCount > debugThreshold) {
let region = captureRegion.DeriveCrop(x, y, width, height);
region.DrawSelf("debug");
region.dispose();
}
captureRegion.dispose();
}
await sleep(retryInterval);
}
return { success: false };
}
async function recognizeTextAndClick(targetText, ocrRegion, timeout = 5000, retryInterval = 50, replacementMap = defaultReplacementMap) {
let x, y, width, height;
if (Array.isArray(ocrRegion)) {
[x, y, width, height] = ocrRegion;
} else if (typeof ocrRegion === "object" && ocrRegion !== null) {
({ x, y, width, height } = ocrRegion);
} else {
throw new Error("Invalid parameter 'ocrRegion'");
}
const debugThreshold = timeout / retryInterval / 3;
let startTime = Date.now();
let retryCount = 0; // 重试计数
while (Date.now() - startTime < timeout) {
let captureRegion = captureGameRegion();
try {
// 尝试 OCR 识别
let resList = captureRegion.findMulti(RecognitionObject.ocr(x, y, width, height)); // 指定识别区域
// 遍历识别结果,检查是否找到目标文本
for (let res of resList) {
// 后处理:根据替换映射表检查和替换错误识别的字符
let correctedText = res.text;
for (let [wrongChar, correctChar] of Object.entries(replacementMap)) {
correctedText = correctedText.replace(new RegExp(wrongChar, "g"), correctChar);
}
if (correctedText.includes(targetText)) {
// 如果找到目标文本,计算并点击文字的中心坐标
let centerX = Math.round(res.x + res.width / 2);
let centerY = Math.round(res.y + res.height / 2);
await click(centerX, centerY);
await sleep(50);
return { success: true, x: centerX, y: centerY };
}
}
} catch (error) {
log.warn(`页面标志识别失败,正在进行第 ${retryCount} 次重试...`);
} finally {
retryCount++; // 增加重试计数
if (retryCount > debugThreshold) {
let region = captureRegion.DeriveCrop(x, y, width, height);
region.DrawSelf("debug");
region.dispose();
}
captureRegion.dispose();
}
await sleep(retryInterval);
}
return { success: false };
}
// 模块级变量,存储默认映射表
let replacementMap = {
监: "盐",
卵: "卯",
};
/** 允许用户在运行时动态修改库的默认映射表 */
function setGlobalReplacementMap(newMap) {
if (typeof newMap === "object" && newMap !== null) {
replacementMap = newMap;
}
}
/**
* 内部私有工具:校正文本
*/
function _correctText(text, customMap) {
if (!text) return "";
const map = customMap || replacementMap; // 如果没传自定义的,就用默认的
let correctedText = text;
for (const [wrong, right] of Object.entries(map)) {
correctedText = correctedText.replace(new RegExp(wrong, "g"), right);
}
return correctedText.trim();
}
/**
* 解析坐标
* @param {Array|Object} area - 坐标 [x, y, w, h] 或 {x, y, width, height}
*/
function parseRect(area) {
let x, y, width, height;
if (Array.isArray(area)) {
[x, y, width, height] = area;
} else if (typeof area === "object" && area !== null) {
({ x, y, width, height } = area);
} else {
throw new TypeError("Invalid area format");
}
return { x, y, width, height };
}
/**
* 屏幕截图包装器
* @param {Function} action - 接收 region 对象的异步函数
*/
async function withCapture(action) {
const region = captureGameRegion();
try {
return await action(region);
} finally {
region.dispose?.();
}
}
/**
* 局部裁剪包装器
* @param {object} region - 父级截图区域
* @param {object} rect - {x, y, width, height}
* @param {Function} action - 接收 crop 对象的异步函数
*/
async function withCrop(region, rect, action) {
const crop = region.DeriveCrop(rect.x, rect.y, rect.width, rect.height);
try {
return await action(crop);
} finally {
crop.dispose?.();
}
}
/**
* 安全地绘制区域标识(自动处理坐标解析与资源释放)
* @param {Array|Object} area - 坐标 [x, y, w, h] 或 {x, y, width, height}
* @param {object} [existingFrame=null] - (可选) 已有的截图对象。如果不传,则自动创建并释放新截图。
* @param {string} label - 绘制在框上的标签名
*/
async function drawRegion(area, existingFrame = null, label = null) {
const rect = parseRect(area);
// 内部绘制逻辑:只负责裁切和画图
const doDraw = async (f) => {
await withCrop(f, rect, async (crop) => {
const mark = label ? label : `rect_${rect.x}_${rect.y}_${rect.width}_${rect.height}`;
crop.DrawSelf(mark);
});
};
if (existingFrame) {
// 如果外部传了 frame,我们只负责释放 crop,不释放外部的 frame
await doDraw(existingFrame);
} else {
// 如果没传,我们截一张新图,并在画完释放自己截的这张图
await withCapture(async (tempFrame) => {
await doDraw(tempFrame);
});
}
}
/**
* 快速判断区域内是否存在文本(单次检查)
*/
async function isTextExistedInRegion(searchText, ocrRegion) {
const rect = parseRect(ocrRegion);
return await withCapture(async (captureRegion) => {
const result = captureRegion.find(RecognitionObject.ocr(rect.x, rect.y, rect.width, rect.height));
if (!result || !result.text) return false;
const text = result.text;
return (searchText instanceof RegExp) ? !!text.match(searchText) : text.includes(searchText);
});
}
/**
* 获取区域内的文本(带重试机制)
*/
async function getTextInRegion(ocrRegion, timeout = 5000, retryInterval = 50, replacementMap = null) {
const rect = parseRect(ocrRegion);
const debugThreshold = timeout / retryInterval / 3;
const startTime = Date.now();
let retryCount = 0;
while (Date.now() - startTime < timeout) {
// 使用 withCapture 自动管理截图资源的生命周期
const result = await withCapture(async (captureRegion) => {
try {
const resList = captureRegion.findMulti(RecognitionObject.ocr(rect.x, rect.y, rect.width, rect.height));
// resList 通常不是真正的 JS Array,使用 .count 且使用下标访问
const count = resList.count || resList.Count || 0;
for (let i = 0; i < count; i++) {
const res = resList[i];
if (!res || !res.text) continue;
const corrected = _correctText(res.text, replacementMap);
// 如果识别到了有效文本(不为空),则返回
if (corrected) {
return corrected;
}
}
} catch (error) {
log.warn(`OCR 识别失败,正在进行第 ${retryCount} 次重试...`);
}
// 达到调试阈值时画框
if (++retryCount > debugThreshold) {
await drawRegion(rect, captureRegion, "debug");
}
return null;
});
if (result !== null) return result;
await sleep(retryInterval);
}
return null;
}
/**
* 等待特定文本出现
*/
async function waitForTextAppear(targetText, ocrRegion, timeout = 5000, retryInterval = 50, replacementMap = null) {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
const currentText = await getTextInRegion(ocrRegion, timeout, retryInterval, replacementMap);
if (currentText && currentText.includes(targetText)) {
return { success: true, wait_time: Date.now() - startTime };
}
// 此处不需要额外 sleep,因为 getTextInRegion 内部已经耗费了时间
}
return { success: false };
}
/**
* 识别文本并点击中心点
*/
async function recognizeTextAndClick(targetText, ocrRegion, timeout = 5000, retryInterval = 50, replacementMap = null) {
const rect = parseRect(ocrRegion);
const debugThreshold = timeout / retryInterval / 3;
const startTime = Date.now();
let retryCount = 0;
while (Date.now() - startTime < timeout) {
const clicked = await withCapture(async (captureRegion) => {
try {
const resList = captureRegion.findMulti(RecognitionObject.ocr(rect.x, rect.y, rect.width, rect.height));
// resList 通常不是真正的 JS Array,使用 .count 且使用下标访问
const count = resList.count || resList.Count || 0;
for (let i = 0; i < count; i++) {
const res = resList[i];
const correctedText = _correctText(res.text, replacementMap);
if (correctedText.includes(targetText)) {
const centerX = Math.round(res.x + res.width / 2);
const centerY = Math.round(res.y + res.height / 2);
await click(centerX, centerY);
await sleep(50);
return { success: true, x: centerX, y: centerY };
}
}
} catch (e) {
log.warn(`识别点击失败重试中...`);
}
if (++retryCount > debugThreshold) {
await drawRegion(rect, captureRegion);
}
return null;
});
if (clicked) return clicked;
await sleep(retryInterval);
}
return { success: false };
}
+5 -5
View File
@@ -1,4 +1,5 @@
eval(file.readTextSync("lib/ocr.js"));
eval(file.readTextSync("lib/lib.js"));
const rewardIcon = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/RewardIcon.png"), 1430, 760, 100, 70);
const tavernRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/TavernIcon.png"), 800, 450, 500, 330);
@@ -16,9 +17,9 @@ let currentState = "任意界面";
const outFile = "卡牌熟练度.json";
let allProficiencys = {};
try {
allProficiencys = JSON.parse(file.readTextSync(outFile));
allProficiencys = JSON.parse(readTextSync(outFile));
} catch (error) {
log.debug("历史熟练度文件不存在");
log.warn("读取卡牌熟练度失败: {0}", error.toString());
}
(async function () {
@@ -95,8 +96,7 @@ async function runAsPartner() {
log.info("辅助账号开始工作,如需停止请按下你设置的BetterGI停止按键");
while (true) {
log.info("等待对局邀请");
await waitForTextAppear("点击进行准备", [820, 70, 296, 31], 1800000);
keyPress("Y");
await waitForTextAppear("正在匹配对局", [870, 386, 181, 43], 1800000);
await recognizeTextAndClick("接受", [1177, 713, 82, 55]);
log.info("等待加载");
@@ -196,7 +196,7 @@ async function startChallenge() {
}
function recommendNextTeam(targetProficiency) {
log.info("当前牌组中卡牌已达成熟练度目标,请更换牌组内角色");
notification.Send("当前牌组中卡牌已达成熟练度目标,请更换牌组内角色");
const nextTeam = Object.fromEntries(
Object.entries(allProficiencys)
.filter(([_, v]) => v < targetProficiency)
+1 -1
View File
@@ -1,7 +1,7 @@
{
"manifest_version": 1,
"name": "七圣召唤卡牌熟练度速刷",
"version": "1.3",
"version": "1.4",
"bgi_version": "0.45.0",
"description": "七圣召唤卡牌熟练度速刷",
"authors": [