Greasy Fork is available in English.

MWIAlchemyCalc

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

  1. // ==UserScript==
  2. // @name MWIAlchemyCalc
  3.  
  4. // @namespace http://tampermonkey.net/
  5. // @version 20250501.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 mwi.initClientData.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. // 文本内容变化(如文本节点修改)
  289. delayCall(updateFunc, observer);
  290. }
  291. });
  292. });
  293.  
  294.  
  295. const config = {
  296. childList: true,
  297. subtree: true,
  298. characterData: true
  299. };
  300. observer.reobserve = function () {
  301. observer.observe(rootNode, config);
  302. }//重新观察
  303. observer.observe(rootNode, config);
  304. return observer;
  305. }
  306.  
  307. loadClientData();//加载游戏数据
  308. hookWS();//hook收到角色信息
  309.  
  310. //模块逻辑代码
  311. const MARKET_API_URL = "https://raw.githubusercontent.com/holychikenz/MWIApi/main/milkyapi.json";
  312.  
  313. let marketData = JSON.parse(localStorage.getItem("MWIAPI_JSON") || localStorage.getItem("MWITools_marketAPI_json") || "{}");//Use MWITools的API数据
  314. if (!(marketData?.time > Date.now() / 1000 - 86400)) {//如果本地缓存数据过期,则重新获取
  315. fetch(MARKET_API_URL).then(res => {
  316. res.json().then(data => {
  317. marketData = data;
  318. //更新本地缓存数据
  319. localStorage.setItem("MWIAPI_JSON", JSON.stringify(data));//更新本地缓存数据
  320. console.info("MWIAPI_JSON updated:", new Date(marketData.time * 1000).toLocaleString());
  321. })
  322. });
  323. }
  324.  
  325.  
  326. //返回[买,卖]
  327. function getPrice(itemHrid, enhancementLevel = 0) {
  328. return mwi.coreMarket.getItemPrice(itemHrid, enhancementLevel);
  329. }
  330. let includeRare = false;
  331. let priceMode = "ab";//左买右卖
  332. //计算每次的收益
  333. function calculateProfit(data, isIroncow = false, isCoinify = false) {
  334. let profit = 0;
  335. let input = 0;
  336. let output = 0;
  337. let essence = 0;
  338. let rare = 0;
  339. let tea = 0;
  340. let catalyst = 0;
  341. let tax = isIroncow ? 1 : 0.98;//铁牛不扣税
  342.  
  343. const mode = {
  344. "ab": ["ask", "bid"],
  345. "ba": ["bid", "ask"],
  346. "aa": ["ask", "ask"],
  347. "bb": ["bid", "bid"],
  348. };
  349. let [buyPrice, sellPrice] = mode[priceMode];
  350.  
  351. for (let item of data.inputItems) {//消耗物品每次必定消耗
  352.  
  353. input -= getPrice(item.itemHrid, item.enhancementLevel)[buyPrice] * item.count;//买入材料价格*数量
  354.  
  355. }
  356. for (let item of data.teaUsage) {//茶每次必定消耗
  357. tea -= getPrice(item.itemHrid)[buyPrice] * item.count;//买入材料价格*数量
  358. }
  359.  
  360. for (let item of data.outputItems) {//产出物品每次不一定产出,需要计算成功率
  361. output += getPrice(item.itemHrid)[sellPrice] * item.count * data.successRate * tax;//卖出产出价格*数量*成功率*税后
  362.  
  363. }
  364. if (data.inputItems[0].itemHrid !== "/items/task_crystal") {//任务水晶有问题,暂时不计算
  365. for (let item of data.essenceDrops) {//精华和宝箱与成功率无关 消息id,10211754失败出精华!
  366. essence += getPrice(item.itemHrid)[sellPrice] * item.count * tax;//采集数据的地方已经算进去了
  367. }
  368. if (includeRare) {//排除宝箱,因为几率过低,严重影响收益显示
  369. for (let item of data.rareDrops) {//宝箱也是按自己的几率出!
  370. // getOpenableItems(item.itemHrid).forEach(openItem => {
  371. // rare += getPrice(openItem.itemHrid).bid * openItem.count * item.count;//已折算
  372. // });
  373. rare += getPrice(item.itemHrid)[sellPrice] * item.count * tax;//失败要出箱子,消息id,2793104转化,工匠茶失败出箱子了
  374. }
  375. }
  376. }
  377. //催化剂
  378. for (let item of data.catalystItems) {//催化剂,成功才会用
  379. catalyst -= getPrice(item.itemHrid)[buyPrice] * item.count * data.successRate;//买入材料价格*数量
  380. }
  381.  
  382. let description = "";
  383. if (isIroncow && isCoinify) {//铁牛点金不计算输入
  384. profit = tea + output + essence + rare + catalyst;
  385. description = `Last Update${new Date(marketData.time * 1000).toLocaleString()}
  386. (${mwi.isZh ? "税" : "tax"}${isIroncow ? "0" : "2%"})
  387. (${mwi.isZh ? "效率" : "effeciency"}+${(data.effeciency * 100).toFixed(2)}%)
  388. ${mwi.isZh ? "每次收益" : "each"}:${profit}=
  389. \t${mwi.isZh ? "材料" : "material"}(${input})[${mwi.isZh ? "铁牛点金不计入" : "not included for ironcowinify"}]
  390. \t${mwi.isZh ? "茶" : "tea"}(${tea})
  391. \t${mwi.isZh ? "催化剂" : "catalyst"}(${catalyst})
  392. \t${mwi.isZh ? "产出" : "output"}(${output})
  393. \t${mwi.isZh ? "精华" : "essence"}(${essence})
  394. \t${mwi.isZh ? "稀有" : "rare"}(${rare})`;
  395.  
  396. } else {
  397. profit = input + tea + output + essence + rare + catalyst;
  398. description = `Last Update${new Date(marketData.time * 1000).toLocaleString()}
  399. (${mwi.isZh ? "税" : "tax"}${isIroncow ? "0" : "2%"})
  400. (${mwi.isZh ? "效率" : "effeciency"}+${(data.effeciency * 100).toFixed(2)}%)
  401. ${mwi.isZh ? "每次收益" : "each"}:${profit}=
  402. \t${mwi.isZh ? "材料" : "material"}(${input})
  403. \t${mwi.isZh ? "茶" : "tea"}(${tea})
  404. \t${mwi.isZh ? "催化剂" : "catalyst"}(${catalyst})
  405. \t${mwi.isZh ? "产出" : "output"}(${output})
  406. \t${mwi.isZh ? "精华" : "essence"}(${essence})
  407. \t${mwi.isZh ? "稀有" : "rare"}(${rare})`;
  408. }
  409.  
  410. //console.info(description);
  411. return [profit, description];//再乘以次数
  412. }
  413.  
  414. function showNumber(num) {
  415. if (isNaN(num)) return num;
  416. if (num === 0) return "0";// 单独处理0的情况
  417.  
  418. const sign = num > 0 ? '+' : '';
  419. const absNum = Math.abs(num);
  420.  
  421. return absNum >= 1e10 ? `${sign}${(num / 1e9).toFixed(1)}B` :
  422. absNum >= 1e7 ? `${sign}${(num / 1e6).toFixed(1)}M` :
  423. absNum >= 1e5 ? `${sign}${Math.floor(num / 1e3)}K` :
  424. `${sign}${Math.floor(num)}`;
  425. }
  426. function parseNumber(str) {
  427. return parseInt(str.replaceAll("/", "").replaceAll(",", "").replaceAll(" ", ""));
  428. }
  429. let predictPerDay = {};
  430. function handleAlchemyDetailChanged(observer) {
  431. let inputItems = [];
  432. let outputItems = [];
  433. let essenceDrops = [];
  434. let rareDrops = [];
  435. let teaUsage = [];
  436. let catalystItems = [];
  437.  
  438. let costNodes = document.querySelector(".AlchemyPanel_skillActionDetailContainer__o9SsW .SkillActionDetail_itemRequirements__3SPnA");
  439. if (!costNodes) return;//没有炼金详情就不处理
  440.  
  441. let costs = Array.from(costNodes.children);
  442. //每三个元素取textContent拼接成一个字符串,用空格和/分割
  443. for (let i = 0; i < costs.length; i += 3) {
  444.  
  445. let need = parseNumber(costs[i + 1].textContent);
  446. let nameArr = costs[i + 2].textContent.split("+");
  447. let itemHrid = getItemHridByShowName(nameArr[0]);
  448. let enhancementLevel = nameArr.length > 1 ? parseNumber(nameArr[1]) : 0;
  449.  
  450. inputItems.push({ itemHrid: itemHrid, enhancementLevel: enhancementLevel, count: need });
  451. }
  452.  
  453. //炼金输出
  454. for (let line of document.querySelectorAll(".SkillActionDetail_alchemyOutput__6-92q .SkillActionDetail_drop__26KBZ")) {
  455. let count = parseFloat(line.children[0].textContent.replaceAll(",", ""));
  456. let itemName = line.children[1].textContent;
  457. let rate = line.children[2].textContent ? parseFloat(line.children[2].textContent.substring(1, line.children[2].textContent.length - 1) / 100.0) : 1;//默认1
  458. outputItems.push({ itemHrid: getItemHridByShowName(itemName), count: count * rate });
  459. }
  460. //精华输出
  461. for (let line of document.querySelectorAll(".SkillActionDetail_essenceDrops__2skiB .SkillActionDetail_drop__26KBZ")) {
  462. let count = parseFloat(line.children[0].textContent);
  463. let itemName = line.children[1].textContent;
  464. let rate = line.children[2].textContent ? parseFloat(line.children[2].textContent.substring(1, line.children[2].textContent.length - 1) / 100.0) : 1;//默认1
  465. essenceDrops.push({ itemHrid: getItemHridByShowName(itemName), count: count * rate });
  466. }
  467. //稀有输出
  468. for (let line of document.querySelectorAll(".SkillActionDetail_rareDrops__3OTzu .SkillActionDetail_drop__26KBZ")) {
  469. let count = parseFloat(line.children[0].textContent);
  470. let itemName = line.children[1].textContent;
  471. let rate = line.children[2].textContent ? parseFloat(line.children[2].textContent.substring(1, line.children[2].textContent.length - 1) / 100.0) : 1;//默认1
  472. rareDrops.push({ itemHrid: getItemHridByShowName(itemName), count: count * rate });
  473. }
  474. //成功率
  475. let successRateStr = document.querySelector(".SkillActionDetail_successRate__2jPEP .SkillActionDetail_value__dQjYH").textContent;
  476. let successRate = parseFloat(successRateStr.substring(0, successRateStr.length - 1)) / 100.0;
  477.  
  478. //消耗时间
  479. let costTimeStr = document.querySelector(".SkillActionDetail_timeCost__1jb2x .SkillActionDetail_value__dQjYH").textContent;
  480. let costSeconds = parseFloat(costTimeStr.substring(0, costTimeStr.length - 1));//秒,有分再改
  481.  
  482.  
  483.  
  484. //催化剂
  485. let catalystItem = document.querySelector(".SkillActionDetail_catalystItemInput__2ERjq .Icon_icon__2LtL_") || document.querySelector(".SkillActionDetail_catalystItemInputContainer__5zmou .Item_iconContainer__5z7j4 .Icon_icon__2LtL_");//过程中是另一个框
  486. if (catalystItem) {
  487. catalystItems = [{ itemHrid: getItemHridByShowName(catalystItem.getAttribute("aria-label")), count: 1 }];
  488. }
  489.  
  490. //计算效率
  491. let effeciency = getBuffValueByType("/action_types/alchemy", "/buff_types/efficiency");
  492. let skillLevel = getSkillLevel("/skills/alchemy", true);
  493. let mainItem = getItemDataByHrid(inputItems[0].itemHrid);
  494. if (mainItem.itemLevel) {
  495. effeciency += Math.max(0, skillLevel - mainItem.itemLevel) / 100;//等级加成
  496. }
  497.  
  498. //costSeconds = costSeconds * (1 - effeciency);//效率,相当于减少每次的时间
  499. costSeconds = costSeconds / (1 + effeciency);
  500. //茶饮,茶饮的消耗就减少了
  501. let teas = getDrinkSlots("/action_types/alchemy");//炼金茶配置
  502. for (let tea of teas) {
  503. if (tea) {//有可能空位
  504. teaUsage.push({ itemHrid: tea.itemHrid, count: costSeconds / 300 });//300秒消耗一个茶
  505. }
  506. }
  507. console.info("效率", effeciency);
  508.  
  509.  
  510. //返回结果
  511. let ret = {
  512. inputItems: inputItems,
  513. outputItems: outputItems,
  514. essenceDrops: essenceDrops,
  515. rareDrops: rareDrops,
  516. successRate: successRate,
  517. costTime: costSeconds,
  518. teaUsage: teaUsage,
  519. catalystItems: catalystItems,
  520. effeciency: effeciency,
  521. }
  522. const buttons = document.querySelectorAll(".AlchemyPanel_tabsComponentContainer__1f7FY .MuiButtonBase-root.MuiTab-root.MuiTab-textColorPrimary.css-1q2h7u5");
  523. const selectedIndex = Array.from(buttons).findIndex(button =>
  524. button.classList.contains('Mui-selected')
  525. );
  526. let isCowinify = (selectedIndex == 0 || (selectedIndex == 3 && alchemyIndex == 0));//点金模式
  527.  
  528. //次数,收益
  529. let result = calculateProfit(ret, mwi.character?.gameMode === "ironcow", isCowinify);
  530. let profit = result[0];
  531. let desc = result[1];
  532.  
  533. let timesPerHour = 3600 / costSeconds;//加了效率相当于增加了次数
  534. let profitPerHour = profit * timesPerHour;
  535.  
  536. let timesPerDay = 24 * timesPerHour;
  537. let profitPerDay = profit * timesPerDay;
  538.  
  539. predictPerDay[selectedIndex] = profitPerDay;//记录第几个对应的每日收益
  540.  
  541. observer?.disconnect();//断开观察
  542.  
  543. //显示位置
  544. let showParent = document.querySelector(".SkillActionDetail_notes__2je2F");
  545. let label = showParent.querySelector("#alchemoo");
  546. if (!label) {
  547. label = document.createElement("div");
  548. label.id = "alchemoo";
  549. showParent.appendChild(label);
  550. }
  551.  
  552. let color = "white";
  553. if (profitPerHour > 0) {
  554. color = "lime";
  555. } else if (profitPerHour < 0) {
  556. color = "red";
  557. }
  558. label.innerHTML = `
  559. <div id="alchemoo" style="color: ${color};">
  560. <div>
  561. <span title="${desc}">${mwi.isZh ? "预估收益" : "Profit"}ℹ️:</span><input type="checkbox" id="alchemoo_includeRare"/><label for="alchemoo_includeRare">${mwi.isZh ? "稀有" : "Rares"}</label>
  562. <select id="alchemoo_selectMode">
  563. <option value="ab">${mwi.isZh ? "左买右卖" : "ask in,bid out"}</option>
  564. <option value="ba">${mwi.isZh ? "右买左卖" : "bid in,ask out"}</option>
  565. <option value="aa">${mwi.isZh ? "左买左卖" : "ask in,ask out"}</option>
  566. <option value="bb">${mwi.isZh ? "右买右卖" : "bid in,bid out"}</option>
  567. </select>
  568. </div>
  569. <div>
  570. <svg width="14px" height="14px" style="display:inline-block"><use href="/static/media/items_sprite.6d12eb9d.svg#coin"></use></svg>
  571. <span>${showNumber(profit)}/${mwi.isZh ? "次" : "each"}</span>
  572. </div>
  573. <div>
  574. <svg width="14px" height="14px" style="display:inline-block"><use href="/static/media/items_sprite.6d12eb9d.svg#coin"></use></svg>
  575. <span title="${showNumber(timesPerHour)}${mwi.isZh ? "" : "times"}">${showNumber(profitPerHour)}/${mwi.isZh ? "时" : "hour"}</span>
  576. </div>
  577. <div>
  578. <svg width="14px" height="14px" style="display:inline-block"><use href="/static/media/items_sprite.6d12eb9d.svg#coin"></use></svg>
  579. <span title="${showNumber(timesPerDay)}${mwi.isZh ? "" : "times"}">${showNumber(profitPerDay)}/${mwi.isZh ? "天" : "day"}</span>
  580. </div>
  581. </div>`;
  582. document.querySelector("#alchemoo_includeRare").checked = includeRare;
  583. document.querySelector("#alchemoo_includeRare").addEventListener("change", function () {
  584. includeRare = this.checked;
  585. handleAlchemyDetailChanged();//重新计算
  586. });
  587. document.querySelector("#alchemoo_selectMode").value = priceMode;
  588. document.querySelector("#alchemoo_selectMode").addEventListener("change", function () {
  589. priceMode = this.value;
  590. handleAlchemyDetailChanged();//重新计算
  591. });
  592.  
  593. //console.log(ret);
  594. observer?.reobserve();
  595. }
  596.  
  597. observeNode(".SkillActionDetail_alchemyComponent__1J55d", "body", handleAlchemyDetailChanged, handleAlchemyDetailChanged);
  598.  
  599. let currentInput = {};
  600. let currentOutput = {};
  601. let alchemyStartTime = Date.now();
  602. let lastAction = null;
  603.  
  604. //统计功能
  605. function countAlchemyOutput(inputHashCount, outputHashCount, index) {
  606. alchemyIndex = index;
  607. for (let itemHash in inputHashCount) {
  608. currentInput[itemHash] = (currentInput[itemHash] || 0) + inputHashCount[itemHash];
  609. }
  610. for (let itemHash in outputHashCount) {
  611. currentOutput[itemHash] = (currentOutput[itemHash] || 0) + outputHashCount[itemHash];
  612. }
  613. showOutput();
  614. }
  615.  
  616. function updateAlchemyAction(action) {
  617. if ((!lastAction) || (lastAction.id != action.id)) {//新动作,重置统计信息
  618. lastAction = action;
  619. currentOutput = {};
  620. currentInput = {};
  621. alchemyStartTime = Date.now();//重置开始时间
  622. }
  623. showOutput();
  624. }
  625. function calcChestPrice(itemHrid) {
  626. let total = 0;
  627. getOpenableItems(itemHrid).forEach(openItem => {
  628. total += getPrice(openItem.itemHrid).bid * openItem.count;
  629. });
  630. return total;
  631. }
  632. function calcPrice(items) {
  633. let total = 0;
  634. for (let item of items) {
  635.  
  636. if (item.itemHrid === "/items/task_crystal") {//任务水晶有问题,暂时不计算
  637. }
  638. else if (getItemDataByHrid(item.itemHrid)?.categoryHrid === "/item_categories/loot") {
  639. total += calcChestPrice(item.itemHrid) * item.count;
  640. } else {
  641. total += getPrice(item.itemHrid, item.enhancementLevel ?? 0).ask * item.count;//买入材料价格*数量
  642. }
  643.  
  644. }
  645. return total;
  646. }
  647. function itemHashToItem(itemHash) {
  648. let item = {};
  649. let arr = itemHash.split("::");
  650. item.itemHrid = arr[2];
  651. item.enhancementLevel = arr[3];
  652. return item;
  653. }
  654. function getItemNameByHrid(itemHrid) {
  655. return mwi.isZh ?
  656. mwi.lang.zh.translation.itemNames[itemHrid] : mwi.lang.en.translation.itemNames[itemHrid];
  657. }
  658. function secondsToHms(seconds) {
  659. seconds = Number(seconds);
  660. const h = Math.floor(seconds / 3600);
  661. const m = Math.floor((seconds % 3600) / 60);
  662. const s = Math.floor(seconds % 60);
  663.  
  664. return [
  665. h.toString().padStart(2, '0'),
  666. m.toString().padStart(2, '0'),
  667. s.toString().padStart(2, '0')
  668. ].join(':');
  669. }
  670. function showOutput() {
  671. let alchemyContainer = document.querySelector(".SkillActionDetail_alchemyComponent__1J55d");
  672. if (!alchemyContainer) return;
  673.  
  674. if (!document.querySelector("#alchemoo_result")) {
  675. let outputContainer = document.createElement("div");
  676. outputContainer.id = "alchemoo_result";
  677. outputContainer.style.fontSize = "13px";
  678. outputContainer.style.lineHeight = "16px";
  679. outputContainer.style.maxWidth = "220px";
  680. outputContainer.innerHTML = `
  681. <div id="alchemoo_title" style="font-weight: bold; margin-bottom: 10px; text-align: center; color: var(--color-space-300);">${mwi.isZh ? "炼金统计" : "Alchemy Result"}</div>
  682. <div id="alchemoo_cost" style="display: flex; flex-wrap: wrap; gap: 4px;"></div>
  683. <div id="alchemoo_rate"></div>
  684. <div id="alchemoo_output" style="display: flex; flex-wrap: wrap; gap: 4px;"></div>
  685. <div id="alchemoo_essence"></div>
  686. <div id="alchemoo_rare"></div>
  687. <div id="alchemoo_exp"></div>
  688. <div id="alchemoo_time"></div>
  689. <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>
  690. `;
  691. outputContainer.style.flex = "0 0 auto";
  692. alchemyContainer.appendChild(outputContainer);
  693. }
  694. "💰"
  695.  
  696. let cost = calcPrice(Object.entries(currentInput).map(
  697. ([itemHash, count]) => {
  698. let arr = itemHash.split("::");
  699. return { "itemHrid": arr[2], "enhancementLevel": parseInt(arr[3]), "count": count }
  700. })
  701. );
  702. let gain = calcPrice(Object.entries(currentOutput).map(
  703. ([itemHash, count]) => {
  704. let arr = itemHash.split("::");
  705. return { "itemHrid": arr[2], "enhancementLevel": parseInt(arr[3]), "count": count }
  706. })
  707. );
  708. if (alchemyIndex == 0 && mwi.character?.gameMode === "ironcow") { cost = 0 };//铁牛点金,不计算成本
  709. let total = cost + gain;
  710.  
  711. let text = "";
  712. //消耗
  713. Object.entries(currentInput).forEach(([itemHash, count]) => {
  714. let item = itemHashToItem(itemHash);
  715. let price = getPrice(item.itemHrid);
  716. text += `
  717. <div title="price:${price.ask}/${price.bid}" style="display: inline-flex;border:1px solid var(--color-space-300);border-radius:4px;padding:1px 5px;">
  718. <svg width="14px" height="14px" style="display:inline-block"><use href="/static/media/items_sprite.6d12eb9d.svg#${item.itemHrid.replace("/items/", "")}"></use></svg>
  719. <span style="display:inline-block">${getItemNameByHrid(item.itemHrid)}</span>
  720. <span style="color:red;display:inline-block;font-size:14px;">${showNumber(count).replace("-", "*")}</span>
  721. </div>
  722. `;
  723. });
  724. if (cost > 0) {//0不显示
  725. 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>`;
  726. }
  727. document.querySelector("#alchemoo_cost").innerHTML = text;
  728.  
  729. document.querySelector("#alchemoo_rate").innerHTML = `<br/>`;//成功率
  730.  
  731. text = "";
  732. Object.entries(currentOutput).forEach(([itemHash, count]) => {
  733. let item = itemHashToItem(itemHash);
  734. let price = getPrice(item.itemHrid);
  735. text += `
  736. <div title="price:${price.ask}/${price.bid}" style="display: inline-flex;border:1px solid var(--color-space-300);border-radius:4px;padding:1px 5px;">
  737. <svg width="14px" height="14px" style="display:inline-block"><use href="/static/media/items_sprite.6d12eb9d.svg#${item.itemHrid.replace("/items/", "")}"></use></svg>
  738. <span style="display:inline-block">${getItemNameByHrid(item.itemHrid)}</span>
  739. <span style="color:lime;display:inline-block;font-size:14px;">${showNumber(count).replace("+", "*")}</span>
  740. </div>
  741. `;
  742. });
  743. if (gain > 0) {//0不显示
  744. 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>`;
  745. }
  746. document.querySelector("#alchemoo_output").innerHTML = text;//产出
  747.  
  748. //document.querySelector("#alchemoo_essence").innerHTML = `<br/>`;//精华
  749. //document.querySelector("#alchemoo_rare").innerHTML = `<br/>`;//稀有
  750. document.querySelector("#alchemoo_exp").innerHTML = `<br/>`;//经验
  751. let time = (Date.now() - alchemyStartTime) / 1000;
  752. //document.querySelector("#alchemoo_time").innerHTML = `<span>耗时:${secondsToHms(time)}</span>`;//时间
  753. let perDay = (86400 / time) * total;
  754.  
  755. let profitPerDay = predictPerDay[alchemyIndex] || 0;
  756. document.querySelector("#alchemoo_total").innerHTML =
  757. `
  758. <span>${mwi.isZh ? "耗时" : "Time Elapsed"}:${secondsToHms(time)}</span>
  759. <div>${mwi.isZh ? "累计收益" : "Gain"}:<span style="color:${total > 0 ? "lime" : "red"}">${showNumber(total)}</span></div>
  760. <div>${mwi.isZh ? "每日收益" : "Daily"}:<span style="color:${perDay > profitPerDay ? "lime" : "red"}">${showNumber(total * (86400 / time)).replace("+", "")}</span></div>
  761. `;//总收益
  762. }
  763. //mwi.hookMessage("action_completed", countAlchemyOutput);
  764. //mwi.hookMessage("action_updated", updateAlchemyAction)
  765. })();