bettergi-scripts-list/repo/js/自动购买商品/main.js
Leeon-666 4063d10088
自动购买商品 3.7.1 (#3749)
* 自动购买商品 3.7.1

* 1

* 2
2026-10-19 02:30:26 +08:00

1668 lines
65 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// fakeLog 函数,使用方法:将本函数放在主函数前,调用时请务必使用await,否则可能出现v8白框报错
// 在js开头处伪造该js结束运行的日志信息,如 await fakeLog("js脚本", true, true, 0);
// 在js结尾处伪造该js开始运行的日志信息,如 await fakeLog("js脚本", true, false, 2333);
// duration项目仅在伪造结束信息时有效,且无实际作用,可以任意填写,当你需要在日志中输出特定值时才需要,单位为毫秒
// 在调用地图追踪前伪造该地图追踪开始运行的日志信息,如 await fakeLog(`地图追踪.json`, false, true, 0);
// 在调用地图追踪后伪造该地图追踪结束运行的日志信息,如 await fakeLog(`地图追踪.json`, false, false, 0);
// 如此便可以在js运行过程中伪造地图追踪的日志信息,可以在日志分析等中查看
// name: 字符串,表示脚本或地图追踪的名称
// isJs: 布尔值,true表示脚本,false表示地图追踪
// isStart: 布尔值,true表示开始日志,false表示结束日志
// duration: 整数,表示脚本或地图追踪的运行时间(仅在结束日志时使用),单位为毫秒_基本填0即可
// 示例:
// JS脚本开始
// await fakeLog("js脚本名", true, true, 0);
// JS脚本结束
// await fakeLog("js脚本名", true, false, 0);
// 地图追踪开始
// await fakeLog("地图追踪名", false, true, 0);
// 地图追踪结束
// await fakeLog("地图追踪名", false, false, 0);
// 交互或拾取:"XXXX"
// await fakeLog("XXXX", false, false, 23333);
async function fakeLog(name, isJs, isStart, duration) {
await sleep(10);
const currentTime = Date.now();
// 参数检查
if (typeof name !== 'string') {
log.error("参数 'name' 必须是字符串类型!");
return;
}
if (typeof isJs !== 'boolean') {
log.error("参数 'isJs' 必须是布尔型!");
return;
}
if (typeof isStart !== 'boolean') {
log.error("参数 'isStart' 必须是布尔型!");
return;
}
if (typeof duration !== 'number' || !Number.isInteger(duration)) {
log.error("参数 'duration' 必须是整数!");
return;
}
// 将 currentTime 转换为 Date 对象并格式化为 HH:mm:ss.sss
const date = new Date(currentTime);
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
const milliseconds = String(date.getMilliseconds()).padStart(3, '0');
const formattedTime = `${hours}:${minutes}:${seconds}.${milliseconds}`;
// 将 duration 转换为分钟和秒,并保留三位小数
const durationInSeconds = duration / 1000; // 转换为秒
const durationMinutes = Math.floor(durationInSeconds / 60);
const durationSeconds = (durationInSeconds % 60).toFixed(3); // 保留三位小数
// 交互或拾取:"XXXX"
if (duration == 23333) {
log.info(`交互或拾取:"${name}"`);
return;
}
// 使用四个独立的 if 语句处理四种情况
if (isJs && isStart) {
// 处理 isJs = true 且 isStart = true 的情况
const logMessage = `正在伪造js开始的日志记录\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`------------------------------\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`→ 开始执行JS脚本: "${name}"`;
log.debug(logMessage);
}
if (isJs && !isStart) {
// 处理 isJs = true 且 isStart = false 的情况
const logMessage = `正在伪造js结束的日志记录\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`→ 脚本执行结束: "${name}", 耗时: ${durationMinutes}分${durationSeconds}秒\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`------------------------------`;
log.debug(logMessage);
}
if (!isJs && isStart) {
// 处理 isJs = false 且 isStart = true 的情况
const logMessage = `正在伪造地图追踪开始的日志记录\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`------------------------------\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`→ 开始执行地图追踪任务: "${name}"`;
log.debug(logMessage);
}
if (!isJs && !isStart) {
// 处理 isJs = false 且 isStart = false 的情况
const logMessage = `正在伪造地图追踪结束的日志记录\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`→ 脚本执行结束: "${name}", 耗时: ${durationMinutes}分${durationSeconds}秒\n\n` +
`[${formattedTime}] [INF] BetterGenshinImpact.Service.ScriptService\n` +
`------------------------------`;
log.debug(logMessage);
}
}
// ==================== 日志辅助函数 ====================
function logConditional(message) {
if (ignoreRecords || recordDebug) {
log.info(message);
} else {
log.debug(message);
}
}
// ==================== 加载外部数据文件 ====================
let npcData = {};
// 存储用户要购买的商品名称集合(中文名)
let userFoodsToBuy = new Set();
let userTagsToBuy = new Set(); // 标签名
let allTags = new Set(); // 所有可用标签(从 npcs.json 收集)
let requiredFoods = new Set(); // 所有需要加载图片的商品
let capacityLimitedFoods = new Set(); // 存储因背包容量已达上限而不再购买的商品名
let debugNpcFoods = null; // 调试指定:Map<npc名, Set<商品名>|null(全部商品)>,null 表示未启用
async function loadExternalData() {
try {
// 加载商人数据
const npcsContent = await file.readText("assets/npcs.json");
npcData = JSON.parse(npcsContent);
logConditional(`已加载商人数据: ${Object.keys(npcData).length} 个商人`);
// ========== 收集所有标签 ==========
for (let key in npcData) {
let npc = npcData[key];
if (npc.tags && Array.isArray(npc.tags)) {
npc.tags.forEach(tag => allTags.add(tag));
}
}
logConditional(`共收集到 ${allTags.size} 个标签`);
// ========== 解析用户输入 ==========
const foodsInput = (settings.foodsToBuy || "").trim();
if (foodsInput) {
const items = foodsInput.split(/[,\s、]+/).filter(item => item.trim() !== "");
const enabledFoodsList = [];
const enabledTagsList = [];
for (const item of items) {
// 商品组合别名:"狗粮"对应购买所有狗粮商品
if (FOOD_GROUP_ALIASES[item]) {
const groupFoods = getGroupFoods(item);
if (groupFoods.length === 0) {
log.warn(`商品组合 "${item}" 未匹配到任何商品,请检查 npcs.json 数据`);
}
groupFoods.forEach(food => {
userFoodsToBuy.add(food);
enabledFoodsList.push(food);
});
log.info(`已启用商品组合 "${item}":共 ${groupFoods.length} 种商品 (${groupFoods.join(", ")})`);
continue;
}
if (allTags.has(item)) {
// 是标签
userTagsToBuy.add(item);
enabledTagsList.push(item);
} else {
// 视为商品名 (归一化,忽略「」括号差异,并兼容旧商品名)
const food = canonicalFoodName(item);
if (food !== normalizeFoodName(item)) {
log.info(`商品名 "${item}" 已在新版本中更名为 "${food}",已自动兼容`);
}
userFoodsToBuy.add(food);
enabledFoodsList.push(food);
}
}
// 输出用户启用的标签和商品
if (enabledTagsList.length > 0) {
log.info(`用户启用了以下标签: ${enabledTagsList.join(", ")}`);
}
if (enabledFoodsList.length > 0) {
log.info(`用户启用了以下商品: ${enabledFoodsList.join(", ")}`);
}
if (enabledTagsList.length === 0 && enabledFoodsList.length === 0) {
log.warn("用户未启用任何标签或商品");
}
} else {
log.warn("用户未指定要购买的商品或标签");
}
// 解析调试模式指定的NPC和商品
debugNpcFoods = parseDebugNpcFoods();
// 计算所有需要加载图片的商品
requiredFoods = new Set(userFoodsToBuy);
for (let key in npcData) {
let npc = npcData[key];
if (npc.tags && Array.isArray(npc.tags) && npc.tags.some(tag => userTagsToBuy.has(tag))) {
if (npc._1d_foods) npc._1d_foods.forEach(food => requiredFoods.add(food));
if (npc._3d_foods) npc._3d_foods.forEach(food => requiredFoods.add(food));
if (npc._7d_foods) npc._7d_foods.forEach(food => requiredFoods.add(food));
if (npc._thu_foods) npc._thu_foods.forEach(food => requiredFoods.add(food));
if (npc._month_foods) npc._month_foods.forEach(food => requiredFoods.add(food));
}
}
// 调试模式下加载识别图片
if (debugNpcFoods) {
for (const foods of debugNpcFoods.values()) {
if (foods) foods.forEach(food => requiredFoods.add(food));
}
}
logConditional(`需要加载图片的商品总数: ${requiredFoods.size}`);
return true;
} catch (error) {
log.error(`加载外部数据失败: ${error.message}`);
return false;
}
}
// ==================== 辅助函数:获取商人的所有商品 ====================
function getAllNpcFoods(npc) {
const all = [];
if (npc._1d_foods) all.push(...npc._1d_foods);
if (npc._3d_foods) all.push(...npc._3d_foods);
if (npc._7d_foods) all.push(...npc._7d_foods);
if (npc._thu_foods) all.push(...npc._thu_foods);
if (npc._month_foods) all.push(...npc._month_foods);
return all;
}
// ==================== 辅助函数:过滤用户要购买的商品 ====================
function filterUserFoods(foodList) {
if (!foodList || !Array.isArray(foodList)) {
return [];
}
return foodList.filter(food => {
// 检查归一化(含旧名兼容)后的商品名是否在用户要购买的商品集合中
const shouldBuy = userFoodsToBuy.has(canonicalFoodName(food));
if (recordDebug && shouldBuy) {
log.info(`[调试] 用户选择购买: ${food}`);
}
return shouldBuy;
});
}
// ==================== 辅助函数:检查容量上限消息 ====================
async function checkCapacityLimitMessage() {
let captureRegion = null;
let returnValue = false;
try {
await sleep(100);
captureRegion = captureGameRegion();
// 在指定区域进行 OCR 识别
let ocrObject = RecognitionObject.Ocr(1305, 860, 500, 100);
let ocrResult = captureRegion.Find(ocrObject);
if (ocrResult.isExist() && ocrResult.text.includes("当前物品在背包内的容量已达上限")) {
returnValue = true;
}
} catch (e) {
log.warn(`检查容量上限消息时出错: ${e.message}`);
returnValue = false;
} finally {
if (captureRegion) captureRegion.dispose();
}
return returnValue;
}
// ==================== 辅助函数:检查“已售罄”消息 ====================
async function checkSoldOutMessage() {
let captureRegion = null;
let returnValue = false;
try {
await sleep(100);
captureRegion = captureGameRegion();
// 在指定区域进行 OCR 识别(与容量上限提示区域相同,也可根据需要调整)
let ocrObject = RecognitionObject.Ocr(1305, 860, 500, 100);
let ocrResult = captureRegion.Find(ocrObject);
if (ocrResult.isExist() && (ocrResult.text.includes("售罄"))) {
returnValue = true;
}
} catch (e) {
log.warn(`检查已售罄消息时出错: ${e.message}`);
returnValue = false;
} finally {
if (captureRegion) captureRegion.dispose();
}
return returnValue;
}
// ==================== 辅助函数:获取调整后的星期几(1-7,周一为1) ====================
function getAdjustedDayOfWeek() {
const now = new Date();
let dayOfWeek = now.getDay(); // 0-6 (0是周日)
const hours = now.getHours();
// 如果时间在 00:00~04:00 之间,视为前一天
if (hours < 4) {
dayOfWeek = dayOfWeek === 0 ? 6 : dayOfWeek - 1; // 前一天
if (recordDebug) {
log.info(`[调试] 当前时间 ${now.getHours()}:${now.getMinutes()},视为前一天(周 ${dayOfWeek === 0 ? 7 : dayOfWeek})`);
}
} else if (recordDebug) {
log.info(`[调试] 当前时间 ${now.getHours()}:${now.getMinutes()},使用当天(周 ${dayOfWeek === 0 ? 7 : dayOfWeek})`);
}
// 转换为 1-7 格式(7 代表周日)
return dayOfWeek === 0 ? 7 : dayOfWeek;
}
// ==================== 辅助函数:获取给定日期所在的周一日期 ====================
function getMondayOfWeek(date) {
const d = new Date(date);
// 调整到4点刷新
if (d.getHours() < 4) {
d.setDate(d.getDate() - 1);
}
const day = d.getDay();
const diff = day === 0 ? 6 : day - 1;
d.setDate(d.getDate() - diff);
d.setHours(4, 0, 0, 0);
return d;
}
// ==================== 辅助函数:获取给定日期所在的周四日期 ====================
function getThursdayOfWeek(date) {
const d = new Date(date);
// 调整到4点刷新
if (d.getHours() < 4) {
d.setDate(d.getDate() - 1);
}
const day = d.getDay(); // 0=周日, 1=周一, 2=周二, 3=周三, 4=周四, 5=周五, 6=周六
let targetDay = 4;
if (day < targetDay) {
// 本周四
d.setDate(d.getDate() + (targetDay - day));
} else if (day > targetDay) {
// 下周四
d.setDate(d.getDate() + (7 - day + targetDay));
} else {
// 当天是周四,已经过了4点,返回下周四
d.setDate(d.getDate() + 7);
}
d.setHours(4, 0, 0, 0);
return d;
}
// ==================== 辅助函数:获取下个月1号的日期 ====================
function getNextMonthFirstDay(date) {
const d = new Date(date);
d.setDate(1);
d.setMonth(d.getMonth() + 1);
d.setHours(4, 0, 0, 0);
return d;
}
// ==================== 账号管理功能 ====================
let userName;
// 清理账户名,防止路径非法字符
function validateUserName(name) {
if (typeof name !== 'string' || name.trim() === '') return '默认账户';
// 替换 Windows 路径非法字符,并去除首尾空格
return name.trim().replace(/[\\/:*?"<>|]/g, '_');
}
// 使用genshin.uid()获取当前角色UID
async function getUidFromGame() {
try {
// 确保回到主界面
await genshin.returnMainUi();
await sleep(1000);
// 通过OCR识别当前角色UID,识别失败返回0
const uidInt = await genshin.uid();
const uid = uidInt ? String(uidInt) : "";
if (uid.length >= 5) { // UID通常9位,至少5位
log.info(`从游戏获取到UID: ${uid}`);
return uid;
}
log.warn("无法从游戏获取UID");
return null;
} catch (error) {
log.warn(`获取UID失败: ${error.message}`);
return null;
}
}
// 确保设置变量存在(调试模式总开关:关闭时"显示详细日志"与"指定NPC和商品"均不生效)
const debugMode = settings.debugMode || false;
const ignoreRecords = settings.ignoreRecords || false;
// “无视记录强制购买”为一次性勾选:运行开始即写回 false,本次运行结束后自动取消,
if (ignoreRecords) {
settings.ignoreRecords = false;
}
const recordDebug = debugMode && (settings.recordDebug || false);
// 商人名称兼容映射(旧拼写 -> 新规范名)
// 更名后仍能命中旧购买记录与旧禁用标签设置,避免重复购买
const NPC_NAME_ALIASES = { "卯师父": "卯师傅" };
function canonicalNpcName(name) {
return NPC_NAME_ALIASES[name] || name;
}
// 商品名称归一化:去掉「」括号,使用户输入与数据文件/图片文件名能互相匹配
function normalizeFoodName(name) {
return String(name || "").replace(/[「」]/g, "").trim();
}
// 商品名称兼容映射
// 用户若仍在商品栏填写旧名,自动映射到新名,避免找不到图片而报错
const FOOD_NAME_ALIASES = { "鱼肉2": "鱼肉" };
// 商品组合别名:填写组合名一键购买一组商品
// "狗粮" = 所有带"狗粮商人"标签商人的周四刷新商品
const FOOD_GROUP_ALIASES = { "狗粮": { tag: "狗粮商人", types: ["thu"] } };
// 收集商品组合包含的商品名
function getGroupFoods(group) {
const conf = FOOD_GROUP_ALIASES[group];
const foods = new Set();
if (!conf) return [];
for (const key in npcData) {
const npc = npcData[key];
if (npc.tags && Array.isArray(npc.tags) && npc.tags.includes(conf.tag)) {
conf.types.forEach(type => {
const list = npc[`_${type}_foods`];
if (list) list.forEach(food => foods.add(food));
});
}
}
return [...foods];
}
// 按商人名查找 npcData 中的商人
function findNpcByName(name) {
const canonical = canonicalNpcName(normalizeFoodName(name));
for (const [key, npc] of Object.entries(npcData)) {
if (canonicalNpcName(normalizeFoodName(key)) === canonical ||
canonicalNpcName(normalizeFoodName(npc.name || "")) === canonical) {
return npc;
}
}
return null;
}
// ==================== 调试模式:解析指定的NPC和商品 ====================
// 格式如"布兰琪 盐,莎拉 面粉":只运行指定NPC并只购买其指定商品(NPC和商品可多选)
// 只填NPC名不填商品则购买该商人全部商品;遇到另一个商人名即开启新分组(逗号分隔)
function parseDebugNpcFoods() {
const input = (settings.debugNpcFoods || "").trim();
if (!debugMode || !input) return null;
const tokens = input.split(/[,,\s]+/).filter(t => t !== "");
const result = new Map(); // npc.name -> Set(商品名) 或 null(全部商品)
let currentNpc = null;
for (const token of tokens) {
const npc = findNpcByName(token);
if (npc) {
// 遇到商人名:开启/复用该商人的分组
currentNpc = npc.name;
if (!result.has(currentNpc)) result.set(currentNpc, null);
} else if (currentNpc) {
// 商品名:加入当前商人分组(未填商品时先初始化为指定集合)
let foods = result.get(currentNpc);
if (foods === null) {
foods = new Set();
result.set(currentNpc, foods);
}
foods.add(canonicalFoodName(token));
} else if (recordDebug) {
log.warn(`[调试] "${token}" 不是有效商人名,已忽略`);
}
}
if (result.size === 0) return null;
// 输出调试配置,并校验指定商品是否存在于对应商人的商品列表
if (recordDebug) {
log.info(`[调试] 已指定运行商人: ${[...result.keys()].join(", ")}`);
for (const [npcName, foods] of result.entries()) {
if (!foods) {
log.info(`[调试] ${npcName}: 全部商品`);
continue;
}
const npc = findNpcByName(npcName);
const all = npc ? getAllNpcFoods(npc).map(canonicalFoodName) : [];
const unknown = [...foods].filter(f => !all.includes(f));
if (unknown.length > 0) {
log.warn(`[调试] 商人 ${npcName} 不存在指定商品: ${unknown.join(", ")}`);
}
log.info(`[调试] ${npcName}: ${[...foods].join(", ")}`);
}
}
return result;
}
function canonicalFoodName(name) {
const normalized = normalizeFoodName(name);
return FOOD_NAME_ALIASES[normalized] || normalized;
}
// 解析禁用的标签列表(同时归一到新规范名,使旧名禁用设置继续生效;商品名忽略「」括号差异并兼容旧商品名)
const disabledTags = (settings.disabledTags || "").split(/[,\s、]+/).filter(tag => tag.trim() !== "").map(tag => canonicalNpcName(canonicalFoodName(tag)));
if (disabledTags.length > 0) {
log.info(`已禁用标签或商品: ${disabledTags.join(", ")}`);
}
const disabledTagsSet = new Set(disabledTags);
// 修改AKF设置处理
const AKFValue = parseInt(settings.AKF) || 0; // 默认0(跟随系统)
let followSystem = false;
if (AKFValue === 0) {
followSystem = true;
log.info("每周商品购买: 跟随系统判定");
} else {
const dayNames = ["一", "二", "三", "四", "五", "六", "日"];
log.info(`每周商品购买: 每周${dayNames[AKFValue - 1]}购买`);
}
// 获取账号记录路径
function getRecordPath(accountName) {
// 简单处理账户名,如果为空则使用默认账户
if (!accountName || accountName.trim() === "") {
accountName = "默认账户";
}
return `record/${accountName.trim()}/records.json`;
}
// ==================== 新增函数:读取商人记录文件 ====================
async function loadNpcRecords() {
const recordPath = getRecordPath(userName);
try {
const content = await file.readText(recordPath);
if (content.trim()) {
const records = JSON.parse(content);
// 迁移旧商人名称到新规范名,避免更名后记录命中失败导致重复购买
let changed = false;
for (const record of records) {
const newName = canonicalNpcName(record.npcname);
if (newName !== record.npcname) {
record.npcname = newName;
changed = true;
}
}
// 清除记录中已废弃的旧商品名,避免脏数据残留
const removedFoodAliases = [];
for (const record of records) {
for (const type of ["1d", "3d", "7d", "thu", "month"]) {
if (Array.isArray(record[type])) {
const removed = record[type].filter(food => FOOD_NAME_ALIASES[normalizeFoodName(food)]);
if (removed.length > 0) {
record[type] = record[type].filter(food => !FOOD_NAME_ALIASES[normalizeFoodName(food)]);
removedFoodAliases.push(...removed);
changed = true;
}
}
}
}
if (removedFoodAliases.length > 0) {
const uniqueNames = [...new Set(removedFoodAliases.map(food => normalizeFoodName(food)))];
log.info(`已从购买记录中清除 ${removedFoodAliases.length} 条已废弃的旧商品名记录: ${uniqueNames.join(", ")}`);
}
if (changed) {
// 单独捕获落盘失败:写失败不应让本轮记录被当作空,否则会触发重复购买
try {
await file.writeText(recordPath, JSON.stringify(records, null, 2));
} catch (e) {
log.warn(`迁移记录落盘失败(内存记录仍可用): ${e.message}`);
}
}
return records;
}
} catch (error) {
// 文件不存在或格式错误,返回空数组
}
return [];
}
// ==================== 辅助函数:从路径中提取显示名称 ====================
function getDisplayNameFromPath(path) {
try {
// 从路径中提取文件名(不带.json扩展名)
// 例如:assets/path/璃月-璃月港-阿桂.json → 璃月-璃月港-阿桂
const fileName = path.split('/').pop(); // 获取最后一部分
return fileName.replace('.json', ''); // 移除.json扩展名
} catch (error) {
// 如果解析失败,返回原始路径或默认值
return path || "未知位置";
}
}
// ==================== 保存商人记录 ====================
async function saveNpcRecords(records) {
const recordPath = getRecordPath(userName);
try {
await file.writeText(recordPath, JSON.stringify(records, null, 2));
return true;
} catch (error) {
log.error(`保存记录文件失败: ${error.message}`);
return false;
}
}
// ==================== 获取商人记录 ====================
function getNpcRecord(records, npcName) {
// 兼容迁移前的旧名记录:将记录名归一到新规范名后再比较
return records.find(record => canonicalNpcName(record.npcname) === npcName);
}
// ==================== 更新商人记录 ====================
function updateNpcRecord(records, npcName, refreshType, purchasedItems) {
// 如果没有购买任何商品,不更新记录
if (!purchasedItems || purchasedItems.length === 0) {
return records;
}
let record = getNpcRecord(records, npcName);
if (!record) {
record = { npcname: npcName };
records.push(record);
}
// 合并已购商品(去重),而非覆盖
const existing = record[refreshType] || [];
const merged = [...new Set([...existing, ...purchasedItems])];
record[refreshType] = merged;
const now = new Date();
let refreshTime;
if (refreshType === "1d") {
// 1天商品:下次刷新是购买日+1天
refreshTime = new Date(now);
refreshTime.setHours(4, 0, 0, 0);
// 如果当前时间在4点前,刷新时间从昨天开始算
if (now.getHours() < 4) {
refreshTime.setDate(refreshTime.getDate() - 1);
}
refreshTime.setDate(refreshTime.getDate() + 1);
} else if (refreshType === "3d") {
// 3天商品:基于基准日的3天周期计算
// 基准时间:2025-08-09 04:00 GMT+8 (转换为本地时间)
const baseTime = new Date(2025, 7, 9, 4, 0, 0); // 2025-08-09 04:00
// 调整当前时间到4点基准
const adjustedNow = new Date(now);
if (adjustedNow.getHours() < 4) {
adjustedNow.setDate(adjustedNow.getDate() - 1);
}
adjustedNow.setHours(4, 0, 0, 0);
// 计算距离基准日的天数
const timeDiff = adjustedNow.getTime() - baseTime.getTime();
const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
// 计算当前3天周期
const currentPeriod = Math.floor(daysDiff / 3);
// 下一个3天周期的开始时间
const nextPeriod = currentPeriod + 1;
refreshTime = new Date(baseTime);
refreshTime.setDate(baseTime.getDate() + (nextPeriod * 3));
// 确保刷新时间是04:00
refreshTime.setHours(4, 0, 0, 0);
} else if (refreshType === "7d") {
// 7天商品(周一刷新):下次刷新是下周一
refreshTime = getMondayOfWeek(now);
refreshTime.setDate(refreshTime.getDate() + 7);
} else if (refreshType === "thu") {
// 周四刷新商品:下次刷新是下周四
refreshTime = getThursdayOfWeek(now);
} else if (refreshType === "month") {
// 每月1号刷新商品:下次刷新是下个月1号
refreshTime = getNextMonthFirstDay(now);
}
record[`${refreshType}_time`] = formatDateToLocalISO(refreshTime);
// 计算下次刷新日期
if (recordDebug) {
const nextRefresh = new Date(refreshTime);
log.info(`${npcName} 下次${refreshType}刷新时间: ${formatDateToLocalISO(nextRefresh)}`);
}
return records;
}
// ==================== 计算3天刷新商品基准日周期 ====================
function getBasePeriod(currentDate) {
// 基准时间:2025-08-08 20:00 UTC (对应2025-08-09 04:00 GMT+8)
const baseTime = Date.UTC(2025, 7, 8, 20, 0, 0);
// 转换当前时间到UTC+8
const utcNowMs = currentDate.getTime() + currentDate.getTimezoneOffset() * 60 * 1000;
const gmt8Ms = utcNowMs + 8 * 60 * 60 * 1000;
const gmt8Date = new Date(gmt8Ms);
// 如果还没到凌晨4点,算作前一天
if (gmt8Date.getHours() < 4) {
gmt8Date.setDate(gmt8Date.getDate() - 1);
}
// 计算距离基准日的天数
const daysDiff = Math.floor((gmt8Date.getTime() - baseTime) / (24 * 60 * 60 * 1000));
return {
day: gmt8Date,
daysDiff: daysDiff,
threeDayPeriod: Math.floor(daysDiff / 3),
sevenDayPeriod: Math.floor(daysDiff / 7)
};
}
// ==================== 判断是否需要购买 ====================
function shouldBuyFoods(npc, npcRecord, currentPeriod, forceRefresh = false) {
const now = new Date();
const foodsToBuy = {
"1d": [],
"3d": [],
"7d": [],
"thu": [],
"month": []
};
// 获取当前星期几(1=周一,7=周日),已考虑4点刷新
const currentDay = getAdjustedDayOfWeek();
// 辅助函数:根据用户设置获取候选商品列表(过滤禁用和容量上限)
function getCandidates(fullList) {
if (!fullList || fullList.length === 0) return [];
// 判断是否匹配标签
let useAll = false;
if (npc.tags && Array.isArray(npc.tags)) {
useAll = npc.tags.some(tag => userTagsToBuy.has(tag));
}
let candidateList = useAll ? fullList : filterUserFoods(fullList);
// 调试模式指定NPC和商品:直接按指定商品购买(未填商品则购买该商人全部商品)
if (debugNpcFoods) {
const specified = debugNpcFoods.get(npc.name);
if (specified !== undefined) {
candidateList = specified === null
? [...fullList]
: fullList.filter(food => specified.has(canonicalFoodName(food)));
}
}
// 过滤容量上限和禁用商品(禁用匹配忽略「」括号差异,并兼容旧商品名)
candidateList = candidateList.filter(food =>
!capacityLimitedFoods.has(food) && !disabledTagsSet.has(canonicalFoodName(food))
);
return candidateList;
}
// 处理每种刷新类型
const types = ["1d", "3d", "7d", "thu", "month"];
for (const type of types) {
const fullList = npc[`_${type}_foods`];
if (!fullList) continue;
// ===== 新增:对 7d 和 thu 类型进行日期过滤 =====
if ((type === "7d" || type === "thu") && AKFValue !== 0) {
if (currentDay !== AKFValue) {
continue; // 今天不是用户指定的购买日,跳过该类型
}
}
let candidates = getCandidates(fullList);
if (candidates.length === 0) continue;
if (forceRefresh) {
// 强制刷新:忽略记录,全部尝试购买(但仍受用户过滤约束)
foodsToBuy[type] = candidates;
} else {
// 正常模式:检查购买记录和刷新时间
const purchasedList = npcRecord && npcRecord[type] ? npcRecord[type] : [];
const notPurchased = candidates.filter(food => !purchasedList.includes(food));
if (!npcRecord || !npcRecord[`${type}_time`]) {
foodsToBuy[type] = candidates;
} else {
const nextRefreshTime = new Date(npcRecord[`${type}_time`]);
if (now >= nextRefreshTime) {
foodsToBuy[type] = candidates;
} else {
foodsToBuy[type] = notPurchased;
}
}
}
}
return foodsToBuy;
}
const othrtRo = {
"buy": {
"name": "购买按钮",
"file": "assets/images/buyBtn.png"
}
}
const store_Page_Tags_Ro = RecognitionObject.TemplateMatch(file.ReadImageMatSync("assets/images/store_Page_Tags.png"), 50, 30, 60, 55)
// 获取游戏内时间(考虑4点刷新)
function getGameTime() {
const now = new Date();
const utcNowMs = now.getTime() + now.getTimezoneOffset() * 60 * 1000;
const gmt8Ms = utcNowMs + 8 * 60 * 60 * 1000;
const gmt8Date = new Date(gmt8Ms);
// 如果还没到凌晨4点,算作前一天
if (gmt8Date.getHours() < 4) {
gmt8Date.setDate(gmt8Date.getDate() - 1);
}
return gmt8Date;
}
// ==================== 新增函数:格式化为本地ISO时间 ====================
function formatDateToLocalISO(date) {
// 将日期格式化为 "YYYY-MM-DDTHH:mm:ss+08:00" 格式
const pad = (n) => n.toString().padStart(2, '0');
const year = date.getFullYear();
const month = pad(date.getMonth() + 1);
const day = pad(date.getDate());
const hours = pad(date.getHours());
const minutes = pad(date.getMinutes());
const seconds = pad(date.getSeconds());
return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}+08:00`;
}
// 地图追踪
async function autoPath(locationPath) {
try {
let filePath = locationPath;
await pathingScript.runFile(filePath);
await sleep(200);
return true;
} catch (error) {
log.error(`执行路径时发生错误: ${error.message}`);
return false;
}
}
// 平滑过渡函数(缓动效果)
function smoothStep(t) {
return t * t * (3 - 2 * t);
}
// 模拟鼠标移动到指定位置(带曲线路径)
async function naturalMove(initX, initY, targetX, targetY, duration, wiggle = 30) {
// 生成控制点(使路径形成曲线)
const controlX = (initX + targetX) / 2 + (Math.random() * wiggle * 2 - wiggle);
const controlY = (initY + targetY) / 2 + (Math.random() * wiggle * 2 - wiggle);
const steps = Math.max(duration / 20, 10); // 计算步数
for (let i = 0; i <= steps; i++) {
const progress = i / steps;
const t = smoothStep(progress); // 使用平滑过渡
// 二次贝塞尔曲线计算
const x = (1 - t) * (1 - t) * initX + 2 * (1 - t) * t * controlX + t * t * targetX;
const y = (1 - t) * (1 - t) * initY + 2 * (1 - t) * t * controlY + t * t * targetY;
moveMouseTo(Math.trunc(x), Math.trunc(y));
// 随机延迟使移动更自然
await sleep(Math.trunc(duration / steps * (0.8 + Math.random() * 0.4)));
}
await sleep(200);
// 确保最终位置准确
moveMouseTo(targetX, targetY);
}
// 切换下一页商品
async function nextFoodsPage() {
//设置脚本环境的游戏分辨率和DPI缩放
setGameMetrics(3840, 2160, 1.5);
let [initX, initY] = [1500, 1850];
let [targetX, targetY] = [1800, 260];
moveMouseTo(initX, initY);
leftButtonDown();
await naturalMove(initX, initY, targetX, targetY, 300);
// 按住了, 防止弹太远
await sleep(520);
leftButtonUp();
}
// 快速购买
async function quickBuy(itemName) {
//设置脚本环境的游戏分辨率和DPI缩放
setGameMetrics(3840, 2160, 1.5);
let [buyBtnX, buyBtnY] = [3200, 2045];
let [confirmBtnX, confirmBtnY] = [2025, 1570];
let [addNumX, addNumY] = [2060, 1208];
// 等待界面切换
await sleep(200);
try {
// 查找购买按钮
let captureRegion = captureGameRegion();
let buyBtn = captureRegion.Find(othrtRo.buy.ro);
captureRegion.dispose();
if (buyBtn.isEmpty()) {
// 未找到购买按钮 -> 可能容量已满或售罄
let isCapacityFull = await checkCapacityLimitMessage();
if (isCapacityFull) {
capacityLimitedFoods.add(itemName);
log.info(`[容量上限] 商品 "${itemName}" 触发背包容量已达上限,后续将不再购买。`);
// 交互或拾取:"XXXX"
await fakeLog(`${itemName} 已达上限`, false, false, 23333);
return 'capacity';
}
// 非容量问题,可能售罄导致按钮消失?仍尝试检测售罄消息
let isSoldOut = await checkSoldOutMessage();
if (isSoldOut) {
log.info(`[已售罄] 商品 "${itemName}" 已售罄`);
return 'sold_out';
}
return 'error';
}
// 点击购买按钮
click(buyBtn.x * 2 + buyBtn.width, buyBtn.y * 2 + buyBtn.height);
// 等待购买窗口弹出
await sleep(300);
// 增加数量至最大
leftButtonDown();
await naturalMove(addNumX, addNumY, addNumX + 666, addNumY - 233, 100);
leftButtonUp();
// 确保最终数量至最大
await sleep(200);
click(2370, 1208);
await sleep(200);
// 再點擊+號避免只買99
click(2584, 1204);
await sleep(200);
// 点击确认按钮
click(confirmBtnX, confirmBtnY);
// 等待购买完成
await sleep(1200);
// 点击空白关闭
click(buyBtnX, buyBtnY);
await sleep(200);
return 'success';
} catch (error) {
log.error(`快速购买失败: ${error.message}`);
return 'error';
}
}
// ==================== 检测交互选项并选择包含NPC名字的选项 ====================
// 到达追踪点位后,OCR查找包含NPC名字的交互选项,
// 按住Alt键呼出鼠标指针后点击该选项;
// 未找到时重新执行路径并重试,连续失败则中止该商人的交互
async function selectNpcDialogOption(npcName, npcPath) {
// 设置脚本环境的游戏分辨率和DPI缩放,与OCR坐标一致
setGameMetrics(1920, 1080, 1);
let selected = false;
let retryCount = 0;
const maxRetries = 2; // 最大重试次数
// OCR区域限制在交互选项列表所在区域,防止点击NPC头顶名字
const rightHalfOcr = RecognitionObject.Ocr(1150, 430, 250, 210);
await sleep(1000);
while (!selected && retryCount <= maxRetries) {
// 对交互选项区域进行 OCR
let captureRegion = captureGameRegion();
let resList = captureRegion.findMulti(rightHalfOcr);
captureRegion.dispose();
for (let i = 0; i < resList.count; i++) {
if (resList[i].text.includes(npcName)) {
// 找到包含NPC名字的交互选项
log.info(`找到交互选项: ${resList[i].text.trim()}, 开始交互`);
keyDown("VK_MENU"); // Alt
await sleep(1000);
click(resList[i].x + 30, resList[i].y + 30); // 点击NPC选项
await sleep(1000);
keyUp("VK_MENU"); // Alt
await sleep(1000);
selected = true;
break; // 找到后跳出循环
}
}
if (!selected) {
retryCount++;
if (retryCount <= maxRetries) {
log.warn(`未找到包含 "${npcName}" 的交互选项,进行第 (${retryCount}/${maxRetries}) 次重试`);
await sleep(1500);
if (npcPath) {
// 重新执行路径
await autoPath(npcPath);
}
await sleep(1000);
}
}
}
if (!selected) {
log.error(`连续${maxRetries}次未能找到包含 "${npcName}" 的交互选项`);
}
return selected;
}
// ==================== NPC特殊对话选项 ====================
// 循环OCR检测对话:找到特殊选项立即鼠标点击;选项未出现时按F推进下一句。
async function clickShopDialogOption(maxAttempts = 6) {
// 设置脚本环境的游戏分辨率和DPI缩放
setGameMetrics(1920, 1080, 1);
const keywords = ["有什么卖的", "可以卖一些", "有什么喝的", "我想买些古董"];
for (let attempt = 0; attempt < maxAttempts; attempt++) {
let captureRegion = captureGameRegion();
let target = null;
try {
let resList = captureRegion.findMulti(RecognitionObject.ocrThis);
for (let i = 0; i < resList.count; i++) {
const text = resList[i].text || "";
if (keywords.some(k => text.includes(k))) {
target = resList[i];
break;
}
}
} finally {
captureRegion.dispose();
}
if (target) {
// 商店选项已出现:直接点击
await sleep(300);
click(target.x + 30, target.y + 30);
logConditional(`已点击商店对话选项: ${target.text.trim()}`);
await sleep(800);
return true;
}
// 商店选项尚未出现:按F推进下一句对话
keyPress("VK_F");
await sleep(1250);
}
log.warn("多次尝试后仍未找到商店对话选项");
return false;
}
// 跳过对话
async function spikChat(npcName, npcPath) {
let count = 6; // 添加let声明
if (npcName == "齐良诺夫") {
// 目前仅"齐良诺夫"点位启用新逻辑
const selected = await selectNpcDialogOption(npcName, npcPath);
if (!selected) {
log.error(`未能与 ${npcName} 进入对话,跳过该商人`);
return false;
}
} else {
// 其余点位依旧按F对话
await sleep(1000);
keyPress("VK_F");
await sleep(1000);
if (npcName == "布纳马" || npcName == "杜拉夫") {
// 首次按F已在上方完成,这里推进剩余对话
const loop_count = (npcName == "布纳马") ? 2 : 1;
for (let i = 0; i < loop_count; i++) {
keyPress("VK_F");
await sleep(1500);
}
}
}
if (npcName == "琳琅" || npcName == "布纳马" || npcName == "杜拉夫" || npcName == "齐良诺夫") {
// 设置脚本环境的游戏分辨率和DPI缩放
setGameMetrics(1920, 1080, 1);
// 循环检测并点击"有什么卖的/有什么喝的"商店选项:
// 选项已出现时直接鼠标点击;只有仍是问候语(选项未出现)时才按F推进
await clickShopDialogOption(6);
// 等待购买页面出现
if (await waitForPurchasePage(6)) {
logConditional(`已进入 ${npcName} 的购买页面`);
} else {
log.warn(`未能进入 ${npcName} 的购买页面,尝试继续...`);
}
return true;
} else {
// 通用NPC:已按F进入对话,这里循环检测购买页面
if (await waitForPurchasePage(8)) {
logConditional(`已进入 ${npcName} 的购买页面`);
} else {
log.warn(`未能进入 ${npcName} 的购买页面,脚本可能无法正常购买`);
}
return true;
}
}
// ==================== 辅助函数:等待进入购买页面 ====================
async function waitForPurchasePage(maxAttempts = 8) {
// 强制使用 1080P 坐标系(与模板截图一致)
setGameMetrics(1920, 1080, 1);
for (let attempt = 0; attempt < maxAttempts; attempt++) {
// 检测是否已在购买页面
let capture = captureGameRegion();
try {
let result = capture.Find(store_Page_Tags_Ro);
if (result.isExist()) {
return true;//已進入
}
} finally {
capture.dispose();
}
// 未进入,按 F 推进对话
keyPress("VK_F");
await sleep(1250); // 等待界面响应
}
return false;
}
// ==================== 商品识别对象映射表 ====================
let foodROMap = {}; // 键为商品名(中文),值为 RecognitionObject
// 加载识别对象(只加载用户选择的商品)
async function initRo() {
try {
for (let foodName of requiredFoods) {
// 统一用归一化(含旧名兼容)名称作键,保证与购买时的查找键一致
const roKey = canonicalFoodName(foodName);
if (foodROMap[roKey]) {
continue; // 同一商品的另一种写法(带/不带「」)已加载过
}
// 依次尝试原始文件名与带「」括号的文件名(如「四方八方之网」.png)
const plainPath = `assets/images/${foodName}.png`;
const bracketedPath = `assets/images/「${normalizeFoodName(foodName)}」.png`;
let candidatePaths = plainPath === bracketedPath ? [plainPath] : [plainPath, bracketedPath];
if (typeof file.isExists === "function") {
// 预检文件是否存在,避免 ReadImageMatSync 读不到文件时框架打印错误日志
candidatePaths = candidatePaths.filter(p => file.isExists(p));
}
let loaded = false;
for (const imagePath of candidatePaths) {
try {
const ro = RecognitionObject.TemplateMatch(file.ReadImageMatSync(imagePath));
// 特定商品自定义阈值:默认0.84
const customThresholds = { "小麦": 0.75, "土豆": 0.9, "牛奶": 0.85 };
ro.Threshold = customThresholds[foodName] || 0.84;
ro.Use3Channels = true;
foodROMap[roKey] = ro;
loaded = true;
logConditional(`已启用商品: ${foodName} (${imagePath}, 阈值:${ro.Threshold})`);
break;
} catch (e) {
// 读取或创建识别对象失败,尝试下一个候选路径
}
}
if (!loaded) {
log.error(`加载商品图片失败: ${plainPath},请确保图片存在`);
}
}
for (let [key, item] of Object.entries(othrtRo)) {
item.ro = RecognitionObject.TemplateMatch(file.ReadImageMatSync(item.file));
item.ro.Threshold = 0.85;
}
logConditional(`总共启用了 ${requiredFoods.size} 种商品`);
return true;
}
catch (error) {
log.error("加载识别对象时发生错误: {error}", error.message);
throw error;
}
}
// 主要购买逻辑
async function buyFoods(npcName, npcRecords, currentPeriod) {
// 设置脚本环境的游戏分辨率和DPI缩放
setGameMetrics(3840, 2160, 1.5);
// 获取商人数据
const npc = npcData[npcName];
const npcRecord = getNpcRecord(npcRecords, npc.name);
// 获取显示名称
const displayName = getDisplayNameFromPath(npc.path);
if (recordDebug) {
log.info(`[调试] 开始处理: ${displayName}`);
if (npcRecord) {
log.info(`[调试] 当前记录: 1d=${npcRecord["1d_time"] || "无"}, 3d=${npcRecord["3d_time"] || "无"}, 7d=${npcRecord["7d_time"] || "无"}, thu=${npcRecord["thu_time"] || "无"}, month=${npcRecord["month_time"] || "无"}`);
}
}
// 判断需要购买的商品
const foodsToBuy = shouldBuyFoods(npc, npcRecord, currentPeriod, ignoreRecords);
if (recordDebug) {
log.info(`[调试] ${displayName} 购买判断结果:`);
log.info(`[调试] 1天商品: ${foodsToBuy["1d"].join(", ")}`);
log.info(`[调试] 3天商品: ${foodsToBuy["3d"].join(", ")}`);
log.info(`[调试] 7天商品: ${foodsToBuy["7d"].join(", ")}`);
log.info(`[调试] 周四商品: ${foodsToBuy["thu"].join(", ")}`);
log.info(`[调试] 每月商品: ${foodsToBuy["month"].join(", ")}`);
}
// 合并所有要购买的食物
const allFoodsToBuy = [];
if (foodsToBuy["1d"]) allFoodsToBuy.push(...foodsToBuy["1d"]);
if (foodsToBuy["3d"]) allFoodsToBuy.push(...foodsToBuy["3d"]);
if (foodsToBuy["7d"]) allFoodsToBuy.push(...foodsToBuy["7d"]);
if (foodsToBuy["thu"]) allFoodsToBuy.push(...foodsToBuy["thu"]);
if (foodsToBuy["month"]) allFoodsToBuy.push(...foodsToBuy["month"]);
if (allFoodsToBuy.length === 0) {
logConditional(`${displayName} 没有需要购买的商品`);
return {
purchased: [],
"1d": [],
"3d": [],
"7d": [],
"thu": [],
"month": []
};
}
logConditional(`${displayName} 购买列表: ${allFoodsToBuy.join(", ")}`);
let tempFoods = [...allFoodsToBuy];
const purchasedFoods = [];
const purchasedByType = {
"1d": [],
"3d": [],
"7d": [],
"thu": [],
"month": []
};
// 构建商品到刷新类型的映射
const foodToRefreshType = {};
for (const type of ["1d", "3d", "7d", "thu", "month"]) {
if (foodsToBuy[type]) {
for (const food of foodsToBuy[type]) {
foodToRefreshType[food] = type;
}
}
}
// 多页购买
for (let i = 0; i < npc.page; i++) {
await sleep(520);
// 获取一张截图
let captureRegion = captureGameRegion();
// 记录已经购买的物品
let boughtFoods = new Set([]);
// 匹配商品
for (let item of tempFoods) {
if (capacityLimitedFoods.has(item)) {
if (recordDebug) log.info(`[调试] 跳过已容量上限的商品: ${item}`);
continue;
}
if (recordDebug) {
log.info(`[调试] 尝试购买: ${item}`);
}
// 查找识别对象(键为归一化名称,兼容带/不带「」及旧商品名)
const ro = foodROMap[canonicalFoodName(item)];
if (!ro) {
log.warn(`商品 "${item}" 未启用或没有识别对象,跳过`);
continue;
}
let resList = captureRegion.FindMulti(ro);
// 截图漏检,等待后重新截图再查找,最多尝试 3 次
for (let findAttempt = 1; findAttempt < 3 && resList.count === 0; findAttempt++) {
if (recordDebug) log.info(`[调试] 本次截图未找到 "${item}",等待后重新截图查找(第 ${findAttempt} 次)`);
await sleep(1000);
captureRegion.dispose();
captureRegion = captureGameRegion();
resList = captureRegion.FindMulti(ro);
}
for (let res of resList) {
if (recordDebug) {
log.info(`[调试] 找到物品: ${item} 位置(${res.x},${res.y},${res.width},${res.height})`);
}
// 移除已购买的物品
boughtFoods.add(item);
// 点击商品
click(res.x * 2 + res.width, res.y * 2 + res.height);
let buyResult = await quickBuy(item);
if (buyResult === 'success' || buyResult === 'sold_out') {
if (buyResult === 'success') {
log.info(`购买成功: ${item}`);
} else {
log.info(`商品已售罄,已记录CD: ${item}`);
}
// 交互或拾取提示(售罄时已在 quickBuy 中调用 fakeLog,此处避免重复)
if (buyResult === 'success') {
// 交互或拾取:"XXXX"
await fakeLog(item, false, false, 23333);
} else if (buyResult === 'sold_out') {
// 交互或拾取:"XXXX 已销售"
await fakeLog(`${item} 已销售`, false, false, 23333);
}
// 记录购买的商品
purchasedFoods.push(item);
const refreshType = foodToRefreshType[item];
if (refreshType) {
purchasedByType[refreshType].push(item);
// 立即更新记录
npcRecords = updateNpcRecord(npcRecords, npc.name, refreshType, purchasedByType[refreshType]);
await saveNpcRecords(npcRecords);
}
await sleep(1500);
// 重新截图
captureRegion.dispose(); // 释放旧截图
captureRegion = captureGameRegion(); // 重新截图
}
else if (buyResult === 'capacity') {
log.info(`购买失败: ${item}, 背包已经满或商品已售罄`);
// 如果失败是因为容量上限(quickBuy 内部已加入黑名单),立即从临时列表中移除
if (capacityLimitedFoods.has(item)) {
tempFoods = tempFoods.filter(f => f !== item);
// 因为数组改变了,需要重新截图并跳出本次循环重新开始
captureRegion.dispose(); // 释放旧截图
captureRegion = captureGameRegion(); // 重新截图
break;
}
}
}
}
captureRegion.dispose();
// 从已购买物品中移除
tempFoods = tempFoods.filter(item => !boughtFoods.has(item));
// 若不是最后一页且还有未购买的物品
if (tempFoods.length > 0 && i !== npc.page - 1) {
logConditional("切换到下一页商品");
await nextFoodsPage();
// 最后一次切换界面, 等待UI回弹
if (i === npc.page - 2) {
logConditional("等待界面回弹");
await sleep(520);
}
}
}
// 提示本次未能购买的商品
if (tempFoods.length > 0) {
log.warn(`${displayName} 以下商品本次未能购买,下次运行将自动重试: ${tempFoods.join(", ")}`);
}
if (purchasedFoods.length > 0) {
log.info(`${displayName} 购买完成,已购买: ${purchasedFoods.join(", ")}`);
} else {
logConditional(`${displayName} 没有购买任何商品`);
}
// 返回购买结果
return {
purchased: purchasedFoods,
"1d": purchasedByType["1d"],
"3d": purchasedByType["3d"],
"7d": purchasedByType["7d"],
"thu": purchasedByType["thu"],
"month": purchasedByType["month"]
};
}
// 初始化商人商品
async function initNpcData(records) {
for (let [key, npc] of Object.entries(npcData)) {
// 调试模式:只运行指定的NPC(优先于商人开关与标签禁用)
if (debugNpcFoods) {
if (!debugNpcFoods.has(npc.name)) {
npc.enable = false;
if (recordDebug) log.info(`[调试] 跳过未指定的商人: ${npc.name}`);
continue;
}
npc.enable = true;
}
// 检查是否通过标签禁用(调试指定的商人不受标签禁用影响)
if (npc.tags && Array.isArray(npc.tags) && !(debugNpcFoods && debugNpcFoods.has(npc.name))) {
const hasDisabledTag = npc.tags.some(tag => disabledTags.includes(tag));
if (hasDisabledTag) {
npc.enable = false;
logConditional(`按标签禁用商人: ${npc.name} (标签: ${npc.tags.join(", ")})`);
continue;
}
}
const npcRecord = getNpcRecord(records, npc.name);
// 判断是否需要强制刷新
const forceRefresh = ignoreRecords;
// 判断需要购买的商品(这里只是检查是否有商品需要购买)
const gameTime = getGameTime();
const currentPeriod = getBasePeriod(gameTime);
const foodsToBuy = shouldBuyFoods(npc, npcRecord, currentPeriod, forceRefresh);
// 检查是否有需要购买的商品
const hasFoodsToBuy = foodsToBuy["1d"].length > 0 ||
foodsToBuy["3d"].length > 0 ||
foodsToBuy["7d"].length > 0 ||
foodsToBuy["thu"].length > 0 ||
foodsToBuy["month"].length > 0;
npc.enable = npc.enable && hasFoodsToBuy;
if (recordDebug && !npc.enable && hasFoodsToBuy) {
const displayName = getDisplayNameFromPath(npc.path);
log.info(`${displayName} 有商品需要购买但商人被禁用`);
}
}
}
// ==================== 商品预设 ====================
// 预设由脚本目录下的“预设工具.html”维护,全局共享(与具体账户无关);
// 预设记录文件存放在 record/ 下
const PRESET_FILE = "record/presets.json";
async function loadPresets() {
try {
const content = await file.readText(PRESET_FILE);
const data = JSON.parse(content);
return (data && typeof data === "object" && !Array.isArray(data)) ? data : {};
} catch (e) {
// 文件不存在或内容损坏时,按"无预设"处理
return {};
}
}
function logPresetList(presets) {
const names = Object.keys(presets);
if (names.length === 0) {
log.warn("当前没有已保存的商品预设");
return;
}
log.warn(`可用的商品预设(共 ${names.length} 个): ${names.join(", ")}`);
}
// settings.preset 选中预设时,读取该预设的商品组合覆盖商品栏;预设失效时回退为按商品栏购买
async function applyPreset() {
const presetName = (settings.preset || "").trim();
if (!presetName || presetName === "不使用预设") return true;
const presets = await loadPresets();
const preset = presets[presetName];
if (!preset || !preset.foods) {
// 下拉栏残留的失效值(如预设已在工具中删除、清空 presets.json 后旧选择未复位):
// 不终止运行,警告后回退为按商品栏购买,并复位下拉栏避免一直显示为空
log.warn(`商品预设 "${presetName}" 不存在(可能已在预设工具中删除),本次将按商品栏购买`);
logPresetList(presets);
settings.preset = "不使用预设";
return true;
}
settings.foodsToBuy = preset.foods;
log.info(`使用商品预设 "${presetName}": ${preset.foods}`);
return true;
}
(async function () {
// 重置容量限制集合
capacityLimitedFoods.clear();
try {
let scriptVersion = "版本号";
try {
const manifest = JSON.parse(await file.readText("manifest.json"));
if (manifest.version) scriptVersion = manifest.version;
} catch (e) {
log.warn(`读取 manifest.json 版本号失败: ${e.message}`);
}
await fakeLog(`当前版本 ${scriptVersion}`, false, false, 23333);
// ==================== 确定账号名 ====================
let rawUserName = settings.userName ? settings.userName.trim() : "";
if (!rawUserName) {
log.info("settings.userName 为空,尝试从游戏获取UID作为账户名...");
const uid = await getUidFromGame();
if (uid) {
userName = uid;
log.info(`使用UID作为账户名: ${userName}`);
} else {
userName = "默认账户";
log.warn("无法获取UID,使用默认账户");
}
} else {
userName = validateUserName(rawUserName);
if (userName !== rawUserName) {
log.info(`账户名已清理: ${userName}`);
settings.userName = userName;
}
}
log.info(`当前账户: ${userName}`);
// ==================== 商品预设:选中预设时用其商品组合覆盖商品栏(失效则回退商品栏) ====================
await applyPreset();
// ==================== 加载外部数据 ====================
if (!await loadExternalData()) {
log.error("商人数据加载失败,脚本终止");
return;
}
const skip = settings.skip || false;
// ==================== 初始化识别对象 ====================
await initRo();
logConditional("识别对象初始化完成");
// ==================== 加载商人购买记录 ====================
let npcRecords = await loadNpcRecords();
logConditional(`已加载 ${npcRecords.length} 个商人的购买记录`);
if (recordDebug && npcRecords.length > 0) {
log.info("[调试] 当前商人记录:");
npcRecords.forEach(record => {
log.info(`[调试] ${record.npcname}:`);
if (record["1d_time"]) log.info(`[调试] 1天刷新: ${record["1d_time"]}`);
if (record["3d_time"]) log.info(`[调试] 3天刷新: ${record["3d_time"]}`);
if (record["7d_time"]) log.info(`[调试] 7天刷新: ${record["7d_time"]}`);
if (record["thu_time"]) log.info(`[调试] 周四刷新: ${record["thu_time"]}`);
if (record["month_time"]) log.info(`[调试] 每月刷新: ${record["month_time"]}`);
});
}
// ==================== 初始化商人数据 ====================
await initNpcData(npcRecords);
logConditional("商人数据初始化完成");
// 统计启用的商人数量
const enabledNpcs = Object.values(npcData).filter(npc => npc.enable);
log.info(`本次执行将处理 ${enabledNpcs.length} 个商人`);
// ==================== 自动购买 ====================
// 获取当前时间和周期
const gameTime = getGameTime();
const currentPeriod = getBasePeriod(gameTime);
if (recordDebug) {
log.info(`[调试] 当前游戏时间: ${formatDateToLocalISO(gameTime)}`);
log.info(`[调试] 当前周期信息: 3天周期=${currentPeriod.threeDayPeriod}, 7天周期=${currentPeriod.sevenDayPeriod}`);
}
let npcIndex = 0;
for (let [key, npc] of Object.entries(npcData)) {
if (npc.enable) {
// 动态检查:考虑当前黑名单后,是否还有商品需要购买
const npcRecord = getNpcRecord(npcRecords, npc.name);
const foodsToBuyNow = shouldBuyFoods(npc, npcRecord, currentPeriod, ignoreRecords);
const hasAnyToBuy = foodsToBuyNow["1d"].length > 0 ||
foodsToBuyNow["3d"].length > 0 ||
foodsToBuyNow["7d"].length > 0 ||
foodsToBuyNow["thu"].length > 0 ||
foodsToBuyNow["month"].length > 0;
if (!hasAnyToBuy) {
logConditional(`跳过商人 ${getDisplayNameFromPath(npc.path)}:所有需要购买的商品均已被容量上限限制`);
continue;
}
npcIndex++;
// 获取显示名称(从路径中提取)
const displayName = getDisplayNameFromPath(npc.path);
// For ABGI only
log.debug(`当前进度:${displayName}(进度: ${npcIndex}/${enabledNpcs.length})`);
log.info(`当前进度:${npcIndex}/${enabledNpcs.length}`);
log.info(`开始前往: ${displayName}`);
await genshin.returnMainUi();
// 地图追踪开始
await fakeLog(displayName, false, true, 0);
// 设置游戏时间
if (npc.time === "night") {
// 设置为晚上8点
await genshin.setTime(20, 0, skip);
}
else if (npc.time === "day") {
// 设置为早上8点
await genshin.setTime(8, 0, skip);
}
await autoPath(npc.path);
const chatOk = await spikChat(npc.name, npc.path);
if (!chatOk) {
// 未能进入对话,跳过该商人
log.error(`已跳过: ${displayName}`);
await genshin.returnMainUi();
// 伪造日志任务结束
await fakeLog(displayName, false, false, 0);
continue;
}
// 购买商品,传入当前记录和周期
const purchaseResult = await buyFoods(key, npcRecords, currentPeriod);
// 返回主界面
await genshin.returnMainUi();
log.info(`完成: ${displayName}`);
// 伪造日志任务结束
await fakeLog(displayName, false, false, 0);
// 商人之间等待
if (npcIndex < enabledNpcs.length) {
logConditional("等待1.5秒后处理下一个商人");
await sleep(1500);
}
}
else {
if (recordDebug) {
log.info(`[调试] 跳过未启用的商人: ${npc.name}`);
}
}
}
log.info("=== 商品购买脚本执行完成 ===");
} catch (error) {
log.error(`执行时发生错误: ${error.message}`);
}
})();