MWIAlchemyCalc

显示炼金收益和产出统计 milkywayidle 银河奶牛放置

当前为 2025-04-30 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name MWIAlchemyCalc
  3.  
  4. // @namespace http://tampermonkey.net/
  5. // @version 20250430.2
  6. // @description 显示炼金收益和产出统计 milkywayidle 银河奶牛放置
  7.  
  8. // @author IOMisaka
  9. // @match https://www.milkywayidle.com/*
  10. // @match https://test.milkywayidle.com/*
  11. // @icon https://www.milkywayidle.com/favicon.svg
  12. // @grant none
  13. // @license MIT
  14. // ==/UserScript==
  15.  
  16. (function () {
  17. 'use strict';
  18. if (!window.mwi) {
  19. console.error("MWIAlchemyCalc需要安装mooket才能使用");
  20. return;
  21. }
  22.  
  23. ////////////////code//////////////////
  24. function hookWS() {
  25. const dataProperty = Object.getOwnPropertyDescriptor(MessageEvent.prototype, "data");
  26. const oriGet = dataProperty.get;
  27. dataProperty.get = hookedGet;
  28. Object.defineProperty(MessageEvent.prototype, "data", dataProperty);
  29.  
  30. function hookedGet() {
  31. const socket = this.currentTarget;
  32. if (!(socket instanceof WebSocket)) {
  33. return oriGet.call(this);
  34. }
  35. if (socket.url.indexOf("api.milkywayidle.com/ws") <= -1 && socket.url.indexOf("api-test.milkywayidle.com/ws") <= -1) {
  36. return oriGet.call(this);
  37. }
  38. const message = oriGet.call(this);
  39. Object.defineProperty(this, "data", { value: message }); // Anti-loop
  40. handleMessage(message);
  41. return message;
  42. }
  43. }
  44.  
  45. let clientData = null;
  46. let characterData = null;
  47. function loadClientData() {
  48. if (localStorage.getItem("initClientData")) {
  49. const obj = JSON.parse(localStorage.getItem("initClientData"));
  50. clientData = obj;
  51. }
  52. }
  53. let alchemyIndex = 0;
  54. function handleMessage(message) {
  55. let obj = JSON.parse(message);
  56. if (obj) {
  57. if (obj.type === "init_character_data") {
  58. characterData = obj;
  59. } else if (obj.type === "action_type_consumable_slots_updated") {//更新饮料和食物槽数据
  60. characterData.actionTypeDrinkSlotsMap = obj.actionTypeDrinkSlotsMap;
  61. characterData.actionTypeFoodSlotsMap = obj.actionTypeFoodSlotsMap;
  62.  
  63. handleAlchemyDetailChanged();
  64. } else if (obj.type === "consumable_buffs_updated") {
  65. characterData.consumableActionTypeBuffsMap = obj.consumableActionTypeBuffsMap;
  66. handleAlchemyDetailChanged();
  67. } else if (obj.type === "community_buffs_updated") {
  68. characterData.communityActionTypeBuffsMap = obj.communityActionTypeBuffsMap;
  69. handleAlchemyDetailChanged();
  70. } else if (obj.type === "equipment_buffs_updated") {//装备buff
  71. characterData.equipmentActionTypeBuffsMap = obj.equipmentActionTypeBuffsMap;
  72. characterData.equipmentTaskActionBuffs = obj.equipmentTaskActionBuffs;
  73. handleAlchemyDetailChanged();
  74. } else if (obj.type === "house_rooms_updated") {//房屋更新
  75. characterData.characterHouseRoomMap = obj.characterHouseRoomMap;
  76. characterData.houseActionTypeBuffsMap = obj.houseActionTypeBuffsMap;
  77. }
  78. else if (obj.type === "actions_updated") {
  79. //延迟检测
  80. setTimeout(() => {
  81. let firstAction = mwi.game?.state?.characterActions[0];
  82. if (firstAction && firstAction.actionHrid.startsWith("/actions/alchemy")) {
  83. updateAlchemyAction(firstAction);
  84. }
  85. }, 100);
  86.  
  87.  
  88. }
  89. else if (obj.type === "action_completed") {//更新技能等级和经验
  90. if (obj.endCharacterItems) {//道具更新
  91. //炼金统计
  92. try {
  93. if (obj.endCharacterAction.actionHrid.startsWith("/actions/alchemy")) {//炼金统计
  94. updateAlchemyAction(obj.endCharacterAction);
  95.  
  96. let outputHashCount = {};
  97. let inputHashCount = {};
  98. let tempItems = {};
  99. obj.endCharacterItems.forEach(
  100. item => {
  101.  
  102. let existItem = tempItems[item.id] || characterData.characterItems.find(x => x.id === item.id);
  103.  
  104. //console.log("炼金(old):",existItem.id,existItem.itemHrid, existItem.count);
  105. //console.log("炼金(new):", item.id,item.itemHrid, item.count);
  106.  
  107. let delta = (item.count - (existItem?.count || 0));//计数
  108. if (delta < 0) {//数量减少
  109. inputHashCount[item.hash] = (inputHashCount[item.hash] || 0) + delta;//可能多次发送同一个物品
  110. tempItems[item.id] = item;//替换旧的物品计数
  111. } else if (delta > 0) {//数量增加
  112. outputHashCount[item.hash] = (outputHashCount[item.hash] || 0) + delta;//可能多次发送同一个物品
  113. tempItems[item.id] = item;//替换旧的物品计数
  114. } else {
  115. console.log("炼金统计出错?不应该为0", item);
  116. }
  117. }
  118. );
  119. let index = [
  120. "/actions/alchemy/coinify",
  121. "/actions/alchemy/decompose",
  122. "/actions/alchemy/transmute"
  123. ].findIndex(x => x === obj.endCharacterAction.actionHrid);
  124. countAlchemyOutput(inputHashCount, outputHashCount, index);
  125. } else {
  126. alchemyIndex = -1;//不是炼金
  127. }
  128. } catch (e) { }
  129.  
  130. let newIds = obj.endCharacterItems.map(i => i.id);
  131. characterData.characterItems = characterData.characterItems.filter(e => !newIds.includes(e.id));//移除存在的物品
  132. characterData.characterItems.push(...mergeObjectsById(obj.endCharacterItems));//放入新物品
  133. }
  134. if (obj.endCharacterSkills) {
  135. for (let newSkill of obj.endCharacterSkills) {
  136. let oldSkill = characterData.characterSkills.find(skill => skill.skillHrid === newSkill.skillHrid);
  137.  
  138. oldSkill.level = newSkill.level;
  139. oldSkill.experience = newSkill.experience;
  140. }
  141. }
  142. } else if (obj.type === "items_updated") {
  143. if (obj.endCharacterItems) {//道具更新
  144. let newIds = obj.endCharacterItems.map(i => i.id);
  145. characterData.characterItems = characterData.characterItems.filter(e => !newIds.includes(e.id));//移除存在的物品
  146. characterData.characterItems.push(...mergeObjectsById(obj.endCharacterItems));//放入新物品
  147. }
  148. }
  149. }
  150. return message;
  151. }
  152. function mergeObjectsById(list) {
  153. return Object.values(list.reduce((acc, obj) => {
  154. const id = obj.id;
  155. acc[id] = { ...acc[id], ...obj }; // 后面的对象会覆盖前面的
  156. return acc;
  157. }, {}));
  158. }
  159. /////////辅助函数,角色动态数据///////////
  160. // skillHrid = "/skills/alchemy"
  161. function getSkillLevel(skillHrid, withBuff = false) {
  162. let skill = characterData.characterSkills.find(skill => skill.skillHrid === skillHrid);
  163. let level = skill?.level || 0;
  164.  
  165. if (withBuff) {//计算buff加成
  166. level += getBuffValueByType(
  167. skillHrid.replace("/skills/", "/action_types/"),
  168. skillHrid.replace("/skills/", "/buff_types/") + "_level"
  169. );
  170. }
  171. return level;
  172. }
  173.  
  174. /// actionTypeHrid = "/action_types/alchemy"
  175. /// buffTypeHrid = "/buff_types/alchemy_level"
  176. function getBuffValueByType(actionTypeHrid, buffTypeHrid) {
  177. let returnValue = 0;
  178. //社区buff
  179.  
  180. for (let buff of characterData.communityActionTypeBuffsMap[actionTypeHrid] || []) {
  181. if (buff.typeHrid === buffTypeHrid) returnValue += buff.flatBoost;
  182. }
  183. //装备buff
  184. for (let buff of characterData.equipmentActionTypeBuffsMap[actionTypeHrid] || []) {
  185. if (buff.typeHrid === buffTypeHrid) returnValue += buff.flatBoost;
  186. }
  187. //房屋buff
  188. for (let buff of characterData.houseActionTypeBuffsMap[actionTypeHrid] || []) {
  189. if (buff.typeHrid === buffTypeHrid) returnValue += buff.flatBoost;
  190. }
  191. //茶饮buff
  192. for (let buff of characterData.consumableActionTypeBuffsMap[actionTypeHrid] || []) {
  193. if (buff.typeHrid === buffTypeHrid) returnValue += buff.flatBoost;
  194. }
  195. return returnValue;
  196. }
  197. /**
  198. * 获取角色ID
  199. *
  200. * @returns {string|null} 角色ID,如果不存在则返回null
  201. */
  202. function getCharacterId() {
  203. return characterData?.character.id;
  204. }
  205. /**
  206. * 获取指定物品的数量
  207. *
  208. * @param itemHrid 物品的唯一标识
  209. * @param enhancementLevel 物品强化等级,默认为0
  210. * @returns 返回指定物品的数量,如果未找到该物品则返回0
  211. */
  212. function getItemCount(itemHrid, enhancementLevel = 0) {
  213. return characterData.characterItems.find(item => item.itemHrid === itemHrid && item.itemLocationHrid === "/item_locations/inventory" && item.enhancementLevel === enhancementLevel)?.count || 0;//背包里面的物品
  214. }
  215. //获取饮料状态,传入类型/action_types/brewing,返回列表
  216.  
  217. function getDrinkSlots(actionTypeHrid) {
  218. return characterData.actionTypeDrinkSlotsMap[actionTypeHrid]
  219. }
  220. /////////游戏静态数据////////////
  221. //中英文都有可能
  222. function getItemHridByShowName(showName) {
  223. return window.mwi.ensureItemHrid(showName)
  224. }
  225. //类似这样的名字blackberry_donut,knights_ingot
  226. function getItemDataByHridName(hrid_name) {
  227. return clientData.itemDetailMap["/items/" + hrid_name];
  228. }
  229. //类似这样的名字/items/blackberry_donut,/items/knights_ingot
  230. function getItemDataByHrid(itemHrid) {
  231. return clientData.itemDetailMap[itemHrid];
  232. }
  233. //类似这样的名字Blackberry Donut,Knight's Ingot
  234. function getItemDataByName(name) {
  235. return Object.entries(clientData.itemDetailMap).find(([k, v]) => v.name == name);
  236. }
  237. function getOpenableItems(itemHrid) {
  238. let items = [];
  239. for (let openItem of clientData.openableLootDropMap[itemHrid]) {
  240. items.push({
  241. itemHrid: openItem.itemHrid,
  242. count: (openItem.minCount + openItem.maxCount) / 2 * openItem.dropRate
  243. });
  244. }
  245. return items;
  246. }
  247. ////////////观察节点变化/////////////
  248. function observeNode(nodeSelector, rootSelector, addFunc = null, updateFunc = null, removeFunc = null) {
  249. const rootNode = document.querySelector(rootSelector);
  250. if (!rootNode) {
  251. //console.error(`Root node with selector "${rootSelector}" not found.wait for 1s to try again...`);
  252. setTimeout(() => observeNode(nodeSelector, rootSelector, addFunc, updateFunc, removeFunc), 1000);
  253. return;
  254. }
  255. console.info(`observing "${rootSelector}"`);
  256.  
  257. function delayCall(func, observer, delay = 200) {
  258. //判断func是function类型
  259. if (typeof func !== 'function') return;
  260. // 延迟执行,如果再次调用则在原有基础上继续延时
  261. func.timeout && clearTimeout(func.timeout);
  262. func.timeout = setTimeout(() => func(observer), delay);
  263. }
  264.  
  265. const observer = new MutationObserver((mutationsList, observer) => {
  266.  
  267. mutationsList.forEach((mutation) => {
  268. mutation.addedNodes.forEach((addedNode) => {
  269. if (addedNode.matches && addedNode.matches(nodeSelector)) {
  270. addFunc?.(observer);
  271. }
  272. });
  273.  
  274. mutation.removedNodes.forEach((removedNode) => {
  275. if (removedNode.matches && removedNode.matches(nodeSelector)) {
  276. removeFunc?.(observer);
  277. }
  278. });
  279.  
  280. // 处理子节点变化
  281. if (mutation.type === 'childList') {
  282. let node = mutation.target.matches(nodeSelector) ? mutation.target : mutation.target.closest(nodeSelector);
  283. if (node) {
  284. delayCall(updateFunc, observer); // 延迟 100ms 合并变动处理,避免频繁触发
  285. }
  286.  
  287. } else if (mutation.type === 'characterData') {
  288. let node = mutation.target.matches(nodeSelector) ? mutation.target : mutation.target.closest(nodeSelector);
  289. // 文本内容变化(如文本节点修改)
  290. if(node)
  291. delayCall(updateFunc, observer);
  292. }
  293. });
  294. });
  295.  
  296.  
  297. const config = {
  298. childList: true,
  299. subtree: true,
  300. characterData: true
  301. };
  302. observer.reobserve = function () {
  303. observer.observe(rootNode, config);
  304. }//重新观察
  305. observer.observe(rootNode, config);
  306. return observer;
  307. }
  308.  
  309. loadClientData();//加载游戏数据
  310. hookWS();//hook收到角色信息
  311.  
  312. //模块逻辑代码
  313. const MARKET_API_URL = "https://raw.githubusercontent.com/holychikenz/MWIApi/main/milkyapi.json";
  314.  
  315. let marketData = JSON.parse(localStorage.getItem("MWIAPI_JSON") || localStorage.getItem("MWITools_marketAPI_json") || "{}");//Use MWITools的API数据
  316. if (!(marketData?.time > Date.now() / 1000 - 86400)) {//如果本地缓存数据过期,则重新获取
  317. fetch(MARKET_API_URL).then(res => {
  318. res.json().then(data => {
  319. marketData = data;
  320. //更新本地缓存数据
  321. localStorage.setItem("MWIAPI_JSON", JSON.stringify(data));//更新本地缓存数据
  322. console.info("MWIAPI_JSON updated:", new Date(marketData.time * 1000).toLocaleString());
  323. })
  324. });
  325. }
  326.  
  327.  
  328. //返回[买,卖]
  329. function getPrice(itemHrid, enhancementLevel = 0) {
  330. return mwi.coreMarket.getItemPrice(itemHrid, enhancementLevel);
  331. }
  332. let includeRare = false;
  333. let priceMode = "ab";//左买右卖
  334. //计算每次的收益
  335. function calculateProfit(data, isIronCowinify = false) {
  336. let profit = 0;
  337. let input = 0;
  338. let output = 0;
  339. let essence = 0;
  340. let rare = 0;
  341. let tea = 0;
  342. let catalyst = 0;
  343.  
  344. const mode = {
  345. "ab":["ask","bid"],
  346. "ba":["bid","ask"],
  347. "aa":["ask","ask"],
  348. "bb":["bid","bid"],
  349. };
  350. let [buyPrice,sellPrice] = mode[priceMode];
  351.  
  352. for (let item of data.inputItems) {//消耗物品每次必定消耗
  353.  
  354. input -= getPrice(item.itemHrid, item.enhancementLevel)[buyPrice] * item.count;//买入材料价格*数量
  355.  
  356. }
  357. for (let item of data.teaUsage) {//茶每次必定消耗
  358. tea -= getPrice(item.itemHrid)[buyPrice] * item.count;//买入材料价格*数量
  359. }
  360.  
  361. for (let item of data.outputItems) {//产出物品每次不一定产出,需要计算成功率
  362. output += getPrice(item.itemHrid)[sellPrice] * item.count * data.successRate * 0.98;//卖出产出价格*数量*成功率*税后
  363.  
  364. }
  365. if (data.inputItems[0].itemHrid !== "/items/task_crystal") {//任务水晶有问题,暂时不计算
  366. for (let item of data.essenceDrops) {//精华和宝箱与成功率无关 消息id,10211754失败出精华!
  367. essence += getPrice(item.itemHrid)[sellPrice] * item.count *0.98;//采集数据的地方已经算进去了
  368. }
  369. if (includeRare) {//排除宝箱,因为几率过低,严重影响收益显示
  370. for (let item of data.rareDrops) {//宝箱也是按自己的几率出!
  371. // getOpenableItems(item.itemHrid).forEach(openItem => {
  372. // rare += getPrice(openItem.itemHrid).bid * openItem.count * item.count;//已折算
  373. // });
  374. rare += getPrice(item.itemHrid)[sellPrice] * item.count*0.98;//失败要出箱子,消息id,2793104转化,工匠茶失败出箱子了
  375. }
  376. }
  377. }
  378. //催化剂
  379. for (let item of data.catalystItems) {//催化剂,成功才会用
  380. catalyst -= getPrice(item.itemHrid)[buyPrice] * item.count * data.successRate;//买入材料价格*数量
  381. }
  382.  
  383. let description = "";
  384. if (isIronCowinify) {//铁牛不计算输入
  385. profit = tea + output + essence + rare + catalyst;
  386. description = `Last Update${new Date(marketData.time * 1000).toLocaleString()}\n(效率+${(data.effeciency * 100).toFixed(2)}%)每次收益${profit}=\n\t材料(${input})[不计入]\n\t茶(${tea})\n\t催化剂(${catalyst})\n\t产出(${output})\n\t精华(${essence})\n\t稀有(${rare})`;
  387.  
  388. } else {
  389. profit = input + tea + output + essence + rare + catalyst;
  390. description = `Last Update${new Date(marketData.time * 1000).toLocaleString()}\n(效率+${(data.effeciency * 100).toFixed(2)}%)每次收益${profit}=\n\t材料(${input})\n\t茶(${tea})\n\t催化剂(${catalyst})\n\t产出(${output})\n\t精华(${essence})\n\t稀有(${rare})`;
  391. }
  392.  
  393. //console.info(description);
  394. return [profit, description];//再乘以次数
  395. }
  396.  
  397. function showNumber(num) {
  398. if (isNaN(num)) return num;
  399. if (num === 0) return "0";// 单独处理0的情况
  400.  
  401. const sign = num > 0 ? '+' : '';
  402. const absNum = Math.abs(num);
  403.  
  404. return absNum >= 1e10 ? `${sign}${(num / 1e9).toFixed(1)}B` :
  405. absNum >= 1e7 ? `${sign}${(num / 1e6).toFixed(1)}M` :
  406. absNum >= 1e5 ? `${sign}${Math.floor(num / 1e3)}K` :
  407. `${sign}${Math.floor(num)}`;
  408. }
  409. function parseNumber(str) {
  410. return parseInt(str.replaceAll("/", "").replaceAll(",", "").replaceAll(" ", ""));
  411. }
  412. let predictPerDay = {};
  413. function handleAlchemyDetailChanged(observer) {
  414. let inputItems = [];
  415. let outputItems = [];
  416. let essenceDrops = [];
  417. let rareDrops = [];
  418. let teaUsage = [];
  419. let catalystItems = [];
  420.  
  421. let costNodes = document.querySelector(".AlchemyPanel_skillActionDetailContainer__o9SsW .SkillActionDetail_itemRequirements__3SPnA");
  422. if (!costNodes) return;//没有炼金详情就不处理
  423.  
  424. let costs = Array.from(costNodes.children);
  425. //每三个元素取textContent拼接成一个字符串,用空格和/分割
  426. for (let i = 0; i < costs.length; i += 3) {
  427.  
  428. let need = parseNumber(costs[i + 1].textContent);
  429. let nameArr = costs[i + 2].textContent.split("+");
  430. let itemHrid = getItemHridByShowName(nameArr[0]);
  431. let enhancementLevel = nameArr.length > 1 ? parseNumber(nameArr[1]) : 0;
  432.  
  433. inputItems.push({ itemHrid: itemHrid, enhancementLevel: enhancementLevel, count: need });
  434. }
  435.  
  436. //炼金输出
  437. for (let line of document.querySelectorAll(".SkillActionDetail_alchemyOutput__6-92q .SkillActionDetail_drop__26KBZ")) {
  438. let count = parseFloat(line.children[0].textContent.replaceAll(",", ""));
  439. let itemName = line.children[1].textContent;
  440. let rate = line.children[2].textContent ? parseFloat(line.children[2].textContent.substring(1, line.children[2].textContent.length - 1) / 100.0) : 1;//默认1
  441. outputItems.push({ itemHrid: getItemHridByShowName(itemName), count: count * rate });
  442. }
  443. //精华输出
  444. for (let line of document.querySelectorAll(".SkillActionDetail_essenceDrops__2skiB .SkillActionDetail_drop__26KBZ")) {
  445. let count = parseFloat(line.children[0].textContent);
  446. let itemName = line.children[1].textContent;
  447. let rate = line.children[2].textContent ? parseFloat(line.children[2].textContent.substring(1, line.children[2].textContent.length - 1) / 100.0) : 1;//默认1
  448. essenceDrops.push({ itemHrid: getItemHridByShowName(itemName), count: count * rate });
  449. }
  450. //稀有输出
  451. for (let line of document.querySelectorAll(".SkillActionDetail_rareDrops__3OTzu .SkillActionDetail_drop__26KBZ")) {
  452. let count = parseFloat(line.children[0].textContent);
  453. let itemName = line.children[1].textContent;
  454. let rate = line.children[2].textContent ? parseFloat(line.children[2].textContent.substring(1, line.children[2].textContent.length - 1) / 100.0) : 1;//默认1
  455. rareDrops.push({ itemHrid: getItemHridByShowName(itemName), count: count * rate });
  456. }
  457. //成功率
  458. let successRateStr = document.querySelector(".SkillActionDetail_successRate__2jPEP .SkillActionDetail_value__dQjYH").textContent;
  459. let successRate = parseFloat(successRateStr.substring(0, successRateStr.length - 1)) / 100.0;
  460.  
  461. //消耗时间
  462. let costTimeStr = document.querySelector(".SkillActionDetail_timeCost__1jb2x .SkillActionDetail_value__dQjYH").textContent;
  463. let costSeconds = parseFloat(costTimeStr.substring(0, costTimeStr.length - 1));//秒,有分再改
  464.  
  465.  
  466.  
  467. //催化剂
  468. let catalystItem = document.querySelector(".SkillActionDetail_catalystItemInput__2ERjq .Icon_icon__2LtL_") || document.querySelector(".SkillActionDetail_catalystItemInputContainer__5zmou .Item_iconContainer__5z7j4 .Icon_icon__2LtL_");//过程中是另一个框
  469. if (catalystItem) {
  470. catalystItems = [{ itemHrid: getItemHridByShowName(catalystItem.getAttribute("aria-label")), count: 1 }];
  471. }
  472.  
  473. //计算效率
  474. let effeciency = getBuffValueByType("/action_types/alchemy", "/buff_types/efficiency");
  475. let skillLevel = getSkillLevel("/skills/alchemy", true);
  476. let mainItem = getItemDataByHrid(inputItems[0].itemHrid);
  477. if (mainItem.itemLevel) {
  478. effeciency += Math.max(0, skillLevel - mainItem.itemLevel) / 100;//等级加成
  479. }
  480.  
  481. //costSeconds = costSeconds * (1 - effeciency);//效率,相当于减少每次的时间
  482. costSeconds = costSeconds / (1 + effeciency);
  483. //茶饮,茶饮的消耗就减少了
  484. let teas = getDrinkSlots("/action_types/alchemy");//炼金茶配置
  485. for (let tea of teas) {
  486. if (tea) {//有可能空位
  487. teaUsage.push({ itemHrid: tea.itemHrid, count: costSeconds / 300 });//300秒消耗一个茶
  488. }
  489. }
  490. console.info("效率", effeciency);
  491.  
  492.  
  493. //返回结果
  494. let ret = {
  495. inputItems: inputItems,
  496. outputItems: outputItems,
  497. essenceDrops: essenceDrops,
  498. rareDrops: rareDrops,
  499. successRate: successRate,
  500. costTime: costSeconds,
  501. teaUsage: teaUsage,
  502. catalystItems: catalystItems,
  503. effeciency: effeciency,
  504. }
  505. const buttons = document.querySelectorAll(".AlchemyPanel_tabsComponentContainer__1f7FY .MuiButtonBase-root.MuiTab-root.MuiTab-textColorPrimary.css-1q2h7u5");
  506. const selectedIndex = Array.from(buttons).findIndex(button =>
  507. button.classList.contains('Mui-selected')
  508. );
  509. let isIronCowinify = (selectedIndex == 0 || (selectedIndex == 3 && alchemyIndex == 0)) && mwi.character?.gameMode === "ironcow";//铁牛点金
  510. //次数,收益
  511. let result = calculateProfit(ret, isIronCowinify);
  512. let profit = result[0];
  513. let desc = result[1];
  514.  
  515. let timesPerHour = 3600 / costSeconds;//加了效率相当于增加了次数
  516. let profitPerHour = profit * timesPerHour;
  517.  
  518. let timesPerDay = 24 * timesPerHour;
  519. let profitPerDay = profit * timesPerDay;
  520.  
  521. predictPerDay[selectedIndex] = profitPerDay;//记录第几个对应的每日收益
  522.  
  523. observer?.disconnect();//断开观察
  524.  
  525. //显示位置
  526. let showParent = document.querySelector(".SkillActionDetail_notes__2je2F");
  527. let label = showParent.querySelector("#alchemoo");
  528. if (!label) {
  529. label = document.createElement("div");
  530. label.id = "alchemoo";
  531. showParent.appendChild(label);
  532. }
  533.  
  534. let color = "white";
  535. if (profitPerHour > 0) {
  536. color = "lime";
  537. } else if (profitPerHour < 0) {
  538. color = "red";
  539. }
  540. label.innerHTML = `
  541. <div id="alchemoo" style="color: ${color};">
  542. <div>
  543. <span title="(2%税后)\n${desc}">预估收益ℹ️:</span><input type="checkbox" id="alchemoo_includeRare"/><label for="alchemoo_includeRare">稀有</label>
  544. <select id="alchemoo_selectMode">
  545. <option value="ab">左买右卖</option>
  546. <option value="ba">右买左卖</option>
  547. <option value="aa">左买左卖</option>
  548. <option value="bb">右买右卖</option>
  549. </select>
  550. </div>
  551. <div>
  552. <svg width="14px" height="14px" style="display:inline-block"><use href="/static/media/items_sprite.6d12eb9d.svg#coin"></use></svg>
  553. <span>${showNumber(profit)}/次</span>
  554. </div>
  555. <div>
  556. <svg width="14px" height="14px" style="display:inline-block"><use href="/static/media/items_sprite.6d12eb9d.svg#coin"></use></svg>
  557. <span title="${showNumber(timesPerHour)}次">${showNumber(profitPerHour)}/时</span>
  558. </div>
  559. <div>
  560. <svg width="14px" height="14px" style="display:inline-block"><use href="/static/media/items_sprite.6d12eb9d.svg#coin"></use></svg>
  561. <span title="${showNumber(timesPerDay)}次">${showNumber(profitPerDay)}/天</span>
  562. </div>
  563. </div>`;
  564. document.querySelector("#alchemoo_includeRare").checked = includeRare;
  565. document.querySelector("#alchemoo_includeRare").addEventListener("change", function () {
  566. includeRare = this.checked;
  567. handleAlchemyDetailChanged();//重新计算
  568. });
  569. document.querySelector("#alchemoo_selectMode").value = priceMode;
  570. document.querySelector("#alchemoo_selectMode").addEventListener("change", function () {
  571. priceMode = this.value;
  572. handleAlchemyDetailChanged();//重新计算
  573. });
  574.  
  575. //console.log(ret);
  576. observer?.reobserve();
  577. }
  578.  
  579. observeNode(".SkillActionDetail_alchemyComponent__1J55d", "body", handleAlchemyDetailChanged, handleAlchemyDetailChanged);
  580.  
  581. let currentInput = {};
  582. let currentOutput = {};
  583. let alchemyStartTime = Date.now();
  584. let lastAction = null;
  585.  
  586. //统计功能
  587. function countAlchemyOutput(inputHashCount, outputHashCount, index) {
  588. alchemyIndex = index;
  589. for (let itemHash in inputHashCount) {
  590. currentInput[itemHash] = (currentInput[itemHash] || 0) + inputHashCount[itemHash];
  591. }
  592. for (let itemHash in outputHashCount) {
  593. currentOutput[itemHash] = (currentOutput[itemHash] || 0) + outputHashCount[itemHash];
  594. }
  595. showOutput();
  596. }
  597.  
  598. function updateAlchemyAction(action) {
  599. if ((!lastAction) || (lastAction.id != action.id)) {//新动作,重置统计信息
  600. lastAction = action;
  601. currentOutput = {};
  602. currentInput = {};
  603. alchemyStartTime = Date.now();//重置开始时间
  604. }
  605. showOutput();
  606. }
  607. function calcChestPrice(itemHrid) {
  608. let total = 0;
  609. getOpenableItems(itemHrid).forEach(openItem => {
  610. total += getPrice(openItem.itemHrid).bid * openItem.count;
  611. });
  612. return total;
  613. }
  614. function calcPrice(items) {
  615. let total = 0;
  616. for (let item of items) {
  617.  
  618. if (item.itemHrid === "/items/task_crystal") {//任务水晶有问题,暂时不计算
  619. }
  620. else if (getItemDataByHrid(item.itemHrid)?.categoryHrid === "/item_categories/loot") {
  621. total += calcChestPrice(item.itemHrid) * item.count;
  622. } else {
  623. total += getPrice(item.itemHrid, item.enhancementLevel ?? 0).ask * item.count;//买入材料价格*数量
  624. }
  625.  
  626. }
  627. return total;
  628. }
  629. function itemHashToItem(itemHash) {
  630. let item = {};
  631. let arr = itemHash.split("::");
  632. item.itemHrid = arr[2];
  633. item.enhancementLevel = arr[3];
  634. return item;
  635. }
  636. function getItemNameByHrid(itemHrid) {
  637. return mwi.isZh ?
  638. mwi.lang.zh.translation.itemNames[itemHrid] : mwi.lang.en.translation.itemNames[itemHrid];
  639. }
  640. function secondsToHms(seconds) {
  641. seconds = Number(seconds);
  642. const h = Math.floor(seconds / 3600);
  643. const m = Math.floor((seconds % 3600) / 60);
  644. const s = Math.floor(seconds % 60);
  645.  
  646. return [
  647. h.toString().padStart(2, '0'),
  648. m.toString().padStart(2, '0'),
  649. s.toString().padStart(2, '0')
  650. ].join(':');
  651. }
  652. function showOutput() {
  653. let alchemyContainer = document.querySelector(".SkillActionDetail_alchemyComponent__1J55d");
  654. if (!alchemyContainer) return;
  655.  
  656. if (!document.querySelector("#alchemoo_result")) {
  657. let outputContainer = document.createElement("div");
  658. outputContainer.id = "alchemoo_result";
  659. outputContainer.style.fontSize = "13px";
  660. outputContainer.style.lineHeight = "16px";
  661. outputContainer.style.maxWidth = "220px";
  662. outputContainer.innerHTML = `
  663. <div id="alchemoo_title" style="font-weight: bold; margin-bottom: 10px; text-align: center; color: var(--color-space-300);">炼金结果</div>
  664. <div id="alchemoo_cost" style="display: flex; flex-wrap: wrap; gap: 4px;"></div>
  665. <div id="alchemoo_rate"></div>
  666. <div id="alchemoo_output" style="display: flex; flex-wrap: wrap; gap: 4px;"></div>
  667. <div id="alchemoo_essence"></div>
  668. <div id="alchemoo_rare"></div>
  669. <div id="alchemoo_exp"></div>
  670. <div id="alchemoo_time"></div>
  671. <div id="alchemoo_total" style="font-weight:bold;font-size:16px;border:1px solid var(--color-space-300);border-radius:4px;padding:1px 5px;display: flex; flex-direction: column; align-items: flex-start; gap: 4px;"></div>
  672. `;
  673. outputContainer.style.flex = "0 0 auto";
  674. alchemyContainer.appendChild(outputContainer);
  675. }
  676. "💰"
  677.  
  678. let cost = calcPrice(Object.entries(currentInput).map(
  679. ([itemHash, count]) => {
  680. let arr = itemHash.split("::");
  681. return { "itemHrid": arr[2], "enhancementLevel": parseInt(arr[3]), "count": count }
  682. })
  683. );
  684. let gain = calcPrice(Object.entries(currentOutput).map(
  685. ([itemHash, count]) => {
  686. let arr = itemHash.split("::");
  687. return { "itemHrid": arr[2], "enhancementLevel": parseInt(arr[3]), "count": count }
  688. })
  689. );
  690. if (alchemyIndex == 0 && mwi.character?.gameMode === "ironcow") { cost = 0 };//铁牛点金,不计算成本
  691. let total = cost + gain;
  692.  
  693. let text = "";
  694. //消耗
  695. Object.entries(currentInput).forEach(([itemHash, count]) => {
  696. let item = itemHashToItem(itemHash);
  697. let price = getPrice(item.itemHrid);
  698. text += `
  699. <div title="直买价:${price.ask}" style="display: inline-flex;border:1px solid var(--color-space-300);border-radius:4px;padding:1px 5px;">
  700. <svg width="14px" height="14px" style="display:inline-block"><use href="/static/media/items_sprite.6d12eb9d.svg#${item.itemHrid.replace("/items/", "")}"></use></svg>
  701. <span style="display:inline-block">${getItemNameByHrid(item.itemHrid)}</span>
  702. <span style="color:red;display:inline-block;font-size:14px;">${showNumber(count).replace("-", "*")}</span>
  703. </div>
  704. `;
  705. });
  706. if (cost > 0) {//0不显示
  707. text += `<div style="display: inline-block;border:1px solid var(--color-space-300);border-radius:4px;padding:1px 5px;"><span style="color:red;font-size:16px;">${showNumber(cost)}</span></div>`;
  708. }
  709. document.querySelector("#alchemoo_cost").innerHTML = text;
  710.  
  711. document.querySelector("#alchemoo_rate").innerHTML = `<br/>`;//成功率
  712.  
  713. text = "";
  714. Object.entries(currentOutput).forEach(([itemHash, count]) => {
  715. let item = itemHashToItem(itemHash);
  716. let price = getPrice(item.itemHrid);
  717. text += `
  718. <div title="直卖价:${price.bid}" style="display: inline-flex;border:1px solid var(--color-space-300);border-radius:4px;padding:1px 5px;">
  719. <svg width="14px" height="14px" style="display:inline-block"><use href="/static/media/items_sprite.6d12eb9d.svg#${item.itemHrid.replace("/items/", "")}"></use></svg>
  720. <span style="display:inline-block">${getItemNameByHrid(item.itemHrid)}</span>
  721. <span style="color:lime;display:inline-block;font-size:14px;">${showNumber(count).replace("+", "*")}</span>
  722. </div>
  723. `;
  724. });
  725. if (gain > 0) {//0不显示
  726. text += `<div style="display: inline-block;border:1px solid var(--color-space-300);border-radius:4px;padding:1px 5px;"><span style="color:lime;font-size:16px;">${showNumber(gain)}</span></div>`;
  727. }
  728. document.querySelector("#alchemoo_output").innerHTML = text;//产出
  729.  
  730. //document.querySelector("#alchemoo_essence").innerHTML = `<br/>`;//精华
  731. //document.querySelector("#alchemoo_rare").innerHTML = `<br/>`;//稀有
  732. document.querySelector("#alchemoo_exp").innerHTML = `<br/>`;//经验
  733. let time = (Date.now() - alchemyStartTime) / 1000;
  734. //document.querySelector("#alchemoo_time").innerHTML = `<span>耗时:${secondsToHms(time)}</span>`;//时间
  735. let perDay = (86400 / time) * total;
  736.  
  737. let profitPerDay = predictPerDay[alchemyIndex] || 0;
  738. document.querySelector("#alchemoo_total").innerHTML =
  739. `
  740. <span>耗时:${secondsToHms(time)}</span>
  741. <div>累计收益:<span style="color:${total > 0 ? "lime" : "red"}">${showNumber(total)}</span></div>
  742. <div>每日收益:<span style="color:${perDay > profitPerDay ? "lime" : "red"}">${showNumber(total * (86400 / time)).replace("+", "")}</span></div>
  743. `;//总收益
  744. }
  745. //mwi.hookMessage("action_completed", countAlchemyOutput);
  746. //mwi.hookMessage("action_updated", updateAlchemyAction)
  747. })();