mirror of
https://github.com/babalae/bettergi-scripts-list.git
synced 2026-11-17 04:17:45 +00:00
1294 lines
No EOL
58 KiB
JavaScript
1294 lines
No EOL
58 KiB
JavaScript
let userName = settings.userName || "默认账户";
|
||
const mode = settings.runMode || "营养袋模式"
|
||
let recoveryFoodName = settings.recoveryFoodName || "";
|
||
let resurrectionFoodName = settings.resurrectionFoodName || "";
|
||
let attackFoodName = settings.attackFoodName || "";
|
||
let defenseFoodName = settings.defenseFoodName || "";
|
||
let otherFoodName = settings.otherFoodName || "";
|
||
let damageFoodName = settings.damageFoodName || "";
|
||
let resistanceFoodName = settings.resistanceFoodName || "";
|
||
let extraFoodName = settings.extraFoodName || "";
|
||
// 自动补充回血药设置
|
||
const autoRefillRecovery = settings.autoRefillRecovery || false;
|
||
const refillThreshold = parseInt(settings.refillThreshold) || 100;
|
||
const refillCount = settings.refillCount || "20";
|
||
const ocrRegion = {
|
||
x: 1420,
|
||
y: 586,
|
||
width: 350,
|
||
height: 40
|
||
};
|
||
const ocrRegion1 = {
|
||
x: 1420,
|
||
y: 687,
|
||
width: 350,
|
||
height: 40
|
||
};
|
||
const ocrRegion2 = {
|
||
x: 105,
|
||
y: 242,
|
||
width: 140,
|
||
height: 40
|
||
};
|
||
const ocrRegion3 = {
|
||
x: 810,
|
||
y: 574,
|
||
width: 140,
|
||
height: 40
|
||
};
|
||
const ocrRegion4 = {
|
||
x: 961,
|
||
y: 577,
|
||
width: 140,
|
||
height: 40
|
||
};
|
||
const ocrRegion5 = {
|
||
x: 892,
|
||
y: 580,
|
||
width: 140,
|
||
height: 40
|
||
};
|
||
const loadDelay = +settings.loadDelay || 800;
|
||
const stepDelay = +settings.stepDelay || 500;
|
||
let refreshTime = parseFloat(settings.refreshTime) || 4.0;
|
||
if (isNaN(refreshTime) || refreshTime < 0 || refreshTime >= 24) {
|
||
refreshTime = 4.0;
|
||
log.warn(`刷新时间设置错误,使用默认值4.0`);
|
||
}
|
||
// 计算刷新时间的小时和分钟
|
||
const refreshHour = Math.floor(refreshTime);
|
||
const refreshMinute = Math.floor((refreshTime - refreshHour) * 60);
|
||
log.info(`刷新时间为: ${refreshHour}:${String(refreshMinute).padStart(2, '0')}`);
|
||
|
||
// 正则特殊字符转义函数
|
||
function escapeRegExp(string) {
|
||
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||
}
|
||
(async function () {
|
||
// 检验账户名
|
||
async function getUserName() {
|
||
userName = userName.trim();
|
||
// 账户名规则:数字、中英文,长度1-20字符
|
||
if (!userName || !/^[\u4e00-\u9fa5A-Za-z0-9]{1,20}$/.test(userName)) {
|
||
log.error(`账户名${userName}违规,暂时使用默认账户名,请查看readme后修改`)
|
||
userName = "默认账户";
|
||
}
|
||
return userName;
|
||
}
|
||
|
||
async function close_join_world_popup_window() {
|
||
const game_region = captureGameRegion();
|
||
const text_x = 762;
|
||
const text_y = 29;
|
||
const text_w = 210;
|
||
const text_h = 40;
|
||
const ocr_res = game_region.find(RecognitionObject.ocr(text_x, text_y, text_w, text_h));
|
||
if (ocr_res) {
|
||
if (ocr_res.text.includes("进入世界申请")) {
|
||
log.info("检测到有人申请进入世界,拒绝申请");
|
||
click(1051, 51);//选择珍贵物品
|
||
await clickPNG('拒绝', 10);
|
||
}
|
||
}
|
||
game_region.dispose();
|
||
}
|
||
|
||
async function close_expired_stuff_popup_window() {
|
||
const game_region = captureGameRegion();
|
||
const text_x = 850;
|
||
const text_y = 273;
|
||
const text_w = 225;
|
||
const text_h = 51;
|
||
const ocr_res = game_region.find(RecognitionObject.ocr(text_x, text_y, text_w, text_h));
|
||
if (ocr_res) {
|
||
if (ocr_res.text.includes("物品过期")) {
|
||
log.info("检测到物品过期");
|
||
click(1000, 750);
|
||
await sleep(1000);
|
||
}
|
||
}
|
||
game_region.dispose();
|
||
}
|
||
|
||
/**
|
||
* 获取本地记录中当天4点至次日4点间的最早记录
|
||
* @param {string} filePath - 记录文件路径
|
||
* @returns {Promise<object>} 包含药品数据的对象
|
||
* 格式: { recovery: { count }, resurrection: { count }, attack: { count }, defense: { count }, other: { count }, damage: { count }, resistance: { count }, extra: { count }, initialized: { recovery, resurrection, attack, defense, other, damage, resistance, extra } }
|
||
*/
|
||
async function getLocalData(filePath) {
|
||
// 初始化返回结果
|
||
const result = {
|
||
recovery: null,
|
||
resurrection: null,
|
||
attack: null,
|
||
defense: null,
|
||
other: null,
|
||
damage: null,
|
||
resistance: null,
|
||
extra: null,
|
||
initialized: {
|
||
recovery: false,
|
||
resurrection: false,
|
||
attack: false,
|
||
defense: false,
|
||
other: false,
|
||
damage: false,
|
||
resistance: false,
|
||
extra: false
|
||
}
|
||
};
|
||
|
||
try {
|
||
// 尝试读取文件,不存在则直接返回空结果
|
||
const content = await file.readText(filePath);
|
||
const lines = content.split('\n').filter(line => line.trim());
|
||
|
||
if (lines.length === 0) return result;
|
||
|
||
// 获取当前时间范围(根据自定义刷新时间)
|
||
const now = new Date();
|
||
let startTime, endTime;
|
||
|
||
// 创建今天的刷新时间点
|
||
const todayRefresh = new Date(now);
|
||
todayRefresh.setHours(refreshHour, refreshMinute, 0, 0);
|
||
|
||
if (now < todayRefresh) {
|
||
// 当前时间在刷新时间前,时间范围为昨天刷新时间至今天刷新时间
|
||
startTime = new Date(todayRefresh);
|
||
startTime.setDate(startTime.getDate() - 1);
|
||
endTime = new Date(todayRefresh);
|
||
} else {
|
||
// 当前时间在刷新时间后,时间范围为今天刷新时间至明天刷新时间
|
||
startTime = new Date(todayRefresh);
|
||
endTime = new Date(todayRefresh);
|
||
endTime.setDate(endTime.getDate() + 1);
|
||
}
|
||
|
||
// 时间格式正则:匹配 "时间:YYYY/MM/DD HH:mm:ss"
|
||
const timeRegex = /时间:(\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2})/;
|
||
// 药品匹配正则
|
||
const recoveryRegex = new RegExp(`${escapeRegExp(recoveryFoodName)}-(\\d+)`);
|
||
const resurrectionRegex = new RegExp(`${escapeRegExp(resurrectionFoodName)}-(\\d+)`);
|
||
const attackRegex = new RegExp(`${escapeRegExp(attackFoodName)}-(\\d+)`);
|
||
const defenseRegex = new RegExp(`${escapeRegExp(defenseFoodName)}-(\\d+)`);
|
||
const otherRegex = new RegExp(`${escapeRegExp(otherFoodName)}-(\\d+)`);
|
||
const damageRegex = new RegExp(`${escapeRegExp(damageFoodName)}-(\\d+)`);
|
||
const resistanceRegex = new RegExp(`${escapeRegExp(resistanceFoodName)}-(\\d+)`);
|
||
const extraRegex = new RegExp(`${escapeRegExp(extraFoodName)}-(\\d+)`);
|
||
|
||
// 正向遍历:找到第一个小于startTime的行索引(边界)
|
||
let firstOutOfRangeIndex = -1; // 初始化为-1(表示所有行都在时间范围内)
|
||
for (let i = 0; i < lines.length; i++) {
|
||
const line = lines[i];
|
||
const timeMatch = line.match(timeRegex);
|
||
if (!timeMatch) continue;
|
||
|
||
const recordTime = new Date(timeMatch[1]);
|
||
|
||
// 找到第一个超出时间范围(小于startTime)的行,记录索引并终止正向遍历
|
||
if (recordTime < startTime) {
|
||
// 如果第一条记录时间在今天4点之前,直接返回空结果
|
||
if (i === 0) {
|
||
return result;
|
||
}
|
||
firstOutOfRangeIndex = i;
|
||
break;
|
||
}
|
||
}
|
||
|
||
// 反向遍历的起始索引:如果有超出范围的行,从边界上一行开始;否则从最后一行开始
|
||
const reverseStartIndex = firstOutOfRangeIndex === -1
|
||
? lines.length - 1
|
||
: firstOutOfRangeIndex - 1;
|
||
|
||
// 反向遍历的终止索引:0(顶部)
|
||
const reverseEndIndex = 0;
|
||
|
||
// 根据当前模式确定是否需要处理扩展类药品(筛选模式/综合模式下处理攻击/防御/其他/增伤/抗性/额外)
|
||
const needExtendedDrugs = mode === "筛选模式" || mode === "综合模式";
|
||
|
||
// 反向遍历:找时间范围内最早的药品记录
|
||
// 遍历范围:[reverseStartIndex, reverseEndIndex](从时间范围的最旧→最新)
|
||
for (let i = reverseStartIndex; i >= reverseEndIndex; i--) {
|
||
// 防止索引越界(比如边界上一行是-1时)
|
||
if (i < 0) break;
|
||
|
||
const line = lines[i];
|
||
const timeMatch = line.match(timeRegex);
|
||
if (!timeMatch) continue;
|
||
|
||
const recordTime = new Date(timeMatch[1]);
|
||
// 二次校验:确保记录在目标时间范围内(避免边界判断误差)
|
||
if (recordTime < startTime || recordTime >= endTime) {
|
||
continue;
|
||
}
|
||
|
||
// 匹配回血药:未初始化时才赋值
|
||
if (!result.initialized.recovery) {
|
||
const recoveryMatch = line.match(recoveryRegex);
|
||
if (recoveryMatch) {
|
||
result.recovery = { count: parseInt(recoveryMatch[1]) };
|
||
result.initialized.recovery = true;
|
||
}
|
||
}
|
||
|
||
// 匹配复活药:未初始化时才赋值
|
||
if (!result.initialized.resurrection) {
|
||
const resurrectionMatch = line.match(resurrectionRegex);
|
||
if (resurrectionMatch) {
|
||
result.resurrection = { count: parseInt(resurrectionMatch[1]) };
|
||
result.initialized.resurrection = true;
|
||
}
|
||
}
|
||
|
||
// 匹配攻击药:未初始化时才赋值,仅在筛选模式和综合模式下处理
|
||
if (needExtendedDrugs && !result.initialized.attack) {
|
||
const attackMatch = line.match(attackRegex);
|
||
if (attackMatch) {
|
||
result.attack = { count: parseInt(attackMatch[1]) };
|
||
result.initialized.attack = true;
|
||
}
|
||
}
|
||
|
||
// 匹配防御药:未初始化时才赋值,仅在筛选模式和综合模式下处理
|
||
if (needExtendedDrugs && !result.initialized.defense) {
|
||
const defenseMatch = line.match(defenseRegex);
|
||
if (defenseMatch) {
|
||
result.defense = { count: parseInt(defenseMatch[1]) };
|
||
result.initialized.defense = true;
|
||
}
|
||
}
|
||
|
||
// 匹配其他药:未初始化时才赋值,仅在筛选模式和综合模式下处理
|
||
if (needExtendedDrugs && !result.initialized.other) {
|
||
const otherMatch = line.match(otherRegex);
|
||
if (otherMatch) {
|
||
result.other = { count: parseInt(otherMatch[1]) };
|
||
result.initialized.other = true;
|
||
}
|
||
}
|
||
|
||
// 匹配增伤药:未初始化时才赋值,仅在筛选模式和综合模式下处理
|
||
if (needExtendedDrugs && !result.initialized.damage) {
|
||
const damageMatch = line.match(damageRegex);
|
||
if (damageMatch) {
|
||
result.damage = { count: parseInt(damageMatch[1]) };
|
||
result.initialized.damage = true;
|
||
}
|
||
}
|
||
|
||
// 匹配抗性药:未初始化时才赋值,仅在筛选模式和综合模式下处理
|
||
if (needExtendedDrugs && !result.initialized.resistance) {
|
||
const resistanceMatch = line.match(resistanceRegex);
|
||
if (resistanceMatch) {
|
||
result.resistance = { count: parseInt(resistanceMatch[1]) };
|
||
result.initialized.resistance = true;
|
||
}
|
||
}
|
||
|
||
// 匹配额外药:未初始化时才赋值,仅在筛选模式和综合模式下处理
|
||
if (needExtendedDrugs && !result.initialized.extra) {
|
||
const extraMatch = line.match(extraRegex);
|
||
if (extraMatch) {
|
||
result.extra = { count: parseInt(extraMatch[1]) };
|
||
result.initialized.extra = true;
|
||
}
|
||
}
|
||
|
||
// 所有需要的药品都找到,提前终止遍历(已拿到最早记录)
|
||
let allFound = result.initialized.recovery && result.initialized.resurrection;
|
||
if (needExtendedDrugs) {
|
||
allFound = allFound && result.initialized.attack && result.initialized.defense && result.initialized.other
|
||
&& result.initialized.damage && result.initialized.resistance && result.initialized.extra;
|
||
}
|
||
if (allFound) {
|
||
break;
|
||
}
|
||
}
|
||
return result;
|
||
} catch (error) {
|
||
// 文件不存在或读取错误时返回空结果
|
||
return result;
|
||
}
|
||
}
|
||
|
||
async function updateRecord(filePath, currentRecovery, currentResurrection, currentAttack, currentDefense, currentOther, currentDamage, currentResistance, currentExtra, deleteSameDayRecords = false) {
|
||
// 生成当前时间字符串
|
||
const now = new Date();
|
||
const timeStr = `${now.getFullYear()}/${
|
||
String(now.getMonth() + 1).padStart(2, '0')
|
||
}/${
|
||
String(now.getDate()).padStart(2, '0')
|
||
} ${
|
||
String(now.getHours()).padStart(2, '0')
|
||
}:${
|
||
String(now.getMinutes()).padStart(2, '0')
|
||
}:${
|
||
String(now.getSeconds()).padStart(2, '0')
|
||
}`;
|
||
|
||
// 根据当前模式确定是否需要处理扩展类药品(筛选模式/综合模式下处理攻击/防御/其他/增伤/抗性/额外)
|
||
const needExtendedDrugs = mode === "筛选模式" || mode === "综合模式";
|
||
|
||
// 基础药品:回血药和复活药
|
||
const baseDrugs = [
|
||
{ name: recoveryFoodName, count: currentRecovery },
|
||
{ name: resurrectionFoodName, count: currentResurrection }
|
||
];
|
||
|
||
// 根据模式确定要处理的药品列表
|
||
let drugs = [...baseDrugs];
|
||
|
||
// 在筛选模式和综合模式下添加扩展类药品
|
||
if (needExtendedDrugs) {
|
||
drugs = drugs.concat([
|
||
{ name: attackFoodName, count: currentAttack },
|
||
{ name: defenseFoodName, count: currentDefense },
|
||
{ name: otherFoodName, count: currentOther },
|
||
{ name: damageFoodName, count: currentDamage },
|
||
{ name: resistanceFoodName, count: currentResistance },
|
||
{ name: extraFoodName, count: currentExtra }
|
||
]);
|
||
}
|
||
|
||
// 生成记录,只包含name不为空且数量>0的数据
|
||
const records = drugs
|
||
.filter(drug => drug.name.trim() && drug.count > 0)
|
||
.map(drug => `时间:${timeStr}-${drug.name}-${drug.count}`);
|
||
|
||
// 如果没有需要记录的数据,直接返回
|
||
if (records.length === 0) {
|
||
log.info("没有需要记录的数据");
|
||
return true;
|
||
}
|
||
|
||
try {
|
||
let content = await file.readText(filePath);
|
||
let lines = content.split('\n').filter(line => line.trim());
|
||
|
||
if (lines.length === 0) {
|
||
// 文件为空,直接写入新记录
|
||
await file.writeText(filePath, records.join('\n'));
|
||
return true;
|
||
}
|
||
|
||
// 如果需要删除当天同名记录
|
||
if (deleteSameDayRecords) {
|
||
// 获取当前时间范围(根据自定义刷新时间)
|
||
let startTime, endTime;
|
||
|
||
// 创建今天的刷新时间点
|
||
const todayRefresh = new Date(now);
|
||
todayRefresh.setHours(refreshHour, refreshMinute, 0, 0);
|
||
|
||
if (now < todayRefresh) {
|
||
// 当前时间在刷新时间前,时间范围为昨天刷新时间至今天刷新时间
|
||
startTime = new Date(todayRefresh);
|
||
startTime.setDate(startTime.getDate() - 1);
|
||
endTime = new Date(todayRefresh);
|
||
} else {
|
||
// 当前时间在刷新时间后,时间范围为今天刷新时间至明天刷新时间
|
||
startTime = new Date(todayRefresh);
|
||
endTime = new Date(todayRefresh);
|
||
endTime.setDate(endTime.getDate() + 1);
|
||
}
|
||
|
||
// 根据当前模式确定是否需要处理扩展类药品(筛选模式/综合模式下处理攻击/防御/其他/增伤/抗性/额外)
|
||
const needExtendedDrugs = mode === "筛选模式" || mode === "综合模式";
|
||
|
||
// 基础药品:回血药和复活药
|
||
const baseDrugs = [recoveryFoodName, resurrectionFoodName];
|
||
|
||
// 根据模式确定要处理的药品列表
|
||
let drugs = [...baseDrugs];
|
||
|
||
// 在筛选模式和综合模式下添加扩展类药品
|
||
if (needExtendedDrugs) {
|
||
drugs = drugs.concat([attackFoodName, defenseFoodName, otherFoodName, damageFoodName, resistanceFoodName, extraFoodName]);
|
||
}
|
||
|
||
// 创建药品匹配正则,只处理需要记录的药品
|
||
const regexList = drugs
|
||
.filter(name => name.trim())
|
||
.map(name => new RegExp(`${escapeRegExp(name)}-\\d+$`));
|
||
|
||
// 过滤掉当天时间范围内的同名记录
|
||
lines = lines.filter(line => {
|
||
const timeMatch = line.match(/时间:(\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2})/);
|
||
if (!timeMatch) return true;
|
||
|
||
const recordTime = new Date(timeMatch[1]);
|
||
// 检查是否在当天时间范围内
|
||
if (recordTime >= startTime && recordTime < endTime) {
|
||
// 检查是否为需要记录的药品记录
|
||
for (const regex of regexList) {
|
||
if (regex.test(line)) {
|
||
return false; // 删除该记录
|
||
}
|
||
}
|
||
}
|
||
return true; // 保留该记录
|
||
});
|
||
}
|
||
|
||
// 添加新记录到最前面
|
||
lines.unshift(...records);
|
||
|
||
// 只保留30天内的记录
|
||
const thirtyDaysAgo = new Date();
|
||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
||
|
||
const recentLines = lines.filter(line => {
|
||
const timeMatch = line.match(/时间:(\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2})/);
|
||
if (!timeMatch) return false;
|
||
const lineTime = new Date(timeMatch[1]);
|
||
return lineTime >= thirtyDaysAgo;
|
||
});
|
||
|
||
// 写入文件
|
||
await file.writeText(filePath, recentLines.join('\n'));
|
||
return true;
|
||
} catch (error) {
|
||
// 文件不存在时创建新文件
|
||
await file.writeText(filePath, records.join('\n'));
|
||
return true;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 在指定区域内,用 0-9 的 PNG 模板做「多阈值 + 非极大抑制」数字识别,
|
||
* 最终把检测到的数字按左右顺序拼成一个整数返回。
|
||
*
|
||
* @param {string} numberPngFilePath - 存放 0.png ~ 9.png 的文件夹路径(不含文件名)
|
||
* @param {number} x - 待识别区域的左上角 x 坐标,默认 0
|
||
* @param {number} y - 待识别区域的左上角 y 坐标,默认 0
|
||
* @param {number} w - 待识别区域的宽度,默认 1920
|
||
* @param {number} h - 待识别区域的高度,默认 1080
|
||
* @param {number} maxThreshold - 模板匹配起始阈值,默认 0.95(最高可信度)
|
||
* @param {number} minThreshold - 模板匹配最低阈值,默认 0.8(最低可信度)
|
||
* @param {number} splitCount - 在 maxThreshold 与 minThreshold 之间做几次等间隔阈值递减,默认 3
|
||
* @param {number} maxOverlap - 非极大抑制时允许的最大重叠像素,默认 2;只要 x 或 y 方向重叠大于该值即视为重复框
|
||
*
|
||
* @returns {number} 识别出的整数;若没有任何有效数字框则返回 -1
|
||
*
|
||
* @example
|
||
* const mora = await numberTemplateMatch('摩拉数字', 860, 70, 200, 40);
|
||
* if (mora >= 0) console.log(`当前摩拉:${mora}`);
|
||
*/
|
||
async function numberTemplateMatch(
|
||
numberPngFilePath,
|
||
x = 0, y = 0, w = 1920, h = 1080,
|
||
maxThreshold = 0.95,
|
||
minThreshold = 0.8,
|
||
splitCount = 3,
|
||
maxOverlap = 2
|
||
) {
|
||
let ros = [];
|
||
for (let i = 0; i <= 9; i++) {
|
||
ros[i] = RecognitionObject.TemplateMatch(
|
||
file.ReadImageMatSync(`${numberPngFilePath}/${i}.png`), x, y, w, h);
|
||
}
|
||
|
||
function setThreshold(roArr, newThreshold) {
|
||
for (let i = 0; i < roArr.length; i++) {
|
||
roArr[i].Threshold = newThreshold;
|
||
roArr[i].InitTemplate();
|
||
}
|
||
}
|
||
|
||
const gameRegion = captureGameRegion();
|
||
const allCandidates = [];
|
||
|
||
/* 1. splitCount 次等间隔阈值递减 */
|
||
try{
|
||
for (let k = 0; k < splitCount; k++) {
|
||
const curThr = maxThreshold - (maxThreshold - minThreshold) * k / Math.max(splitCount - 1, 1);
|
||
setThreshold(ros, curThr);
|
||
/* 2. 0-9 每个模板跑一遍,所有框都收 */
|
||
for (let digit = 0; digit <= 9; digit++) {
|
||
const res = gameRegion.findMulti(ros[digit]);
|
||
if (res.count === 0) continue;
|
||
for (let i = 0; i < res.count; i++) {
|
||
const box = res[i];
|
||
allCandidates.push({
|
||
digit: digit,
|
||
x: box.x,
|
||
y: box.y,
|
||
w: box.width,
|
||
h: box.height,
|
||
thr: curThr
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}finally {
|
||
gameRegion.dispose();
|
||
}
|
||
|
||
/* 3. 无结果提前返回 -1 */
|
||
if (allCandidates.length === 0) {
|
||
return -1;
|
||
}
|
||
|
||
/* 4. 非极大抑制(必须 x、y 两个方向重叠都 > maxOverlap 才视为重复) */
|
||
const adopted = [];
|
||
for (const c of allCandidates) {
|
||
let overlap = false;
|
||
for (const a of adopted) {
|
||
const xOverlap = Math.max(0, Math.min(c.x + c.w, a.x + a.w) - Math.max(c.x, a.x));
|
||
const yOverlap = Math.max(0, Math.min(c.y + c.h, a.y + a.h) - Math.max(c.y, a.y));
|
||
if (xOverlap > maxOverlap && yOverlap > maxOverlap) {
|
||
overlap = true;
|
||
break;
|
||
}
|
||
}
|
||
if (!overlap) {
|
||
adopted.push(c);
|
||
//log.info(`在 [${c.x},${c.y},${c.w},${c.h}] 找到数字 ${c.digit},匹配阈值=${c.thr}`);
|
||
}
|
||
}
|
||
|
||
/* 5. 按 x 排序,拼整数;仍无有效框时返回 -1 */
|
||
if (adopted.length === 0) return -1;
|
||
adopted.sort((a, b) => a.x - b.x);
|
||
|
||
return adopted.reduce((num, item) => num * 10 + item.digit, 0);
|
||
}
|
||
|
||
/**
|
||
* 识别背包中指定物品的数量
|
||
* @param {string} itemName - 物品名称(仅用于日志)
|
||
* @param {number} x - 数字区域左上角x坐标
|
||
* @param {number} y - 数字区域左上角y坐标
|
||
* @param {number} width - 数字区域宽度
|
||
* @param {number} height - 数字区域高度
|
||
* @returns {Promise<string>} 识别到的数字字符串(可能为空)
|
||
*/
|
||
async function getFoodCount(itemName, ocrRegion) {
|
||
for (let i = 0; i < 5; i++) {
|
||
try {
|
||
// 使用numberTemplateMatch函数识别数字
|
||
const count = await numberTemplateMatch(
|
||
'assets/RecognitionObject/背包数字', // 数字模板文件夹路径
|
||
ocrRegion.x, ocrRegion.y, ocrRegion.width, ocrRegion.height
|
||
);
|
||
const digits = count === -1 ? '' : count.toString();
|
||
log.info(`识别到${itemName}数量为${digits}`);
|
||
//log.info(`识别到${itemName}识别区域为${x}, ${y}, ${width}, ${height}`)
|
||
return digits; // 成功识别即返回
|
||
} catch (error) {
|
||
log.error(`识别${itemName}数量时发生错误: ${error.message}`);
|
||
}
|
||
if (i < 5 - 1) await sleep(50);
|
||
}
|
||
return ''; // 未找到时返回空字符串
|
||
}
|
||
|
||
async function recognizeFoodItemByOCR(ocrRegion, pattern) {
|
||
let captureRegion = null;
|
||
try {
|
||
const ocrRo = RecognitionObject.ocr(ocrRegion.x, ocrRegion.y, ocrRegion.width, ocrRegion.height);
|
||
captureRegion = captureGameRegion();
|
||
const resList = captureRegion.findMulti(ocrRo);
|
||
|
||
if (!resList || resList.length === 0) {
|
||
log.warn("OCR未识别到任何文本");
|
||
return { name: null, count: null };
|
||
}
|
||
|
||
for (const res of resList) {
|
||
if (!res || !res.text) {
|
||
continue;
|
||
}
|
||
const match = res.text.match(pattern);
|
||
if (match) {
|
||
let name = null;
|
||
let count = null;
|
||
|
||
if (match[1]) {
|
||
name = match[1].trim();
|
||
}
|
||
|
||
if (match[2]) {
|
||
count = parseInt(match[2]);
|
||
if (isNaN(count)) {
|
||
count = null;
|
||
}
|
||
}
|
||
|
||
if (name || count) {
|
||
return { name, count };
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch (error) {
|
||
log.error(`OCR识别时发生异常: ${error.message}`);
|
||
}
|
||
finally {
|
||
if (captureRegion) {
|
||
captureRegion.dispose();
|
||
}
|
||
}
|
||
return { name: null, count: null };
|
||
}
|
||
|
||
async function findAndClick(target, doClick = true, maxAttempts = 60) {
|
||
for (let i = 0; i < maxAttempts; i++) {
|
||
const rg = captureGameRegion();
|
||
try {
|
||
const res = rg.find(target);
|
||
if (res.isExist()) { await sleep(50 * 2 + 50); if (doClick) { res.click(); } return true; }
|
||
} finally { rg.dispose(); }
|
||
if (i < maxAttempts - 1) await sleep(50);
|
||
}
|
||
return false;
|
||
}
|
||
|
||
async function clickPNG(png, maxAttempts = 20, doClick=true) {
|
||
//log.info(`调试-点击目标${png},重试次数${maxAttempts}`);
|
||
const pngRo = RecognitionObject.TemplateMatch(file.ReadImageMatSync(`assets/RecognitionObject/${png}.png`));
|
||
pngRo.Threshold = 0.95;
|
||
pngRo.InitTemplate();
|
||
return await findAndClick(pngRo, doClick, maxAttempts);
|
||
}
|
||
|
||
// 生成药品描述的函数
|
||
async function generateDrugDescription(drugName, diffValue,changes) {
|
||
if (!drugName.trim()) return;
|
||
|
||
let desc = "";
|
||
if (diffValue > 0) {
|
||
desc = `- ${drugName}:消耗 ${diffValue} 个`;
|
||
} else if (diffValue < 0) {
|
||
desc = `- ${drugName}:新增 ${-diffValue} 个`;
|
||
} else {
|
||
desc = `- ${drugName}:无变化`;
|
||
}
|
||
changes.push(desc);
|
||
}
|
||
|
||
async function main() {
|
||
let recoveryNumber = 0;
|
||
let resurrectionNumber = 0;
|
||
let attackNumber = 0;
|
||
let defenseNumber = 0;
|
||
let otherNumber = 0;
|
||
let damageNumber = 0;
|
||
let resistanceNumber = 0;
|
||
let extraNumber = 0;
|
||
|
||
// 进入界面的通用函数
|
||
async function enterInterface(interfaceType, maxRetries = 5) {
|
||
let retryCount = 0;
|
||
let successClick = false;
|
||
|
||
while (retryCount < maxRetries && !successClick) {
|
||
retryCount++;
|
||
await close_join_world_popup_window();
|
||
|
||
if (interfaceType === 'nutrition_bag') {
|
||
// 营养袋模式:进入小道具界面
|
||
click(1051, 51); // 选择小道具
|
||
await sleep(loadDelay);
|
||
|
||
if (await clickPNG('拒绝', 3)) {
|
||
log.info("检测到进入世界申请,已拒绝,重新尝试点击分类标签");
|
||
await sleep(stepDelay);
|
||
continue;
|
||
}
|
||
|
||
if (await clickPNG('营养袋', 1, false)) {
|
||
successClick = true;
|
||
log.info("成功进入小道具界面");
|
||
break;
|
||
}
|
||
} else if (interfaceType === 'filter') {
|
||
// 筛选模式:进入食物界面
|
||
click(863, 51); // 选择食物
|
||
await sleep(loadDelay);
|
||
|
||
if (await clickPNG('拒绝', 3)) {
|
||
log.info("检测到进入世界申请,已拒绝,重新尝试点击分类标签");
|
||
await sleep(stepDelay);
|
||
continue;
|
||
}
|
||
|
||
if (await clickPNG('筛选1', 1, false) || await clickPNG('筛选2', 1, false)) {
|
||
successClick = true;
|
||
log.info("成功进入食物界面");
|
||
break;
|
||
}
|
||
}
|
||
|
||
log.warn(`尝试点击分类标签失败,第${retryCount}次重试`);
|
||
await sleep(stepDelay);
|
||
}
|
||
|
||
return successClick;
|
||
}
|
||
|
||
// 搜索和识别药品的通用函数
|
||
async function searchAndRecognizeDrug(drugName, drugType) {
|
||
if (!drugName.trim()) return 0;
|
||
|
||
await clickPNG('筛选1', 1);
|
||
await clickPNG('筛选2', 1);
|
||
await clickPNG('重置');
|
||
await sleep(stepDelay);
|
||
await clickPNG('搜索');
|
||
await sleep(loadDelay);
|
||
log.info(`搜索${drugName}`);
|
||
inputText(drugName);
|
||
await clickPNG('确认筛选');
|
||
await sleep(loadDelay);
|
||
const countStr = await getFoodCount(drugName, ocrRegion2);
|
||
const count = Number(countStr || 0);
|
||
|
||
if (count === 0) {
|
||
notification.send(`【营养袋吃药统计】\n未识别到${drugType}数量\n药品名:${drugName}\n设置数量为:0`);
|
||
}
|
||
|
||
return count;
|
||
}
|
||
|
||
// 营养袋药品识别的通用函数
|
||
async function recognizeNutritionBagDrug(ocrRegionId, pattern, drugType) {
|
||
let result = await recognizeFoodItemByOCR(ocrRegionId, pattern);
|
||
if (result.name && result.count !== null) {
|
||
log.info(`识别到: ${result.name}, 份数: ${result.count}`);
|
||
} else {
|
||
log.warn(`未识别到有效的${drugType}信息`);
|
||
}
|
||
const count = result.count || 0;
|
||
// OCR 失败时返回空字符串,让上层 hasAnyFoodName 检测和 shouldWrite 过滤能正确拦截,避免写入脏数据
|
||
const name = result.name || "";
|
||
|
||
if (count === 0) {
|
||
// 通知展示用兜底文本,保持提示友好
|
||
const displayName = name || `未识别到${drugType}名称`;
|
||
notification.send(`【营养袋吃药统计】\n未识别到${drugType}数量\n药品名:${displayName}\n设置数量为:0`);
|
||
}
|
||
|
||
return { count, name };
|
||
}
|
||
|
||
// 设置分辨率和缩放
|
||
setGameMetrics(1920, 1080, 1);
|
||
await genshin.returnMainUi();
|
||
keyPress("B");//打开背包
|
||
await sleep(1000);
|
||
// 关闭弹窗
|
||
await close_expired_stuff_popup_window();
|
||
await close_join_world_popup_window();
|
||
await sleep(loadDelay);
|
||
|
||
if (mode === "综合模式") {
|
||
// 综合模式:回血药和复活药通过营养袋模式获取,扩展类药品(攻击/防御/其他/增伤/抗性/额外)通过筛选模式获取
|
||
|
||
// 1. 先处理营养袋模式(识别回血药和复活药)
|
||
const successClick = await enterInterface('nutrition_bag');
|
||
if (successClick) {
|
||
await clickPNG('营养袋', 1);
|
||
await sleep(loadDelay);
|
||
const pattern = /(.+?)\s*[(\(](\d+)[份\s]*[)\)]/;
|
||
|
||
// 使用模块化函数识别各种药品
|
||
const recoveryResult = await recognizeNutritionBagDrug(ocrRegion, pattern, '回血药');
|
||
recoveryNumber = recoveryResult.count;
|
||
// 仅在 OCR 识别到名字时才覆盖,失败时保留用户配置的名字
|
||
if (recoveryResult.name) {
|
||
recoveryFoodName = recoveryResult.name;
|
||
}
|
||
|
||
const resurrectionResult = await recognizeNutritionBagDrug(ocrRegion1, pattern, '复活药');
|
||
resurrectionNumber = resurrectionResult.count;
|
||
// 仅在 OCR 识别到名字时才覆盖,失败时保留用户配置的名字
|
||
if (resurrectionResult.name) {
|
||
resurrectionFoodName = resurrectionResult.name;
|
||
}
|
||
}
|
||
// 2. 然后处理筛选模式(识别扩展类药品:攻击/防御/其他/增伤/抗性/额外药,只有填了名字才筛选)
|
||
// 检查是否需要进行筛选(任一扩展类药品名字已填)
|
||
const needFilter = !!attackFoodName.trim() || !!defenseFoodName.trim() || !!otherFoodName.trim()
|
||
|| !!damageFoodName.trim() || !!resistanceFoodName.trim() || !!extraFoodName.trim();
|
||
|
||
if (needFilter) {
|
||
const successClick = await enterInterface('filter');
|
||
if (successClick) {
|
||
// 使用模块化函数识别各种药品
|
||
attackNumber = await searchAndRecognizeDrug(attackFoodName, '攻击药');
|
||
defenseNumber = await searchAndRecognizeDrug(defenseFoodName, '防御药');
|
||
otherNumber = await searchAndRecognizeDrug(otherFoodName, '其他药');
|
||
damageNumber = await searchAndRecognizeDrug(damageFoodName, '增伤药');
|
||
resistanceNumber = await searchAndRecognizeDrug(resistanceFoodName, '抗性药');
|
||
extraNumber = await searchAndRecognizeDrug(extraFoodName, '额外药');
|
||
|
||
// 重置筛选
|
||
await clickPNG('筛选1', 1);
|
||
await clickPNG('筛选2', 1);
|
||
await clickPNG('重置');
|
||
await sleep(stepDelay);
|
||
await clickPNG('确认筛选');
|
||
}
|
||
}
|
||
} else if (mode === "营养袋模式") {
|
||
// 使用通用进入界面函数
|
||
const successClick = await enterInterface('nutrition_bag');
|
||
|
||
if (successClick) {
|
||
await clickPNG('营养袋', 1);
|
||
await sleep(loadDelay);
|
||
const pattern = /(.+?)\s*[(\(](\d+)[份\s]*[)\)]/;
|
||
|
||
// 使用模块化函数识别各种药品
|
||
const recoveryResult = await recognizeNutritionBagDrug(ocrRegion, pattern, '回血药');
|
||
recoveryNumber = recoveryResult.count;
|
||
// 仅在 OCR 识别到名字时才覆盖,失败时保留用户配置的名字
|
||
if (recoveryResult.name) {
|
||
recoveryFoodName = recoveryResult.name;
|
||
}
|
||
|
||
const resurrectionResult = await recognizeNutritionBagDrug(ocrRegion1, pattern, '复活药');
|
||
resurrectionNumber = resurrectionResult.count;
|
||
// 仅在 OCR 识别到名字时才覆盖,失败时保留用户配置的名字
|
||
if (resurrectionResult.name) {
|
||
resurrectionFoodName = resurrectionResult.name;
|
||
}
|
||
}
|
||
} else if (mode === "筛选模式") {
|
||
// 筛选模式:处理所有填写了名称的药品(回血/复活/攻击/防御/其他/增伤/抗性/额外)
|
||
// 使用通用进入界面函数
|
||
const successClick = await enterInterface('filter');
|
||
|
||
if (successClick) {
|
||
// 使用模块化函数识别各种药品
|
||
recoveryNumber = await searchAndRecognizeDrug(recoveryFoodName, '回血药');
|
||
resurrectionNumber = await searchAndRecognizeDrug(resurrectionFoodName, '复活药');
|
||
attackNumber = await searchAndRecognizeDrug(attackFoodName, '攻击药');
|
||
defenseNumber = await searchAndRecognizeDrug(defenseFoodName, '防御药');
|
||
otherNumber = await searchAndRecognizeDrug(otherFoodName, '其他药');
|
||
damageNumber = await searchAndRecognizeDrug(damageFoodName, '增伤药');
|
||
resistanceNumber = await searchAndRecognizeDrug(resistanceFoodName, '抗性药');
|
||
extraNumber = await searchAndRecognizeDrug(extraFoodName, '额外药');
|
||
|
||
// 重置筛选
|
||
await clickPNG('筛选1', 1);
|
||
await clickPNG('筛选2', 1);
|
||
await clickPNG('重置');
|
||
await sleep(stepDelay);
|
||
await clickPNG('确认筛选');
|
||
}
|
||
}
|
||
|
||
await genshin.returnMainUi();
|
||
return { recoveryNumber, resurrectionNumber, attackNumber, defenseNumber, otherNumber, damageNumber, resistanceNumber, extraNumber };
|
||
}
|
||
|
||
/**
|
||
* 自动补充回血药功能
|
||
* 当回血药数量低于阈值时,自动前往烹饪锅制作回血药
|
||
* @param {number} currentRecovery - 当前回血药数量
|
||
*/
|
||
async function autoRefillRecoveryFood(currentRecovery) {
|
||
if (!autoRefillRecovery) {
|
||
return false;
|
||
}
|
||
|
||
if (!recoveryFoodName.trim()) {
|
||
log.warn("未设置回血药名称,无法自动补充");
|
||
return false;
|
||
}
|
||
|
||
if (currentRecovery === 0 && initRecovery > 0) {
|
||
log.warn(`回血药当前数量为0但初始数量为${initRecovery},疑似识别失败,跳过自动烹饪`);
|
||
return false;
|
||
}
|
||
|
||
if (currentRecovery >= refillThreshold) {
|
||
log.info(`回血药数量(${currentRecovery})高于阈值(${refillThreshold}),无需补充`);
|
||
return false;
|
||
}
|
||
|
||
if (initRecovery <= currentRecovery) {
|
||
log.info(`回血药无消耗(初始:${initRecovery}, 当前:${currentRecovery}),无需补充`);
|
||
return false;
|
||
}
|
||
|
||
log.info(`回血药有消耗,同时数量(${currentRecovery})低于阈值(${refillThreshold}),开始自动补充,补充数量:${refillCount}`);
|
||
|
||
const stove = "蒙德炉子";
|
||
log.info(`正在前往${stove}进行料理制作`);
|
||
|
||
try {
|
||
let filePath = `assets/${stove}.json`;
|
||
await pathingScript.runFile(filePath);
|
||
} catch (error) {
|
||
log.error(`执行 ${stove} 路径时发生错误`);
|
||
return;
|
||
}
|
||
|
||
const res1 = await clickPNG("交互烹饪锅",20,false);
|
||
if (res1) {
|
||
keyPress("F");
|
||
} else {
|
||
log.warn("烹饪按钮未找到,正在寻找……");
|
||
let attempts = 0;
|
||
const maxAttempts = 3;
|
||
let foundInRetry = false;
|
||
while (attempts < maxAttempts) {
|
||
log.info(`第${attempts + 1}次尝试寻找烹饪按钮`);
|
||
keyPress("W");
|
||
const res2 = await clickPNG("交互烹饪锅",20,false);
|
||
if (res2) {
|
||
keyPress("F");
|
||
foundInRetry = true;
|
||
break;
|
||
} else {
|
||
attempts++;
|
||
await sleep(500);
|
||
}
|
||
}
|
||
if (!foundInRetry) {
|
||
log.error("多次未找到烹饪按钮,放弃");
|
||
return;
|
||
}
|
||
}
|
||
await clickPNG("料理制作",20,false);
|
||
//搜索回血药
|
||
await clickPNG('筛选1', 1);
|
||
await clickPNG('筛选2', 1);
|
||
await clickPNG('重置');
|
||
await sleep(stepDelay);
|
||
await clickPNG('搜索');
|
||
await sleep(loadDelay);
|
||
// 去除前缀
|
||
let searchName = recoveryFoodName.replace(/^.+的/, '');
|
||
log.info(`搜索${searchName}`);
|
||
inputText(searchName);
|
||
await clickPNG('确认筛选');
|
||
await sleep(loadDelay);
|
||
await clickPNG('制作');
|
||
await sleep(loadDelay);
|
||
await clickPNG('自动烹饪');
|
||
await sleep(stepDelay);
|
||
await clickPNG('选择烹饪数量',20,false);
|
||
await sleep(stepDelay);
|
||
await clickPNG('烹饪输入框');
|
||
await sleep(stepDelay);
|
||
inputText(refillCount);
|
||
await clickPNG('确认按钮');
|
||
await clickPNG('烹饪完成',20,false);
|
||
// 识别烹饪数量
|
||
let baseCount = 0;
|
||
let extraCount = 0;
|
||
let specialCount = 0;
|
||
const hasExtra = await clickPNG('额外物品', 20, false);
|
||
if (hasExtra) {
|
||
baseCount = await getFoodCount('基础料理', ocrRegion3);
|
||
extraCount = await getFoodCount('额外物品', ocrRegion4);
|
||
} else {
|
||
const hasSpecial = await clickPNG('多个物品', 20, false);
|
||
if (hasSpecial) {
|
||
baseCount = await getFoodCount('基础料理', ocrRegion3);
|
||
specialCount = await getFoodCount('特殊料理', ocrRegion4);
|
||
} else {
|
||
baseCount = await getFoodCount('料理', ocrRegion5);
|
||
}
|
||
}
|
||
log.info(`烹饪完成,基础回血药:${baseCount}个${extraCount > 0 ? `,额外回血药:${extraCount}个` : ''}${specialCount > 0 ? `,特殊回血药:${specialCount}个` : ''}`);
|
||
|
||
notification.send(`【营养袋吃药统计】\n\n✅ 自动补充回血药完成\n\n📊 补充前数量:${currentRecovery}个\n📊 制作基础回血药:${baseCount}个${extraCount > 0 ? `\n📊 制作额外回血药:${extraCount}个` : ''}${specialCount > 0 ? `\n📊 制作特殊回血药:${specialCount}个` : ''}\n📊 目标回血药:${recoveryFoodName}`);
|
||
|
||
await genshin.returnMainUi();
|
||
//往后走一步,防止被火烧
|
||
await keyDown("S");
|
||
await sleep(300);
|
||
await keyUp("S");
|
||
}
|
||
|
||
// 主执行流程
|
||
userName = await getUserName();
|
||
const recordPath = `assets/${userName}.txt`;
|
||
// 获取当前药物数量
|
||
const { recoveryNumber, resurrectionNumber, attackNumber, defenseNumber, otherNumber, damageNumber, resistanceNumber, extraNumber } = await main();
|
||
// 获取本地保存的数据
|
||
const localData = await getLocalData(recordPath);
|
||
// 确定初始化数据
|
||
let initRecovery, initResurrection, initAttack, initDefense, initOther, initDamage, initResistance, initExtra;
|
||
let useLocalDataAsInit = false;
|
||
|
||
// 检查本地数据初始化情况,只处理name不为空的数据
|
||
const hasLocalRecovery = recoveryFoodName.trim() && localData.initialized.recovery;
|
||
const hasLocalResurrection = resurrectionFoodName.trim() && localData.initialized.resurrection;
|
||
const hasLocalAttack = attackFoodName.trim() && localData.initialized.attack;
|
||
const hasLocalDefense = defenseFoodName.trim() && localData.initialized.defense;
|
||
const hasLocalOther = otherFoodName.trim() && localData.initialized.other;
|
||
const hasLocalDamage = damageFoodName.trim() && localData.initialized.damage;
|
||
const hasLocalResistance = resistanceFoodName.trim() && localData.initialized.resistance;
|
||
const hasLocalExtra = extraFoodName.trim() && localData.initialized.extra;
|
||
|
||
// 根据当前模式确定是否需要处理扩展类药品(筛选模式/综合模式下处理攻击/防御/其他/增伤/抗性/额外)
|
||
const needExtendedDrugs = mode === "筛选模式" || mode === "综合模式";
|
||
|
||
// 计算有效药品数量(name不为空的药品),只考虑当前模式下需要处理的药品
|
||
const baseFoods = [recoveryFoodName, resurrectionFoodName];
|
||
const allFoods = needExtendedDrugs
|
||
? [...baseFoods, attackFoodName, defenseFoodName, otherFoodName, damageFoodName, resistanceFoodName, extraFoodName]
|
||
: [...baseFoods];
|
||
const validFoodCount = allFoods.filter(name => name.trim()).length;
|
||
|
||
// 计算已读取到本地数据的有效药品数量,只考虑当前模式下需要处理的药品
|
||
const baseLoaded = [hasLocalRecovery, hasLocalResurrection];
|
||
const allLoaded = needExtendedDrugs
|
||
? [...baseLoaded, hasLocalAttack, hasLocalDefense, hasLocalOther, hasLocalDamage, hasLocalResistance, hasLocalExtra]
|
||
: [...baseLoaded];
|
||
const loadedFoodCount = allLoaded.filter(Boolean).length;
|
||
|
||
if (validFoodCount > 0 && validFoodCount === loadedFoodCount) {
|
||
// 情况1:所有有效药品(name不为空)都有本地数据
|
||
initRecovery = hasLocalRecovery ? localData.recovery.count : recoveryNumber;
|
||
initResurrection = hasLocalResurrection ? localData.resurrection.count : resurrectionNumber;
|
||
initAttack = hasLocalAttack ? localData.attack.count : attackNumber;
|
||
initDefense = hasLocalDefense ? localData.defense.count : defenseNumber;
|
||
initOther = hasLocalOther ? localData.other.count : otherNumber;
|
||
initDamage = hasLocalDamage ? localData.damage.count : damageNumber;
|
||
initResistance = hasLocalResistance ? localData.resistance.count : resistanceNumber;
|
||
initExtra = hasLocalExtra ? localData.extra.count : extraNumber;
|
||
useLocalDataAsInit = true;
|
||
log.info(`已读取到本地数据`)
|
||
} else {
|
||
// 情况2:部分有,部分无,用有的那个,缺的用当前数据
|
||
// 情况3:全部本地数据都没有,所有药品都使用当前数据作为初始数据
|
||
initRecovery = hasLocalRecovery ? localData.recovery.count : recoveryNumber;
|
||
initResurrection = hasLocalResurrection ? localData.resurrection.count : resurrectionNumber;
|
||
initAttack = hasLocalAttack ? localData.attack.count : attackNumber;
|
||
initDefense = hasLocalDefense ? localData.defense.count : defenseNumber;
|
||
initOther = hasLocalOther ? localData.other.count : otherNumber;
|
||
initDamage = hasLocalDamage ? localData.damage.count : damageNumber;
|
||
initResistance = hasLocalResistance ? localData.resistance.count : resistanceNumber;
|
||
initExtra = hasLocalExtra ? localData.extra.count : extraNumber;
|
||
if (loadedFoodCount === 0) {
|
||
log.info(`未读取到本地数据,所有药品使用当前数据作为初始数据`)
|
||
} else {
|
||
log.info(`未读取到全部的本地数据,缺失部分使用当前数据作为初始数据`)
|
||
}
|
||
}
|
||
|
||
// 判断是否需要写入(只写入填了名字的药品)
|
||
const shouldWriteRecovery = recoveryFoodName.trim() && recoveryNumber > 0;
|
||
const shouldWriteResurrection = resurrectionFoodName.trim() && resurrectionNumber > 0;
|
||
const shouldWriteAttack = attackFoodName.trim() && attackNumber > 0;
|
||
const shouldWriteDefense = defenseFoodName.trim() && defenseNumber > 0;
|
||
const shouldWriteOther = otherFoodName.trim() && otherNumber > 0;
|
||
const shouldWriteDamage = damageFoodName.trim() && damageNumber > 0;
|
||
const shouldWriteResistance = resistanceFoodName.trim() && resistanceNumber > 0;
|
||
const shouldWriteExtra = extraFoodName.trim() && extraNumber > 0;
|
||
const shouldWriteRecord = shouldWriteRecovery || shouldWriteResurrection || shouldWriteAttack || shouldWriteDefense || shouldWriteOther || shouldWriteDamage || shouldWriteResistance || shouldWriteExtra;
|
||
|
||
// 未配置任何药品名称时,提前提示并退出,避免误报"识别异常"
|
||
const hasAnyFoodName = recoveryFoodName.trim() || resurrectionFoodName.trim()
|
||
|| attackFoodName.trim() || defenseFoodName.trim() || otherFoodName.trim()
|
||
|| damageFoodName.trim() || resistanceFoodName.trim() || extraFoodName.trim();
|
||
if (!hasAnyFoodName) {
|
||
notification.send(`【营养袋吃药统计】\n\n⚠️ 未配置药品名称\n👤 账户:${userName}\n\n请在配置中至少填写一个药品名称`);
|
||
log.warn(`${userName}:未配置任何药品名称,跳过统计`);
|
||
return;
|
||
}
|
||
|
||
// initSelect处理逻辑
|
||
if (settings.initSelect && shouldWriteRecord) {
|
||
// 强制初始化:初始化数量和最后一次运行数量都设为当前值
|
||
await updateRecord(recordPath, recoveryNumber, resurrectionNumber, attackNumber, defenseNumber, otherNumber, damageNumber, resistanceNumber, extraNumber, deleteSameDayRecords=true);
|
||
|
||
// 构建通知消息
|
||
let initMsg = `【营养袋吃药统计】\n\n`;
|
||
initMsg += `📋 强制初始化完成!\n`;
|
||
initMsg += `👤 账户:${userName}\n\n`;
|
||
initMsg += `📊 初始药品数据:\n`;
|
||
|
||
let items = [];
|
||
if (shouldWriteRecovery) items.push(`- ${recoveryFoodName}:${recoveryNumber}个`);
|
||
if (shouldWriteResurrection) items.push(`- ${resurrectionFoodName}:${resurrectionNumber}个`);
|
||
if (shouldWriteAttack) items.push(`- ${attackFoodName}:${attackNumber}个`);
|
||
if (shouldWriteDefense) items.push(`- ${defenseFoodName}:${defenseNumber}个`);
|
||
if (shouldWriteOther) items.push(`- ${otherFoodName}:${otherNumber}个`);
|
||
if (shouldWriteDamage) items.push(`- ${damageFoodName}:${damageNumber}个`);
|
||
if (shouldWriteResistance) items.push(`- ${resistanceFoodName}:${resistanceNumber}个`);
|
||
if (shouldWriteExtra) items.push(`- ${extraFoodName}:${extraNumber}个`);
|
||
|
||
initMsg += items.join('\n');
|
||
|
||
notification.send(initMsg);
|
||
|
||
// 添加简单格式的日志记录
|
||
let initItemsSummary = items.map(item => item.replace(/- /g, "")).join(", ");
|
||
log.info(`${userName}:强制初始化完成|当前库存:${initItemsSummary}`);
|
||
return
|
||
}
|
||
|
||
if (shouldWriteRecord) {
|
||
// 使用当前的数据更新记录
|
||
await updateRecord(recordPath, recoveryNumber, resurrectionNumber, attackNumber, defenseNumber, otherNumber, damageNumber, resistanceNumber, extraNumber);
|
||
|
||
// 本地有初始记录
|
||
if(useLocalDataAsInit){
|
||
const diffRecovery = initRecovery - recoveryNumber;
|
||
const diffResurrection = initResurrection - resurrectionNumber;
|
||
|
||
// 根据当前模式确定是否需要处理扩展类药品(筛选模式/综合模式下处理攻击/防御/其他/增伤/抗性/额外)
|
||
const needExtendedDrugs = mode === "筛选模式" || mode === "综合模式";
|
||
const diffAttack = needExtendedDrugs ? initAttack - attackNumber : 0;
|
||
const diffDefense = needExtendedDrugs ? initDefense - defenseNumber : 0;
|
||
const diffOther = needExtendedDrugs ? initOther - otherNumber : 0;
|
||
const diffDamage = needExtendedDrugs ? initDamage - damageNumber : 0;
|
||
const diffResistance = needExtendedDrugs ? initResistance - resistanceNumber : 0;
|
||
const diffExtra = needExtendedDrugs ? initExtra - extraNumber : 0;
|
||
|
||
let changes = [];
|
||
|
||
await generateDrugDescription(recoveryFoodName, diffRecovery,changes);
|
||
await generateDrugDescription(resurrectionFoodName, diffResurrection,changes);
|
||
|
||
// 在筛选模式和综合模式下处理扩展类药品
|
||
if (needExtendedDrugs) {
|
||
await generateDrugDescription(attackFoodName, diffAttack,changes);
|
||
await generateDrugDescription(defenseFoodName, diffDefense,changes);
|
||
await generateDrugDescription(otherFoodName, diffOther,changes);
|
||
await generateDrugDescription(damageFoodName, diffDamage,changes);
|
||
await generateDrugDescription(resistanceFoodName, diffResistance,changes);
|
||
await generateDrugDescription(extraFoodName, diffExtra,changes);
|
||
}
|
||
|
||
// 构建通知消息
|
||
let logMsg = `【营养袋吃药统计】\n\n`;
|
||
logMsg += `📊 今日药品使用情况\n`;
|
||
logMsg += `👤 账户:${userName}\n\n`;
|
||
|
||
if (changes.every(change => change.includes("无变化"))) {
|
||
logMsg += `✅ 今日药物数量无变化\n\n`;
|
||
} else {
|
||
logMsg += `📝 使用记录:\n`;
|
||
logMsg += changes.join('\n');
|
||
logMsg += `\n\n`;
|
||
}
|
||
|
||
// 添加库存信息
|
||
const baseDrugs = [
|
||
{ name: recoveryFoodName, count: recoveryNumber },
|
||
{ name: resurrectionFoodName, count: resurrectionNumber }
|
||
];
|
||
|
||
let inventoryDrugs = [...baseDrugs];
|
||
|
||
// 在筛选模式和综合模式下添加扩展类药品的库存信息
|
||
if (needExtendedDrugs) {
|
||
inventoryDrugs = inventoryDrugs.concat([
|
||
{ name: attackFoodName, count: attackNumber },
|
||
{ name: defenseFoodName, count: defenseNumber },
|
||
{ name: otherFoodName, count: otherNumber },
|
||
{ name: damageFoodName, count: damageNumber },
|
||
{ name: resistanceFoodName, count: resistanceNumber },
|
||
{ name: extraFoodName, count: extraNumber }
|
||
]);
|
||
}
|
||
|
||
let inventory = inventoryDrugs
|
||
.filter(drug => drug.name.trim() && drug.count > 0)
|
||
.map(drug => `- ${drug.name}:${drug.count}个`);
|
||
|
||
if (inventory.length > 0) {
|
||
logMsg += `📦 当前库存:\n`;
|
||
logMsg += inventory.join('\n');
|
||
}
|
||
|
||
notification.send(logMsg);
|
||
|
||
// 添加简单格式的日志记录
|
||
let usageSummary = changes.every(change => change.includes("无变化")) ? "药物数量无变化" : changes.map(change => change.replace(/- /g, "")).join(", ");
|
||
let inventorySummary = inventory.length > 0 ? inventory.map(item => item.replace(/- /g, "")).join(", ") : "无";
|
||
log.info(`${userName}:今日使用情况|${usageSummary}|当前库存:${inventorySummary}`);
|
||
} else {
|
||
// 构建通知消息
|
||
let initMsg = `【营养袋吃药统计】\n\n`;
|
||
initMsg += `✅ 今日初始化完成!\n`;
|
||
initMsg += `👤 账户:${userName}\n\n`;
|
||
|
||
// 根据当前模式确定是否需要处理扩展类药品(筛选模式/综合模式下处理攻击/防御/其他/增伤/抗性/额外)
|
||
const needExtendedDrugs = mode === "筛选模式" || mode === "综合模式";
|
||
|
||
const baseDrugs = [
|
||
{ name: recoveryFoodName, count: initRecovery },
|
||
{ name: resurrectionFoodName, count: initResurrection }
|
||
];
|
||
|
||
const drugs = needExtendedDrugs
|
||
? [...baseDrugs,
|
||
{ name: attackFoodName, count: initAttack },
|
||
{ name: defenseFoodName, count: initDefense },
|
||
{ name: otherFoodName, count: initOther },
|
||
{ name: damageFoodName, count: initDamage },
|
||
{ name: resistanceFoodName, count: initResistance },
|
||
{ name: extraFoodName, count: initExtra }]
|
||
: [...baseDrugs];
|
||
|
||
let items = drugs
|
||
.filter(drug => drug.name.trim() && drug.count > 0)
|
||
.map(drug => `- ${drug.name}:${drug.count}个`);
|
||
|
||
if (items.length > 0) {
|
||
initMsg += `📊 初始药品数据:\n`;
|
||
initMsg += items.join('\n');
|
||
notification.send(initMsg);
|
||
|
||
// 添加简单格式的日志记录
|
||
let initItemsSummary = items.map(item => item.replace(/- /g, "")).join(", ");
|
||
log.info(`${userName}:初始化完成|当前库存:${initItemsSummary}`);
|
||
} else {
|
||
initMsg += `⚠️ 未识别到有效药品数据\n`;
|
||
notification.send(initMsg);
|
||
|
||
// 添加简单格式的日志记录
|
||
log.info(`${userName}:初始化完成|当前库存:无`);
|
||
}
|
||
}
|
||
} else {
|
||
// 构建通知消息
|
||
let msg = `【营养袋吃药统计】\n\n`;
|
||
msg += `⚠️ 识别异常提醒\n`;
|
||
msg += `👤 账户:${userName}\n\n`;
|
||
msg += `📋 当前药品数量识别不全\n\n`;
|
||
|
||
const drugs = [
|
||
{ name: recoveryFoodName, count: recoveryNumber },
|
||
{ name: resurrectionFoodName, count: resurrectionNumber },
|
||
{ name: attackFoodName, count: attackNumber },
|
||
{ name: defenseFoodName, count: defenseNumber },
|
||
{ name: otherFoodName, count: otherNumber },
|
||
{ name: damageFoodName, count: damageNumber },
|
||
{ name: resistanceFoodName, count: resistanceNumber },
|
||
{ name: extraFoodName, count: extraNumber }
|
||
];
|
||
|
||
let items = drugs
|
||
.filter(drug => drug.name.trim())
|
||
.map(drug => `- ${drug.name}:${drug.count}个`);
|
||
|
||
msg += `🔍 识别结果:\n`;
|
||
msg += items.join('\n');
|
||
msg += `\n\n`;
|
||
msg += `❌ 不更新记录\n`;
|
||
|
||
notification.send(msg);
|
||
|
||
// 添加简单格式的日志记录
|
||
log.info(`${userName}:识别异常,未更新记录|当前库存:无`);
|
||
}
|
||
|
||
// 自动补充回血药
|
||
if (autoRefillRecovery && shouldWriteRecord) {
|
||
await autoRefillRecoveryFood(recoveryNumber);
|
||
}
|
||
})(); |