HeroWarsHelper

Automation of actions for the game Hero Wars

目前为 2025-03-10 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @name:ru HeroWarsHelper
  5. // @namespace HeroWarsHelper
  6. // @version 2.325
  7. // @description Automation of actions for the game Hero Wars
  8. // @description:en Automation of actions for the game Hero Wars
  9. // @description:ru Автоматизация действий для игры Хроники Хаоса
  10. // @author ZingerY
  11. // @license Copyright ZingerY
  12. // @homepage https://zingery.ru/scripts/HeroWarsHelper.user.js
  13. // @icon https://zingery.ru/scripts/VaultBoyIco16.ico
  14. // @icon64 https://zingery.ru/scripts/VaultBoyIco64.png
  15. // @match https://www.hero-wars.com/*
  16. // @match https://apps-1701433570146040.apps.fbsbx.com/*
  17. // @run-at document-start
  18. // ==/UserScript==
  19.  
  20. (function() {
  21. /**
  22. * Start script
  23. *
  24. * Стартуем скрипт
  25. */
  26. console.log('%cStart ' + GM_info.script.name + ', v' + GM_info.script.version + ' by ' + GM_info.script.author, 'color: red');
  27. /**
  28. * Script info
  29. *
  30. * Информация о скрипте
  31. */
  32. this.scriptInfo = (({name, version, author, homepage, lastModified}, updateUrl) =>
  33. ({name, version, author, homepage, lastModified, updateUrl}))
  34. (GM_info.script, GM_info.scriptUpdateURL);
  35. this.GM_info = GM_info;
  36. /**
  37. * Information for completing daily quests
  38. *
  39. * Информация для выполнения ежендевных квестов
  40. */
  41. const questsInfo = {};
  42. /**
  43. * Is the game data loaded
  44. *
  45. * Загружены ли данные игры
  46. */
  47. let isLoadGame = false;
  48. /**
  49. * Headers of the last request
  50. *
  51. * Заголовки последнего запроса
  52. */
  53. let lastHeaders = {};
  54. /**
  55. * Information about sent gifts
  56. *
  57. * Информация об отправленных подарках
  58. */
  59. let freebieCheckInfo = null;
  60. /**
  61. * missionTimer
  62. *
  63. * missionTimer
  64. */
  65. let missionBattle = null;
  66. /**
  67. * User data
  68. *
  69. * Данные пользователя
  70. */
  71. let userInfo;
  72. this.isTimeBetweenNewDays = function () {
  73. if (userInfo.timeZone <= 3) {
  74. return false;
  75. }
  76. const nextDayTs = new Date(userInfo.nextDayTs * 1e3);
  77. const nextServerDayTs = new Date(userInfo.nextServerDayTs * 1e3);
  78. if (nextDayTs > nextServerDayTs) {
  79. nextDayTs.setDate(nextDayTs.getDate() - 1);
  80. }
  81. const now = Date.now();
  82. if (now > nextDayTs && now < nextServerDayTs) {
  83. return true;
  84. }
  85. return false;
  86. };
  87.  
  88. function getUserInfo() {
  89. return userInfo;
  90. }
  91. /**
  92. * Original methods for working with AJAX
  93. *
  94. * Оригинальные методы для работы с AJAX
  95. */
  96. const original = {
  97. open: XMLHttpRequest.prototype.open,
  98. send: XMLHttpRequest.prototype.send,
  99. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  100. SendWebSocket: WebSocket.prototype.send,
  101. fetch: fetch,
  102. };
  103.  
  104. // Sentry blocking
  105. // Блокировка наблюдателя
  106. this.fetch = function (url, options) {
  107. /**
  108. * Checking URL for blocking
  109. * Проверяем URL на блокировку
  110. */
  111. if (url.includes('sentry.io')) {
  112. console.log('%cFetch blocked', 'color: red');
  113. console.log(url, options);
  114. const body = {
  115. id: md5(Date.now()),
  116. };
  117. let info = {};
  118. try {
  119. info = JSON.parse(options.body);
  120. } catch (e) {}
  121. if (info.event_id) {
  122. body.id = info.event_id;
  123. }
  124. /**
  125. * Mock response for blocked URL
  126. *
  127. * Мокаем ответ для заблокированного URL
  128. */
  129. const mockResponse = new Response('Custom blocked response', {
  130. status: 200,
  131. headers: { 'Content-Type': 'application/json' },
  132. body,
  133. });
  134. return Promise.resolve(mockResponse);
  135. } else {
  136. /**
  137. * Call the original fetch function for all other URLs
  138. * Вызываем оригинальную функцию fetch для всех других URL
  139. */
  140. return original.fetch.apply(this, arguments);
  141. }
  142. };
  143.  
  144. /**
  145. * Decoder for converting byte data to JSON string
  146. *
  147. * Декодер для перобразования байтовых данных в JSON строку
  148. */
  149. const decoder = new TextDecoder("utf-8");
  150. /**
  151. * Stores a history of requests
  152. *
  153. * Хранит историю запросов
  154. */
  155. let requestHistory = {};
  156. /**
  157. * URL for API requests
  158. *
  159. * URL для запросов к API
  160. */
  161. let apiUrl = '';
  162.  
  163. /**
  164. * Connecting to the game code
  165. *
  166. * Подключение к коду игры
  167. */
  168. this.cheats = new hackGame();
  169. /**
  170. * The function of calculating the results of the battle
  171. *
  172. * Функция расчета результатов боя
  173. */
  174. this.BattleCalc = cheats.BattleCalc;
  175. /**
  176. * Sending a request available through the console
  177. *
  178. * Отправка запроса доступная через консоль
  179. */
  180. this.SendRequest = send;
  181. /**
  182. * Simple combat calculation available through the console
  183. *
  184. * Простой расчет боя доступный через консоль
  185. */
  186. this.Calc = function (data) {
  187. const type = getBattleType(data?.type);
  188. return new Promise((resolve, reject) => {
  189. try {
  190. BattleCalc(data, type, resolve);
  191. } catch (e) {
  192. reject(e);
  193. }
  194. })
  195. }
  196. /**
  197. * Short asynchronous request
  198. * Usage example (returns information about a character):
  199. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  200. *
  201. * Короткий асинхронный запрос
  202. * Пример использования (возвращает информацию о персонаже):
  203. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  204. */
  205. this.Send = function (json, pr) {
  206. return new Promise((resolve, reject) => {
  207. try {
  208. send(json, resolve, pr);
  209. } catch (e) {
  210. reject(e);
  211. }
  212. })
  213. }
  214.  
  215. this.xyz = (({ name, version, author }) => ({ name, version, author }))(GM_info.script);
  216. const i18nLangData = {
  217. /* English translation by BaBa */
  218. en: {
  219. /* Checkboxes */
  220. SKIP_FIGHTS: 'Skip battle',
  221. SKIP_FIGHTS_TITLE: 'Skip battle in Outland and the arena of the titans, auto-pass in the tower and campaign',
  222. ENDLESS_CARDS: 'Infinite cards',
  223. ENDLESS_CARDS_TITLE: 'Disable Divination Cards wasting',
  224. AUTO_EXPEDITION: 'Auto Expedition',
  225. AUTO_EXPEDITION_TITLE: 'Auto-sending expeditions',
  226. CANCEL_FIGHT: 'Cancel battle',
  227. CANCEL_FIGHT_TITLE: 'Ability to cancel manual combat on GW, CoW and Asgard',
  228. GIFTS: 'Gifts',
  229. GIFTS_TITLE: 'Collect gifts automatically',
  230. BATTLE_RECALCULATION: 'Battle recalculation',
  231. BATTLE_RECALCULATION_TITLE: 'Preliminary calculation of the battle',
  232. QUANTITY_CONTROL: 'Quantity control',
  233. QUANTITY_CONTROL_TITLE: 'Ability to specify the number of opened "lootboxes"',
  234. REPEAT_CAMPAIGN: 'Repeat missions',
  235. REPEAT_CAMPAIGN_TITLE: 'Auto-repeat battles in the campaign',
  236. DISABLE_DONAT: 'Disable donation',
  237. DISABLE_DONAT_TITLE: 'Removes all donation offers',
  238. DAILY_QUESTS: 'Quests',
  239. DAILY_QUESTS_TITLE: 'Complete daily quests',
  240. AUTO_QUIZ: 'AutoQuiz',
  241. AUTO_QUIZ_TITLE: 'Automatically receive correct answers to quiz questions',
  242. SECRET_WEALTH_CHECKBOX: 'Automatic purchase in the store "Secret Wealth" when entering the game',
  243. HIDE_SERVERS: 'Collapse servers',
  244. HIDE_SERVERS_TITLE: 'Hide unused servers',
  245. /* Input fields */
  246. HOW_MUCH_TITANITE: 'How much titanite to farm',
  247. COMBAT_SPEED: 'Combat Speed Multiplier',
  248. NUMBER_OF_TEST: 'Number of test fights',
  249. NUMBER_OF_AUTO_BATTLE: 'Number of auto-battle attempts',
  250. /* Buttons */
  251. RUN_SCRIPT: 'Run the',
  252. TO_DO_EVERYTHING: 'Do All',
  253. TO_DO_EVERYTHING_TITLE: 'Perform multiple actions of your choice',
  254. OUTLAND: 'Outland',
  255. OUTLAND_TITLE: 'Collect Outland',
  256. TITAN_ARENA: 'ToE',
  257. TITAN_ARENA_TITLE: 'Complete the titan arena',
  258. DUNGEON: 'Dungeon',
  259. DUNGEON_TITLE: 'Go through the dungeon',
  260. SEER: 'Seer',
  261. SEER_TITLE: 'Roll the Seer',
  262. TOWER: 'Tower',
  263. TOWER_TITLE: 'Pass the tower',
  264. EXPEDITIONS: 'Expeditions',
  265. EXPEDITIONS_TITLE: 'Sending and collecting expeditions',
  266. SYNC: 'Sync',
  267. SYNC_TITLE: 'Partial synchronization of game data without reloading the page',
  268. ARCHDEMON: 'Archdemon',
  269. FURNACE_OF_SOULS: 'Furnace of souls',
  270. ARCHDEMON_TITLE: 'Hitting kills and collecting rewards',
  271. ESTER_EGGS: 'Easter eggs',
  272. ESTER_EGGS_TITLE: 'Collect all Easter eggs or rewards',
  273. REWARDS: 'Rewards',
  274. REWARDS_TITLE: 'Collect all quest rewards',
  275. MAIL: 'Mail',
  276. MAIL_TITLE: 'Collect all mail, except letters with energy and charges of the portal',
  277. MINIONS: 'Minions',
  278. MINIONS_TITLE: 'Attack minions with saved packs',
  279. ADVENTURE: 'Adv.',
  280. ADVENTURE_TITLE: 'Passes the adventure along the specified route',
  281. STORM: 'Storm',
  282. STORM_TITLE: 'Passes the Storm along the specified route',
  283. SANCTUARY: 'Sanctuary',
  284. SANCTUARY_TITLE: 'Fast travel to Sanctuary',
  285. GUILD_WAR: 'Guild War',
  286. GUILD_WAR_TITLE: 'Fast travel to Guild War',
  287. SECRET_WEALTH: 'Secret Wealth',
  288. SECRET_WEALTH_TITLE: 'Buy something in the store "Secret Wealth"',
  289. /* Misc */
  290. BOTTOM_URLS:
  291. '<a href="https://t.me/+0oMwICyV1aQ1MDAy" target="_blank" title="Telegram"><svg width="20" height="20" style="margin:2px" viewBox="0 0 1e3 1e3" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="a" x1="50%" x2="50%" y2="99.258%"><stop stop-color="#2AABEE" offset="0"/><stop stop-color="#229ED9" offset="1"/></linearGradient></defs><g fill-rule="evenodd"><circle cx="500" cy="500" r="500" fill="url(#a)"/><path d="m226.33 494.72c145.76-63.505 242.96-105.37 291.59-125.6 138.86-57.755 167.71-67.787 186.51-68.119 4.1362-0.072862 13.384 0.95221 19.375 5.8132 5.0584 4.1045 6.4501 9.6491 7.1161 13.541 0.666 3.8915 1.4953 12.756 0.83608 19.683-7.5246 79.062-40.084 270.92-56.648 359.47-7.0089 37.469-20.81 50.032-34.17 51.262-29.036 2.6719-51.085-19.189-79.207-37.624-44.007-28.847-68.867-46.804-111.58-74.953-49.366-32.531-17.364-50.411 10.769-79.631 7.3626-7.6471 135.3-124.01 137.77-134.57 0.30968-1.3202 0.59708-6.2414-2.3265-8.8399s-7.2385-1.7099-10.352-1.0032c-4.4137 1.0017-74.715 47.468-210.9 139.4-19.955 13.702-38.029 20.379-54.223 20.029-17.853-0.3857-52.194-10.094-77.723-18.393-31.313-10.178-56.199-15.56-54.032-32.846 1.1287-9.0037 13.528-18.212 37.197-27.624z" fill="#fff"/></g></svg></a><a href="https://www.patreon.com/HeroWarsUserScripts" target="_blank" title="Patreon"><svg width="20" height="20" viewBox="0 0 1080 1080" xmlns="http://www.w3.org/2000/svg"><g fill="#FFF" stroke="None"><path d="m1033 324.45c-0.19-137.9-107.59-250.92-233.6-291.7-156.48-50.64-362.86-43.3-512.28 27.2-181.1 85.46-237.99 272.66-240.11 459.36-1.74 153.5 13.58 557.79 241.62 560.67 169.44 2.15 194.67-216.18 273.07-321.33 55.78-74.81 127.6-95.94 216.01-117.82 151.95-37.61 255.51-157.53 255.29-316.38z"/></g></svg></a>',
  292. GIFTS_SENT: 'Gifts sent!',
  293. DO_YOU_WANT: 'Do you really want to do this?',
  294. BTN_RUN: 'Run',
  295. BTN_CANCEL: 'Cancel',
  296. BTN_ACCEPT: 'Accept',
  297. BTN_OK: 'OK',
  298. MSG_HAVE_BEEN_DEFEATED: 'You have been defeated!',
  299. BTN_AUTO: 'Auto',
  300. MSG_YOU_APPLIED: 'You applied',
  301. MSG_DAMAGE: 'damage',
  302. MSG_CANCEL_AND_STAT: 'Auto (F5) and show statistic',
  303. MSG_REPEAT_MISSION: 'Repeat the mission?',
  304. BTN_REPEAT: 'Repeat',
  305. BTN_NO: 'No',
  306. MSG_SPECIFY_QUANT: 'Specify Quantity:',
  307. BTN_OPEN: 'Open',
  308. QUESTION_COPY: 'Question copied to clipboard',
  309. ANSWER_KNOWN: 'The answer is known',
  310. ANSWER_NOT_KNOWN: 'ATTENTION THE ANSWER IS NOT KNOWN',
  311. BEING_RECALC: 'The battle is being recalculated',
  312. THIS_TIME: 'This time',
  313. VICTORY: '<span style="color:green;">VICTORY</span>',
  314. DEFEAT: '<span style="color:red;">DEFEAT</span>',
  315. CHANCE_TO_WIN: 'Chance to win <span style="color: red;">based on pre-calculation</span>',
  316. OPEN_DOLLS: 'nesting dolls recursively',
  317. SENT_QUESTION: 'Question sent',
  318. SETTINGS: 'Settings',
  319. MSG_BAN_ATTENTION: '<p style="color:red;">Using this feature may result in a ban.</p> Continue?',
  320. BTN_YES_I_AGREE: 'Yes, I understand the risks!',
  321. BTN_NO_I_AM_AGAINST: 'No, I refuse it!',
  322. VALUES: 'Values',
  323. EXPEDITIONS_SENT: 'Expeditions:<br>Collected: {countGet}<br>Sent: {countSend}',
  324. EXPEDITIONS_NOTHING: 'Nothing to collect/send',
  325. EXPEDITIONS_NOTTIME: 'It is not time for expeditions',
  326. TITANIT: 'Titanit',
  327. COMPLETED: 'completed',
  328. FLOOR: 'Floor',
  329. LEVEL: 'Level',
  330. BATTLES: 'battles',
  331. EVENT: 'Event',
  332. NOT_AVAILABLE: 'not available',
  333. NO_HEROES: 'No heroes',
  334. DAMAGE_AMOUNT: 'Damage amount',
  335. NOTHING_TO_COLLECT: 'Nothing to collect',
  336. COLLECTED: 'Collected',
  337. REWARD: 'rewards',
  338. REMAINING_ATTEMPTS: 'Remaining attempts',
  339. BATTLES_CANCELED: 'Battles canceled',
  340. MINION_RAID: 'Minion Raid',
  341. STOPPED: 'Stopped',
  342. REPETITIONS: 'Repetitions',
  343. MISSIONS_PASSED: 'Missions passed',
  344. STOP: 'stop',
  345. TOTAL_OPEN: 'Total open',
  346. OPEN: 'Open',
  347. ROUND_STAT: 'Damage statistics for ',
  348. BATTLE: 'battles',
  349. MINIMUM: 'Minimum',
  350. MAXIMUM: 'Maximum',
  351. AVERAGE: 'Average',
  352. NOT_THIS_TIME: 'Not this time',
  353. RETRY_LIMIT_EXCEEDED: 'Retry limit exceeded',
  354. SUCCESS: 'Success',
  355. RECEIVED: 'Received',
  356. LETTERS: 'letters',
  357. PORTALS: 'portals',
  358. ATTEMPTS: 'attempts',
  359. /* Quests */
  360. QUEST_10001: 'Upgrade the skills of heroes 3 times',
  361. QUEST_10002: 'Complete 10 missions',
  362. QUEST_10003: 'Complete 3 heroic missions',
  363. QUEST_10004: 'Fight 3 times in the Arena or Grand Arena',
  364. QUEST_10006: 'Use the exchange of emeralds 1 time',
  365. QUEST_10007: 'Perform 1 summon in the Solu Atrium',
  366. QUEST_10016: 'Send gifts to guildmates',
  367. QUEST_10018: 'Use an experience potion',
  368. QUEST_10019: 'Open 1 chest in the Tower',
  369. QUEST_10020: 'Open 3 chests in Outland',
  370. QUEST_10021: 'Collect 75 Titanite in the Guild Dungeon',
  371. QUEST_10021: 'Collect 150 Titanite in the Guild Dungeon',
  372. QUEST_10023: 'Upgrade Gift of the Elements by 1 level',
  373. QUEST_10024: 'Level up any artifact once',
  374. QUEST_10025: 'Start Expedition 1',
  375. QUEST_10026: 'Start 4 Expeditions',
  376. QUEST_10027: 'Win 1 battle of the Tournament of Elements',
  377. QUEST_10028: 'Level up any titan artifact',
  378. QUEST_10029: 'Unlock the Orb of Titan Artifacts',
  379. QUEST_10030: 'Upgrade any Skin of any hero 1 time',
  380. QUEST_10031: 'Win 6 battles of the Tournament of Elements',
  381. QUEST_10043: 'Start or Join an Adventure',
  382. QUEST_10044: 'Use Summon Pets 1 time',
  383. QUEST_10046: 'Open 3 chests in Adventure',
  384. QUEST_10047: 'Get 150 Guild Activity Points',
  385. NOTHING_TO_DO: 'Nothing to do',
  386. YOU_CAN_COMPLETE: 'You can complete quests',
  387. BTN_DO_IT: 'Do it',
  388. NOT_QUEST_COMPLETED: 'Not a single quest completed',
  389. COMPLETED_QUESTS: 'Completed quests',
  390. /* everything button */
  391. ASSEMBLE_OUTLAND: 'Assemble Outland',
  392. PASS_THE_TOWER: 'Pass the tower',
  393. CHECK_EXPEDITIONS: 'Check Expeditions',
  394. COMPLETE_TOE: 'Complete ToE',
  395. COMPLETE_DUNGEON: 'Complete the dungeon',
  396. COLLECT_MAIL: 'Collect mail',
  397. COLLECT_MISC: 'Collect some bullshit',
  398. COLLECT_MISC_TITLE: 'Collect Easter Eggs, Skin Gems, Keys, Arena Coins and Soul Crystal',
  399. COLLECT_QUEST_REWARDS: 'Collect quest rewards',
  400. MAKE_A_SYNC: 'Make a sync',
  401.  
  402. RUN_FUNCTION: 'Run the following functions?',
  403. BTN_GO: 'Go!',
  404. PERFORMED: 'Performed',
  405. DONE: 'Done',
  406. ERRORS_OCCURRES: 'Errors occurred while executing',
  407. COPY_ERROR: 'Copy error information to clipboard',
  408. BTN_YES: 'Yes',
  409. ALL_TASK_COMPLETED: 'All tasks completed',
  410.  
  411. UNKNOWN: 'unknown',
  412. ENTER_THE_PATH: 'Enter the path of adventure using commas or dashes',
  413. START_ADVENTURE: 'Start your adventure along this path!',
  414. INCORRECT_WAY: 'Incorrect path in adventure: {from} -> {to}',
  415. BTN_CANCELED: 'Canceled',
  416. MUST_TWO_POINTS: 'The path must contain at least 2 points.',
  417. MUST_ONLY_NUMBERS: 'The path must contain only numbers and commas',
  418. NOT_ON_AN_ADVENTURE: 'You are not on an adventure',
  419. YOU_IN_NOT_ON_THE_WAY: 'Your location is not on the way',
  420. ATTEMPTS_NOT_ENOUGH: 'Your attempts are not enough to complete the path, continue?',
  421. YES_CONTINUE: 'Yes, continue!',
  422. NOT_ENOUGH_AP: 'Not enough action points',
  423. ATTEMPTS_ARE_OVER: 'The attempts are over',
  424. MOVES: 'Moves',
  425. BUFF_GET_ERROR: 'Buff getting error',
  426. BATTLE_END_ERROR: 'Battle end error',
  427. AUTOBOT: 'Autobot',
  428. FAILED_TO_WIN_AUTO: 'Failed to win the auto battle',
  429. ERROR_OF_THE_BATTLE_COPY: 'An error occurred during the passage of the battle<br>Copy the error to the clipboard?',
  430. ERROR_DURING_THE_BATTLE: 'Error during the battle',
  431. NO_CHANCE_WIN: 'No chance of winning this fight: 0/',
  432. LOST_HEROES: 'You have won, but you have lost one or several heroes',
  433. VICTORY_IMPOSSIBLE: 'Is victory impossible, should we focus on the result?',
  434. FIND_COEFF: 'Find the coefficient greater than',
  435. BTN_PASS: 'PASS',
  436. BRAWLS: 'Brawls',
  437. BRAWLS_TITLE: 'Activates the ability to auto-brawl',
  438. START_AUTO_BRAWLS: 'Start Auto Brawls?',
  439. LOSSES: 'Losses',
  440. WINS: 'Wins',
  441. FIGHTS: 'Fights',
  442. STAGE: 'Stage',
  443. DONT_HAVE_LIVES: "You don't have lives",
  444. LIVES: 'Lives',
  445. SECRET_WEALTH_ALREADY: 'Item for Pet Potions already purchased',
  446. SECRET_WEALTH_NOT_ENOUGH: 'Not Enough Pet Potion, You Have {available}, Need {need}',
  447. SECRET_WEALTH_UPGRADE_NEW_PET: 'After purchasing the Pet Potion, it will not be enough to upgrade a new pet',
  448. SECRET_WEALTH_PURCHASED: 'Purchased {count} {name}',
  449. SECRET_WEALTH_CANCELED: 'Secret Wealth: Purchase Canceled',
  450. SECRET_WEALTH_BUY: 'You have {available} Pet Potion.<br>Do you want to buy {countBuy} {name} for {price} Pet Potion?',
  451. DAILY_BONUS: 'Daily bonus',
  452. DO_DAILY_QUESTS: 'Do daily quests',
  453. ACTIONS: 'Actions',
  454. ACTIONS_TITLE: 'Dialog box with various actions',
  455. OTHERS: 'Others',
  456. OTHERS_TITLE: 'Others',
  457. CHOOSE_ACTION: 'Choose an action',
  458. OPEN_LOOTBOX: 'You have {lootBox} boxes, should we open them?',
  459. STAMINA: 'Energy',
  460. BOXES_OVER: 'The boxes are over',
  461. NO_BOXES: 'No boxes',
  462. NO_MORE_ACTIVITY: 'No more activity for items today',
  463. EXCHANGE_ITEMS: 'Exchange items for activity points (max {maxActive})?',
  464. GET_ACTIVITY: 'Get Activity',
  465. NOT_ENOUGH_ITEMS: 'Not enough items',
  466. ACTIVITY_RECEIVED: 'Activity received',
  467. NO_PURCHASABLE_HERO_SOULS: 'No purchasable Hero Souls',
  468. PURCHASED_HERO_SOULS: 'Purchased {countHeroSouls} Hero Souls',
  469. NOT_ENOUGH_EMERALDS_540: 'Not enough emeralds, you need {imgEmerald}540 you have {imgEmerald}{currentStarMoney}',
  470. BUY_OUTLAND_BTN: 'Buy {count} chests {imgEmerald}{countEmerald}',
  471. CHESTS_NOT_AVAILABLE: 'Chests not available',
  472. OUTLAND_CHESTS_RECEIVED: 'Outland chests received',
  473. RAID_NOT_AVAILABLE: 'The raid is not available or there are no spheres',
  474. RAID_ADVENTURE: 'Raid {adventureId} adventure!',
  475. SOMETHING_WENT_WRONG: 'Something went wrong',
  476. ADVENTURE_COMPLETED: 'Adventure {adventureId} completed {times} times',
  477. CLAN_STAT_COPY: 'Clan statistics copied to clipboard',
  478. GET_ENERGY: 'Get Energy',
  479. GET_ENERGY_TITLE: 'Opens platinum boxes one at a time until you get 250 energy',
  480. ITEM_EXCHANGE: 'Item Exchange',
  481. ITEM_EXCHANGE_TITLE: 'Exchanges items for the specified amount of activity',
  482. BUY_SOULS: 'Buy souls',
  483. BUY_SOULS_TITLE: 'Buy hero souls from all available shops',
  484. BUY_OUTLAND: 'Buy Outland',
  485. BUY_OUTLAND_TITLE: 'Buy 9 chests in Outland for 540 emeralds',
  486. RAID: 'Raid',
  487. AUTO_RAID_ADVENTURE: 'Raid',
  488. AUTO_RAID_ADVENTURE_TITLE: 'Raid adventure set number of times',
  489. CLAN_STAT: 'Clan statistics',
  490. CLAN_STAT_TITLE: 'Copies clan statistics to the clipboard',
  491. BTN_AUTO_F5: 'Auto (F5)',
  492. BOSS_DAMAGE: 'Boss Damage: ',
  493. NOTHING_BUY: 'Nothing to buy',
  494. LOTS_BOUGHT: '{countBuy} lots bought for gold',
  495. BUY_FOR_GOLD: 'Buy for gold',
  496. BUY_FOR_GOLD_TITLE: 'Buy items for gold in the Town Shop and in the Pet Soul Stone Shop',
  497. REWARDS_AND_MAIL: 'Rewards and Mail',
  498. REWARDS_AND_MAIL_TITLE: 'Collects rewards and mail',
  499. COLLECT_REWARDS_AND_MAIL: 'Collected {countQuests} rewards and {countMail} letters',
  500. TIMER_ALREADY: 'Timer already started {time}',
  501. NO_ATTEMPTS_TIMER_START: 'No attempts, timer started {time}',
  502. EPIC_BRAWL_RESULT: 'Wins: {wins}/{attempts}, Coins: {coins}, Streak: {progress}/{nextStage} [Close]{end}',
  503. ATTEMPT_ENDED: '<br>Attempts ended, timer started {time}',
  504. EPIC_BRAWL: 'Cosmic Battle',
  505. EPIC_BRAWL_TITLE: 'Spends attempts in the Cosmic Battle',
  506. RELOAD_GAME: 'Reload game',
  507. TIMER: 'Timer:',
  508. SHOW_ERRORS: 'Show errors',
  509. SHOW_ERRORS_TITLE: 'Show server request errors',
  510. ERROR_MSG: 'Error: {name}<br>{description}',
  511. EVENT_AUTO_BOSS:
  512. 'Maximum number of battles for calculation:</br>{length} ∗ {countTestBattle} = {maxCalcBattle}</br>If you have a weak computer, it may take a long time for this, click on the cross to cancel.</br>Should I search for the best pack from all or the first suitable one?',
  513. BEST_SLOW: 'Best (slower)',
  514. FIRST_FAST: 'First (faster)',
  515. FREEZE_INTERFACE: 'Calculating... <br>The interface may freeze.',
  516. ERROR_F12: 'Error, details in the console (F12)',
  517. FAILED_FIND_WIN_PACK: 'Failed to find a winning pack',
  518. BEST_PACK: 'Best pack:',
  519. BOSS_HAS_BEEN_DEF: 'Boss {bossLvl} has been defeated.',
  520. NOT_ENOUGH_ATTEMPTS_BOSS: 'Not enough attempts to defeat boss {bossLvl}, retry?',
  521. BOSS_VICTORY_IMPOSSIBLE:
  522. 'Based on the recalculation of {battles} battles, victory has not been achieved. Would you like to continue the search for a winning battle in real battles?',
  523. BOSS_HAS_BEEN_DEF_TEXT:
  524. 'Boss {bossLvl} defeated in<br>{countBattle}/{countMaxBattle} attempts{winTimer}<br>(Please synchronize or restart the game to update the data)',
  525. MAP: 'Map: ',
  526. PLAYER_POS: 'Player positions:',
  527. NY_GIFTS: 'Gifts',
  528. NY_GIFTS_TITLE: "Open all New Year's gifts",
  529. NY_NO_GIFTS: 'No gifts not received',
  530. NY_GIFTS_COLLECTED: '{count} gifts collected',
  531. CHANGE_MAP: 'Island map',
  532. CHANGE_MAP_TITLE: 'Change island map',
  533. SELECT_ISLAND_MAP: 'Select an island map:',
  534. MAP_NUM: 'Map {num}',
  535. SECRET_WEALTH_SHOP: 'Secret Wealth {name}: ',
  536. SHOPS: 'Shops',
  537. SHOPS_DEFAULT: 'Default',
  538. SHOPS_DEFAULT_TITLE: 'Default stores',
  539. SHOPS_LIST: 'Shops {number}',
  540. SHOPS_LIST_TITLE: 'List of shops {number}',
  541. SHOPS_WARNING:
  542. 'Stores<br><span style="color:red">If you buy brawl store coins for emeralds, you must use them immediately, otherwise they will disappear after restarting the game!</span>',
  543. MINIONS_WARNING: 'The hero packs for attacking minions are incomplete, should I continue?',
  544. FAST_SEASON: 'Fast season',
  545. FAST_SEASON_TITLE: 'Skip the map selection screen in a season',
  546. SET_NUMBER_LEVELS: 'Specify the number of levels:',
  547. POSSIBLE_IMPROVE_LEVELS: 'It is possible to improve only {count} levels.<br>Improving?',
  548. NOT_ENOUGH_RESOURECES: 'Not enough resources',
  549. IMPROVED_LEVELS: 'Improved levels: {count}',
  550. ARTIFACTS_UPGRADE: 'Artifacts Upgrade',
  551. ARTIFACTS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero artifacts',
  552. SKINS_UPGRADE: 'Skins Upgrade',
  553. SKINS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero skins',
  554. HINT: '<br>Hint: ',
  555. PICTURE: '<br>Picture: ',
  556. ANSWER: '<br>Answer: ',
  557. NO_HEROES_PACK: 'Fight at least one battle to save the attacking team',
  558. BRAWL_AUTO_PACK: 'Automatic selection of packs',
  559. BRAWL_AUTO_PACK_NOT_CUR_HERO: 'Automatic pack selection is not suitable for the current hero',
  560. BRAWL_DAILY_TASK_COMPLETED: 'Daily task completed, continue attacking?',
  561. CALC_STAT: 'Calculate statistics',
  562. ELEMENT_TOURNAMENT_REWARD: 'Unclaimed bonus for Elemental Tournament',
  563. BTN_TRY_FIX_IT: 'Fix it',
  564. BTN_TRY_FIX_IT_TITLE: 'Enable auto attack combat correction',
  565. DAMAGE_FIXED: 'Damage fixed from {lastDamage} to {maxDamage}!',
  566. DAMAGE_NO_FIXED: 'Failed to fix damage: {lastDamage}',
  567. LETS_FIX: "Let's fix",
  568. COUNT_FIXED: 'For {count} attempts',
  569. DEFEAT_TURN_TIMER: 'Defeat! Turn on the timer to complete the mission?',
  570. SEASON_REWARD: 'Season Rewards',
  571. SEASON_REWARD_TITLE: 'Collects available free rewards from all current seasons',
  572. SEASON_REWARD_COLLECTED: 'Collected {count} season rewards',
  573. SELL_HERO_SOULS: 'Sell ​​souls',
  574. SELL_HERO_SOULS_TITLE: 'Exchanges all absolute star hero souls for gold',
  575. GOLD_RECEIVED: 'Gold received: {gold}',
  576. OPEN_ALL_EQUIP_BOXES: 'Open all Equipment Fragment Box?',
  577. SERVER_NOT_ACCEPT: 'The server did not accept the result',
  578. INVASION_BOSS_BUFF: 'For {bossLvl} boss need buff {needBuff} you have {haveBuff}}',
  579. HERO_POWER: 'Hero Power',
  580. HERO_POWER_TITLE: 'Displays the current and maximum power of heroes',
  581. MAX_POWER_REACHED: 'Maximum power reached: {power}',
  582. CURRENT_POWER: 'Current power: {power}',
  583. POWER_TO_MAX: 'Power left to reach maximum: <span style="color:{color};">{power}</span><br>',
  584. BEST_RESULT: 'Best result: {value}%',
  585. GUILD_ISLAND_TITLE: 'Fast travel to Guild Island',
  586. TITAN_VALLEY_TITLE: 'Fast travel to Titan Valley',
  587. },
  588. ru: {
  589. /* Чекбоксы */
  590. SKIP_FIGHTS: 'Пропуск боев',
  591. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  592. ENDLESS_CARDS: 'Бесконечные карты',
  593. ENDLESS_CARDS_TITLE: 'Отключить трату карт предсказаний',
  594. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  595. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  596. CANCEL_FIGHT: 'Отмена боя',
  597. CANCEL_FIGHT_TITLE: 'Возможность отмены ручного боя на ВГ, СМ и в Асгарде',
  598. GIFTS: 'Подарки',
  599. GIFTS_TITLE: 'Собирать подарки автоматически',
  600. BATTLE_RECALCULATION: 'Прерасчет боя',
  601. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  602. QUANTITY_CONTROL: 'Контроль кол-ва',
  603. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  604. REPEAT_CAMPAIGN: 'Повтор в кампании',
  605. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  606. DISABLE_DONAT: 'Отключить донат',
  607. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  608. DAILY_QUESTS: 'Квесты',
  609. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  610. AUTO_QUIZ: 'АвтоВикторина',
  611. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  612. SECRET_WEALTH_CHECKBOX: 'Автоматическая покупка в магазине "Тайное Богатство" при заходе в игру',
  613. HIDE_SERVERS: 'Свернуть сервера',
  614. HIDE_SERVERS_TITLE: 'Скрывать неиспользуемые сервера',
  615. /* Поля ввода */
  616. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  617. COMBAT_SPEED: 'Множитель ускорения боя',
  618. NUMBER_OF_TEST: 'Количество тестовых боев',
  619. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  620. /* Кнопки */
  621. RUN_SCRIPT: 'Запустить скрипт',
  622. TO_DO_EVERYTHING: 'Сделать все',
  623. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  624. OUTLAND: 'Запределье',
  625. OUTLAND_TITLE: 'Собрать Запределье',
  626. TITAN_ARENA: 'Турн.Стихий',
  627. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  628. DUNGEON: 'Подземелье',
  629. DUNGEON_TITLE: 'Автопрохождение подземелья',
  630. SEER: 'Провидец',
  631. SEER_TITLE: 'Покрутить Провидца',
  632. TOWER: 'Башня',
  633. TOWER_TITLE: 'Автопрохождение башни',
  634. EXPEDITIONS: 'Экспедиции',
  635. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  636. SYNC: 'Синхронизация',
  637. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  638. ARCHDEMON: 'Архидемон',
  639. FURNACE_OF_SOULS: 'Горнило душ',
  640. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  641. ESTER_EGGS: 'Пасхалки',
  642. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  643. REWARDS: 'Награды',
  644. REWARDS_TITLE: 'Собрать все награды за задания',
  645. MAIL: 'Почта',
  646. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  647. MINIONS: 'Прислужники',
  648. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  649. ADVENTURE: 'Прикл',
  650. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  651. STORM: 'Буря',
  652. STORM_TITLE: 'Проходит бурю по указанному маршруту',
  653. SANCTUARY: 'Святилище',
  654. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  655. GUILD_WAR: 'Война гильдий',
  656. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  657. SECRET_WEALTH: 'Тайное богатство',
  658. SECRET_WEALTH_TITLE: 'Купить что-то в магазине "Тайное богатство"',
  659. /* Разное */
  660. BOTTOM_URLS:
  661. '<a href="https://t.me/+q6gAGCRpwyFkNTYy" target="_blank" title="Telegram"><svg width="20" height="20" style="margin:2px" viewBox="0 0 1e3 1e3" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="a" x1="50%" x2="50%" y2="99.258%"><stop stop-color="#2AABEE" offset="0"/><stop stop-color="#229ED9" offset="1"/></linearGradient></defs><g fill-rule="evenodd"><circle cx="500" cy="500" r="500" fill="url(#a)"/><path d="m226.33 494.72c145.76-63.505 242.96-105.37 291.59-125.6 138.86-57.755 167.71-67.787 186.51-68.119 4.1362-0.072862 13.384 0.95221 19.375 5.8132 5.0584 4.1045 6.4501 9.6491 7.1161 13.541 0.666 3.8915 1.4953 12.756 0.83608 19.683-7.5246 79.062-40.084 270.92-56.648 359.47-7.0089 37.469-20.81 50.032-34.17 51.262-29.036 2.6719-51.085-19.189-79.207-37.624-44.007-28.847-68.867-46.804-111.58-74.953-49.366-32.531-17.364-50.411 10.769-79.631 7.3626-7.6471 135.3-124.01 137.77-134.57 0.30968-1.3202 0.59708-6.2414-2.3265-8.8399s-7.2385-1.7099-10.352-1.0032c-4.4137 1.0017-74.715 47.468-210.9 139.4-19.955 13.702-38.029 20.379-54.223 20.029-17.853-0.3857-52.194-10.094-77.723-18.393-31.313-10.178-56.199-15.56-54.032-32.846 1.1287-9.0037 13.528-18.212 37.197-27.624z" fill="#fff"/></g></svg></a><a href="https://vk.com/invite/YNPxKGX" target="_blank" title="Вконтакте"><svg width="20" height="20" style="margin:2px" viewBox="0 0 101 100" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="M0.5 48C0.5 25.3726 0.5 14.0589 7.52944 7.02944C14.5589 0 25.8726 0 48.5 0H52.5C75.1274 0 86.4411 0 93.4706 7.02944C100.5 14.0589 100.5 25.3726 100.5 48V52C100.5 74.6274 100.5 85.9411 93.4706 92.9706C86.4411 100 75.1274 100 52.5 100H48.5C25.8726 100 14.5589 100 7.52944 92.9706C0.5 85.9411 0.5 74.6274 0.5 52V48Z" fill="#07f"/><path d="m53.708 72.042c-22.792 0-35.792-15.625-36.333-41.625h11.417c0.375 19.083 8.7915 27.167 15.458 28.833v-28.833h10.75v16.458c6.5833-0.7083 13.499-8.2082 15.832-16.458h10.75c-1.7917 10.167-9.2917 17.667-14.625 20.75 5.3333 2.5 13.875 9.0417 17.125 20.875h-11.834c-2.5417-7.9167-8.8745-14.042-17.25-14.875v14.875h-1.2919z" fill="#fff"/></g><defs><clipPath id="a"><rect transform="translate(.5)" width="100" height="100" fill="#fff"/></clipPath></defs></svg></a>',
  662. GIFTS_SENT: 'Подарки отправлены!',
  663. DO_YOU_WANT: 'Вы действительно хотите это сделать?',
  664. BTN_RUN: 'Запускай',
  665. BTN_CANCEL: 'Отмена',
  666. BTN_ACCEPT: 'Принять',
  667. BTN_OK: 'Ок',
  668. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  669. BTN_AUTO: 'Авто',
  670. MSG_YOU_APPLIED: 'Вы нанесли',
  671. MSG_DAMAGE: 'урона',
  672. MSG_CANCEL_AND_STAT: 'Авто (F5) и показать Статистику',
  673. MSG_REPEAT_MISSION: 'Повторить миссию?',
  674. BTN_REPEAT: 'Повторить',
  675. BTN_NO: 'Нет',
  676. MSG_SPECIFY_QUANT: 'Указать количество:',
  677. BTN_OPEN: 'Открыть',
  678. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  679. ANSWER_KNOWN: 'Ответ известен',
  680. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  681. BEING_RECALC: 'Идет прерасчет боя',
  682. THIS_TIME: 'На этот раз',
  683. VICTORY: '<span style="color:green;">ПОБЕДА</span>',
  684. DEFEAT: '<span style="color:red;">ПОРАЖЕНИЕ</span>',
  685. CHANCE_TO_WIN: 'Шансы на победу <span style="color:red;">на основе прерасчета</span>',
  686. OPEN_DOLLS: 'матрешек рекурсивно',
  687. SENT_QUESTION: 'Вопрос отправлен',
  688. SETTINGS: 'Настройки',
  689. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  690. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  691. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  692. VALUES: 'Значения',
  693. EXPEDITIONS_SENT: 'Экспедиции:<br>Собрано: {countGet}<br>Отправлено: {countSend}',
  694. EXPEDITIONS_NOTHING: 'Нечего собирать/отправлять',
  695. EXPEDITIONS_NOTTIME: 'Не время для экспедиций',
  696. TITANIT: 'Титанит',
  697. COMPLETED: 'завершено',
  698. FLOOR: 'Этаж',
  699. LEVEL: 'Уровень',
  700. BATTLES: 'бои',
  701. EVENT: 'Эвент',
  702. NOT_AVAILABLE: 'недоступен',
  703. NO_HEROES: 'Нет героев',
  704. DAMAGE_AMOUNT: 'Количество урона',
  705. NOTHING_TO_COLLECT: 'Нечего собирать',
  706. COLLECTED: 'Собрано',
  707. REWARD: 'наград',
  708. REMAINING_ATTEMPTS: 'Осталось попыток',
  709. BATTLES_CANCELED: 'Битв отменено',
  710. MINION_RAID: 'Рейд прислужников',
  711. STOPPED: 'Остановлено',
  712. REPETITIONS: 'Повторений',
  713. MISSIONS_PASSED: 'Миссий пройдено',
  714. STOP: 'остановить',
  715. TOTAL_OPEN: 'Всего открыто',
  716. OPEN: 'Открыто',
  717. ROUND_STAT: 'Статистика урона за',
  718. BATTLE: 'боев',
  719. MINIMUM: 'Минимальный',
  720. MAXIMUM: 'Максимальный',
  721. AVERAGE: 'Средний',
  722. NOT_THIS_TIME: 'Не в этот раз',
  723. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  724. SUCCESS: 'Успех',
  725. RECEIVED: 'Получено',
  726. LETTERS: 'писем',
  727. PORTALS: 'порталов',
  728. ATTEMPTS: 'попыток',
  729. QUEST_10001: 'Улучши умения героев 3 раза',
  730. QUEST_10002: 'Пройди 10 миссий',
  731. QUEST_10003: 'Пройди 3 героические миссии',
  732. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  733. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  734. QUEST_10007: 'Соверши 1 призыв в Атриуме Душ',
  735. QUEST_10016: 'Отправь подарки согильдийцам',
  736. QUEST_10018: 'Используй зелье опыта',
  737. QUEST_10019: 'Открой 1 сундук в Башне',
  738. QUEST_10020: 'Открой 3 сундука в Запределье',
  739. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  740. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  741. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  742. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  743. QUEST_10025: 'Начни 1 Экспедицию',
  744. QUEST_10026: 'Начни 4 Экспедиции',
  745. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  746. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  747. QUEST_10029: 'Открой сферу артефактов титанов',
  748. QUEST_10030: 'Улучши облик любого героя 1 раз',
  749. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  750. QUEST_10043: 'Начни или присоеденись к Приключению',
  751. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  752. QUEST_10046: 'Открой 3 сундука в Приключениях',
  753. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  754. NOTHING_TO_DO: 'Нечего выполнять',
  755. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  756. BTN_DO_IT: 'Выполняй',
  757. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполенно',
  758. COMPLETED_QUESTS: 'Выполнено квестов',
  759. /* everything button */
  760. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  761. PASS_THE_TOWER: 'Пройти башню',
  762. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  763. COMPLETE_TOE: 'Пройти Турнир Стихий',
  764. COMPLETE_DUNGEON: 'Пройти подземелье',
  765. COLLECT_MAIL: 'Собрать почту',
  766. COLLECT_MISC: 'Собрать всякую херню',
  767. COLLECT_MISC_TITLE: 'Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души',
  768. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  769. MAKE_A_SYNC: 'Сделать синхронизацию',
  770.  
  771. RUN_FUNCTION: 'Выполнить следующие функции?',
  772. BTN_GO: 'Погнали!',
  773. PERFORMED: 'Выполняется',
  774. DONE: 'Выполнено',
  775. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  776. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  777. BTN_YES: 'Да',
  778. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  779.  
  780. UNKNOWN: 'Неизвестно',
  781. ENTER_THE_PATH: 'Введите путь приключения через запятые или дефисы',
  782. START_ADVENTURE: 'Начать приключение по этому пути!',
  783. INCORRECT_WAY: 'Неверный путь в приключении: {from} -> {to}',
  784. BTN_CANCELED: 'Отменено',
  785. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  786. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  787. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  788. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  789. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  790. YES_CONTINUE: 'Да, продолжай!',
  791. NOT_ENOUGH_AP: 'Попыток не достаточно',
  792. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  793. MOVES: 'Ходы',
  794. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  795. BATTLE_END_ERROR: 'Ошибка завершения боя',
  796. AUTOBOT: 'АвтоБой',
  797. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  798. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  799. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  800. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  801. LOST_HEROES: 'Вы победили, но потеряли одного или несколько героев!',
  802. VICTORY_IMPOSSIBLE: 'Победа не возможна, бъем на результат?',
  803. FIND_COEFF: 'Поиск коэффициента больше чем',
  804. BTN_PASS: 'ПРОПУСК',
  805. BRAWLS: 'Потасовки',
  806. BRAWLS_TITLE: 'Включает возможность автопотасовок',
  807. START_AUTO_BRAWLS: 'Запустить Автопотасовки?',
  808. LOSSES: 'Поражений',
  809. WINS: 'Побед',
  810. FIGHTS: 'Боев',
  811. STAGE: 'Стадия',
  812. DONT_HAVE_LIVES: 'У Вас нет жизней',
  813. LIVES: 'Жизни',
  814. SECRET_WEALTH_ALREADY: 'товар за Зелья питомцев уже куплен',
  815. SECRET_WEALTH_NOT_ENOUGH: 'Не достаточно Зелье Питомца, у Вас {available}, нужно {need}',
  816. SECRET_WEALTH_UPGRADE_NEW_PET: 'После покупки Зелье Питомца будет не достаточно для прокачки нового питомца',
  817. SECRET_WEALTH_PURCHASED: 'Куплено {count} {name}',
  818. SECRET_WEALTH_CANCELED: 'Тайное богатство: покупка отменена',
  819. SECRET_WEALTH_BUY: 'У вас {available} Зелье Питомца.<br>Вы хотите купить {countBuy} {name} за {price} Зелье Питомца?',
  820. DAILY_BONUS: 'Ежедневная награда',
  821. DO_DAILY_QUESTS: 'Сделать ежедневные квесты',
  822. ACTIONS: 'Действия',
  823. ACTIONS_TITLE: 'Диалоговое окно с различными действиями',
  824. OTHERS: 'Разное',
  825. OTHERS_TITLE: 'Диалоговое окно с дополнительными различными действиями',
  826. CHOOSE_ACTION: 'Выберите действие',
  827. OPEN_LOOTBOX: 'У Вас {lootBox} ящиков, откываем?',
  828. STAMINA: 'Энергия',
  829. BOXES_OVER: 'Ящики закончились',
  830. NO_BOXES: 'Нет ящиков',
  831. NO_MORE_ACTIVITY: 'Больше активности за предметы сегодня не получить',
  832. EXCHANGE_ITEMS: 'Обменять предметы на очки активности (не более {maxActive})?',
  833. GET_ACTIVITY: 'Получить активность',
  834. NOT_ENOUGH_ITEMS: 'Предметов недостаточно',
  835. ACTIVITY_RECEIVED: 'Получено активности',
  836. NO_PURCHASABLE_HERO_SOULS: 'Нет доступных для покупки душ героев',
  837. PURCHASED_HERO_SOULS: 'Куплено {countHeroSouls} душ героев',
  838. NOT_ENOUGH_EMERALDS_540: 'Недостаточно изюма, нужно {imgEmerald}540 у Вас {imgEmerald}{currentStarMoney}',
  839. BUY_OUTLAND_BTN: 'Купить {count} сундуков {imgEmerald}{countEmerald}',
  840. CHESTS_NOT_AVAILABLE: 'Сундуки не доступны',
  841. OUTLAND_CHESTS_RECEIVED: 'Получено сундуков Запределья',
  842. RAID_NOT_AVAILABLE: 'Рейд не доступен или сфер нет',
  843. RAID_ADVENTURE: 'Рейд {adventureId} приключения!',
  844. SOMETHING_WENT_WRONG: 'Что-то пошло не так',
  845. ADVENTURE_COMPLETED: 'Приключение {adventureId} пройдено {times} раз',
  846. CLAN_STAT_COPY: 'Клановая статистика скопирована в буфер обмена',
  847. GET_ENERGY: 'Получить энергию',
  848. GET_ENERGY_TITLE: 'Открывает платиновые шкатулки по одной до получения 250 энергии',
  849. ITEM_EXCHANGE: 'Обмен предметов',
  850. ITEM_EXCHANGE_TITLE: 'Обменивает предметы на указанное количество активности',
  851. BUY_SOULS: 'Купить души',
  852. BUY_SOULS_TITLE: 'Купить души героев из всех доступных магазинов',
  853. BUY_OUTLAND: 'Купить Запределье',
  854. BUY_OUTLAND_TITLE: 'Купить 9 сундуков в Запределье за 540 изумрудов',
  855. RAID: 'Рейд',
  856. AUTO_RAID_ADVENTURE: 'Рейд',
  857. AUTO_RAID_ADVENTURE_TITLE: 'Рейд приключения заданное количество раз',
  858. CLAN_STAT: 'Клановая статистика',
  859. CLAN_STAT_TITLE: 'Копирует клановую статистику в буфер обмена',
  860. BTN_AUTO_F5: 'Авто (F5)',
  861. BOSS_DAMAGE: 'Урон по боссу: ',
  862. NOTHING_BUY: 'Нечего покупать',
  863. LOTS_BOUGHT: 'За золото куплено {countBuy} лотов',
  864. BUY_FOR_GOLD: 'Скупить за золото',
  865. BUY_FOR_GOLD_TITLE: 'Скупить предметы за золото в Городской лавке и в магазине Камней Душ Питомцев',
  866. REWARDS_AND_MAIL: 'Награды и почта',
  867. REWARDS_AND_MAIL_TITLE: 'Собирает награды и почту',
  868. COLLECT_REWARDS_AND_MAIL: 'Собрано {countQuests} наград и {countMail} писем',
  869. TIMER_ALREADY: 'Таймер уже запущен {time}',
  870. NO_ATTEMPTS_TIMER_START: 'Попыток нет, запущен таймер {time}',
  871. EPIC_BRAWL_RESULT: '{i} Победы: {wins}/{attempts}, Монеты: {coins}, Серия: {progress}/{nextStage} [Закрыть]{end}',
  872. ATTEMPT_ENDED: '<br>Попытки закончились, запущен таймер {time}',
  873. EPIC_BRAWL: 'Вселенская битва',
  874. EPIC_BRAWL_TITLE: 'Тратит попытки во Вселенской битве',
  875. RELOAD_GAME: 'Перезагрузить игру',
  876. TIMER: 'Таймер:',
  877. SHOW_ERRORS: 'Отображать ошибки',
  878. SHOW_ERRORS_TITLE: 'Отображать ошибки запросов к серверу',
  879. ERROR_MSG: 'Ошибка: {name}<br>{description}',
  880. EVENT_AUTO_BOSS:
  881. 'Максимальное количество боев для расчета:</br>{length} * {countTestBattle} = {maxCalcBattle}</br>Если у Вас слабый компьютер на это может потребоваться много времени, нажмите крестик для отмены.</br>Искать лучший пак из всех или первый подходящий?',
  882. BEST_SLOW: 'Лучший (медленее)',
  883. FIRST_FAST: 'Первый (быстрее)',
  884. FREEZE_INTERFACE: 'Идет расчет... <br> Интерфейс может зависнуть.',
  885. ERROR_F12: 'Ошибка, подробности в консоли (F12)',
  886. FAILED_FIND_WIN_PACK: 'Победный пак найти не удалось',
  887. BEST_PACK: 'Наилучший пак: ',
  888. BOSS_HAS_BEEN_DEF: 'Босс {bossLvl} побежден',
  889. NOT_ENOUGH_ATTEMPTS_BOSS: 'Для победы босса ${bossLvl} не хватило попыток, повторить?',
  890. BOSS_VICTORY_IMPOSSIBLE:
  891. 'По результатам прерасчета {battles} боев победу получить не удалось. Вы хотите продолжить поиск победного боя на реальных боях?',
  892. BOSS_HAS_BEEN_DEF_TEXT:
  893. 'Босс {bossLvl} побежден за<br>{countBattle}/{countMaxBattle} попыток{winTimer}<br>(Сделайте синхронизацию или перезагрузите игру для обновления данных)',
  894. MAP: 'Карта: ',
  895. PLAYER_POS: 'Позиции игроков:',
  896. NY_GIFTS: 'Подарки',
  897. NY_GIFTS_TITLE: 'Открыть все новогодние подарки',
  898. NY_NO_GIFTS: 'Нет не полученных подарков',
  899. NY_GIFTS_COLLECTED: 'Собрано {count} подарков',
  900. CHANGE_MAP: 'Карта острова',
  901. CHANGE_MAP_TITLE: 'Сменить карту острова',
  902. SELECT_ISLAND_MAP: 'Выберите карту острова:',
  903. MAP_NUM: 'Карта {num}',
  904. SECRET_WEALTH_SHOP: 'Тайное богатство {name}: ',
  905. SHOPS: 'Магазины',
  906. SHOPS_DEFAULT: 'Стандартные',
  907. SHOPS_DEFAULT_TITLE: 'Стандартные магазины',
  908. SHOPS_LIST: 'Магазины {number}',
  909. SHOPS_LIST_TITLE: 'Список магазинов {number}',
  910. SHOPS_WARNING:
  911. 'Магазины<br><span style="color:red">Если Вы купите монеты магазинов потасовок за изумруды, то их надо использовать сразу, иначе после перезагрузки игры они пропадут!</span>',
  912. MINIONS_WARNING: 'Пачки героев для атаки приспешников неполные, продолжить?',
  913. FAST_SEASON: 'Быстрый сезон',
  914. FAST_SEASON_TITLE: 'Пропуск экрана с выбором карты в сезоне',
  915. SET_NUMBER_LEVELS: 'Указать колличество уровней:',
  916. POSSIBLE_IMPROVE_LEVELS: 'Возможно улучшить только {count} уровней.<br>Улучшаем?',
  917. NOT_ENOUGH_RESOURECES: 'Не хватает ресурсов',
  918. IMPROVED_LEVELS: 'Улучшено уровней: {count}',
  919. ARTIFACTS_UPGRADE: 'Улучшение артефактов',
  920. ARTIFACTS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых артефактов героев',
  921. SKINS_UPGRADE: 'Улучшение обликов',
  922. SKINS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых обликов героев',
  923. HINT: '<br>Подсказка: ',
  924. PICTURE: '<br>На картинке: ',
  925. ANSWER: '<br>Ответ: ',
  926. NO_HEROES_PACK: 'Проведите хотя бы один бой для сохранения атакующей команды',
  927. BRAWL_AUTO_PACK: 'Автоподбор пачки',
  928. BRAWL_AUTO_PACK_NOT_CUR_HERO: 'Автоматический подбор пачки не подходит для текущего героя',
  929. BRAWL_DAILY_TASK_COMPLETED: 'Ежедневное задание выполнено, продолжить атаку?',
  930. CALC_STAT: 'Посчитать статистику',
  931. ELEMENT_TOURNAMENT_REWARD: 'Несобранная награда за Турнир Стихий',
  932. BTN_TRY_FIX_IT: 'Исправить',
  933. BTN_TRY_FIX_IT_TITLE: 'Включить исправление боев при автоатаке',
  934. DAMAGE_FIXED: 'Урон исправлен с {lastDamage} до {maxDamage}!',
  935. DAMAGE_NO_FIXED: 'Не удалось исправить урон: {lastDamage}',
  936. LETS_FIX: 'Исправляем',
  937. COUNT_FIXED: 'За {count} попыток',
  938. DEFEAT_TURN_TIMER: 'Поражение! Включить таймер для завершения миссии?',
  939. SEASON_REWARD: 'Награды сезонов',
  940. SEASON_REWARD_TITLE: 'Собирает доступные бесплатные награды со всех текущих сезонов',
  941. SEASON_REWARD_COLLECTED: 'Собрано {count} наград сезонов',
  942. SELL_HERO_SOULS: 'Продать души',
  943. SELL_HERO_SOULS_TITLE: 'Обменивает все души героев с абсолютной звездой на золото',
  944. GOLD_RECEIVED: 'Получено золота: {gold}',
  945. OPEN_ALL_EQUIP_BOXES: 'Открыть все ящики фрагментов экипировки?',
  946. SERVER_NOT_ACCEPT: 'Сервер не принял результат',
  947. INVASION_BOSS_BUFF: 'Для {bossLvl} босса нужен баф {needBuff} у вас {haveBuff}',
  948. HERO_POWER: 'Сила героев',
  949. HERO_POWER_TITLE: 'Отображает текущую и максимальную силу героев',
  950. MAX_POWER_REACHED: 'Максимальная достигнутая мощь: {power}',
  951. CURRENT_POWER: 'Текущая мощь: {power}',
  952. POWER_TO_MAX: 'До максимума мощи осталось: <span style="color:{color};">{power}</span><br>',
  953. BEST_RESULT: 'Лучший результат: {value}%',
  954. GUILD_ISLAND_TITLE: 'Перейти к Острову гильдии',
  955. TITAN_VALLEY_TITLE: 'Перейти к Долине титанов',
  956. },
  957. };
  958.  
  959. function getLang() {
  960. let lang = '';
  961. if (typeof NXFlashVars !== 'undefined') {
  962. lang = NXFlashVars.interface_lang
  963. }
  964. if (!lang) {
  965. lang = (navigator.language || navigator.userLanguage).substr(0, 2);
  966. }
  967. if (lang == 'ru') {
  968. return lang;
  969. }
  970. return 'en';
  971. }
  972.  
  973. this.I18N = function (constant, replace) {
  974. const selectLang = getLang();
  975. if (constant && constant in i18nLangData[selectLang]) {
  976. const result = i18nLangData[selectLang][constant];
  977. if (replace) {
  978. return result.sprintf(replace);
  979. }
  980. return result;
  981. }
  982. return `% ${constant} %`;
  983. };
  984.  
  985. String.prototype.sprintf = String.prototype.sprintf ||
  986. function () {
  987. "use strict";
  988. var str = this.toString();
  989. if (arguments.length) {
  990. var t = typeof arguments[0];
  991. var key;
  992. var args = ("string" === t || "number" === t) ?
  993. Array.prototype.slice.call(arguments)
  994. : arguments[0];
  995.  
  996. for (key in args) {
  997. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  998. }
  999. }
  1000.  
  1001. return str;
  1002. };
  1003.  
  1004. /**
  1005. * Checkboxes
  1006. *
  1007. * Чекбоксы
  1008. */
  1009. const checkboxes = {
  1010. passBattle: {
  1011. label: I18N('SKIP_FIGHTS'),
  1012. cbox: null,
  1013. title: I18N('SKIP_FIGHTS_TITLE'),
  1014. default: false,
  1015. },
  1016. sendExpedition: {
  1017. label: I18N('AUTO_EXPEDITION'),
  1018. cbox: null,
  1019. title: I18N('AUTO_EXPEDITION_TITLE'),
  1020. default: false,
  1021. },
  1022. cancelBattle: {
  1023. label: I18N('CANCEL_FIGHT'),
  1024. cbox: null,
  1025. title: I18N('CANCEL_FIGHT_TITLE'),
  1026. default: false,
  1027. },
  1028. preCalcBattle: {
  1029. label: I18N('BATTLE_RECALCULATION'),
  1030. cbox: null,
  1031. title: I18N('BATTLE_RECALCULATION_TITLE'),
  1032. default: false,
  1033. },
  1034. countControl: {
  1035. label: I18N('QUANTITY_CONTROL'),
  1036. cbox: null,
  1037. title: I18N('QUANTITY_CONTROL_TITLE'),
  1038. default: true,
  1039. },
  1040. repeatMission: {
  1041. label: I18N('REPEAT_CAMPAIGN'),
  1042. cbox: null,
  1043. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  1044. default: false,
  1045. },
  1046. noOfferDonat: {
  1047. label: I18N('DISABLE_DONAT'),
  1048. cbox: null,
  1049. title: I18N('DISABLE_DONAT_TITLE'),
  1050. /**
  1051. * A crutch to get the field before getting the character id
  1052. *
  1053. * Костыль чтоб получать поле до получения id персонажа
  1054. */
  1055. default: (() => {
  1056. $result = false;
  1057. try {
  1058. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat']);
  1059. } catch (e) {
  1060. $result = false;
  1061. }
  1062. return $result || false;
  1063. })(),
  1064. },
  1065. dailyQuests: {
  1066. label: I18N('DAILY_QUESTS'),
  1067. cbox: null,
  1068. title: I18N('DAILY_QUESTS_TITLE'),
  1069. default: false,
  1070. },
  1071. // Потасовки
  1072. autoBrawls: {
  1073. label: I18N('BRAWLS'),
  1074. cbox: null,
  1075. title: I18N('BRAWLS_TITLE'),
  1076. default: (() => {
  1077. $result = false;
  1078. try {
  1079. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls']);
  1080. } catch (e) {
  1081. $result = false;
  1082. }
  1083. return $result || false;
  1084. })(),
  1085. hide: false,
  1086. },
  1087. getAnswer: {
  1088. label: I18N('AUTO_QUIZ'),
  1089. cbox: null,
  1090. title: I18N('AUTO_QUIZ_TITLE'),
  1091. default: false,
  1092. hide: true,
  1093. },
  1094. tryFixIt_v2: {
  1095. label: I18N('BTN_TRY_FIX_IT'),
  1096. cbox: null,
  1097. title: I18N('BTN_TRY_FIX_IT_TITLE'),
  1098. default: false,
  1099. hide: false,
  1100. },
  1101. showErrors: {
  1102. label: I18N('SHOW_ERRORS'),
  1103. cbox: null,
  1104. title: I18N('SHOW_ERRORS_TITLE'),
  1105. default: true,
  1106. },
  1107. buyForGold: {
  1108. label: I18N('BUY_FOR_GOLD'),
  1109. cbox: null,
  1110. title: I18N('BUY_FOR_GOLD_TITLE'),
  1111. default: false,
  1112. },
  1113. hideServers: {
  1114. label: I18N('HIDE_SERVERS'),
  1115. cbox: null,
  1116. title: I18N('HIDE_SERVERS_TITLE'),
  1117. default: false,
  1118. },
  1119. fastSeason: {
  1120. label: I18N('FAST_SEASON'),
  1121. cbox: null,
  1122. title: I18N('FAST_SEASON_TITLE'),
  1123. default: false,
  1124. },
  1125. };
  1126. /**
  1127. * Get checkbox state
  1128. *
  1129. * Получить состояние чекбокса
  1130. */
  1131. function isChecked(checkBox) {
  1132. if (!(checkBox in checkboxes)) {
  1133. return false;
  1134. }
  1135. return checkboxes[checkBox].cbox?.checked;
  1136. }
  1137. /**
  1138. * Input fields
  1139. *
  1140. * Поля ввода
  1141. */
  1142. const inputs = {
  1143. countTitanit: {
  1144. input: null,
  1145. title: I18N('HOW_MUCH_TITANITE'),
  1146. default: 150,
  1147. },
  1148. speedBattle: {
  1149. input: null,
  1150. title: I18N('COMBAT_SPEED'),
  1151. default: 5,
  1152. },
  1153. countTestBattle: {
  1154. input: null,
  1155. title: I18N('NUMBER_OF_TEST'),
  1156. default: 10,
  1157. },
  1158. countAutoBattle: {
  1159. input: null,
  1160. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  1161. default: 10,
  1162. },
  1163. FPS: {
  1164. input: null,
  1165. title: 'FPS',
  1166. default: 60,
  1167. }
  1168. }
  1169. /**
  1170. * Checks the checkbox
  1171. *
  1172. * Поплучить данные поля ввода
  1173. */
  1174. function getInput(inputName) {
  1175. return inputs[inputName]?.input?.value;
  1176. }
  1177.  
  1178. /**
  1179. * Control FPS
  1180. *
  1181. * Контроль FPS
  1182. */
  1183. let nextAnimationFrame = Date.now();
  1184. const oldRequestAnimationFrame = this.requestAnimationFrame;
  1185. this.requestAnimationFrame = async function (e) {
  1186. const FPS = Number(getInput('FPS')) || -1;
  1187. const now = Date.now();
  1188. const delay = nextAnimationFrame - now;
  1189. nextAnimationFrame = Math.max(now, nextAnimationFrame) + Math.min(1e3 / FPS, 1e3);
  1190. if (delay > 0) {
  1191. await new Promise((e) => setTimeout(e, delay));
  1192. }
  1193. oldRequestAnimationFrame(e);
  1194. };
  1195. /**
  1196. * Button List
  1197. *
  1198. * Список кнопочек
  1199. */
  1200. const buttons = {
  1201. getOutland: {
  1202. name: I18N('TO_DO_EVERYTHING'),
  1203. title: I18N('TO_DO_EVERYTHING_TITLE'),
  1204. onClick: testDoYourBest,
  1205. },
  1206. doActions: {
  1207. name: I18N('ACTIONS'),
  1208. title: I18N('ACTIONS_TITLE'),
  1209. onClick: async function () {
  1210. const popupButtons = [
  1211. {
  1212. msg: I18N('OUTLAND'),
  1213. result: function () {
  1214. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  1215. },
  1216. title: I18N('OUTLAND_TITLE'),
  1217. },
  1218. {
  1219. msg: I18N('TOWER'),
  1220. result: function () {
  1221. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1222. },
  1223. title: I18N('TOWER_TITLE'),
  1224. },
  1225. {
  1226. msg: I18N('EXPEDITIONS'),
  1227. result: function () {
  1228. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  1229. },
  1230. title: I18N('EXPEDITIONS_TITLE'),
  1231. },
  1232. {
  1233. msg: I18N('MINIONS'),
  1234. result: function () {
  1235. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1236. },
  1237. title: I18N('MINIONS_TITLE'),
  1238. },
  1239. {
  1240. msg: I18N('ESTER_EGGS'),
  1241. result: function () {
  1242. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  1243. },
  1244. title: I18N('ESTER_EGGS_TITLE'),
  1245. },
  1246. {
  1247. msg: I18N('STORM'),
  1248. result: function () {
  1249. testAdventure('solo');
  1250. },
  1251. title: I18N('STORM_TITLE'),
  1252. },
  1253. {
  1254. msg: I18N('REWARDS'),
  1255. result: function () {
  1256. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  1257. },
  1258. title: I18N('REWARDS_TITLE'),
  1259. },
  1260. {
  1261. msg: I18N('MAIL'),
  1262. result: function () {
  1263. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  1264. },
  1265. title: I18N('MAIL_TITLE'),
  1266. },
  1267. {
  1268. msg: I18N('SEER'),
  1269. result: function () {
  1270. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SEER')}?`, rollAscension);
  1271. },
  1272. title: I18N('SEER_TITLE'),
  1273. },
  1274. /*
  1275. {
  1276. msg: I18N('NY_GIFTS'),
  1277. result: getGiftNewYear,
  1278. title: I18N('NY_GIFTS_TITLE'),
  1279. },
  1280. */
  1281. ];
  1282. popupButtons.push({ result: false, isClose: true });
  1283. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1284. if (typeof answer === 'function') {
  1285. answer();
  1286. }
  1287. },
  1288. },
  1289. doOthers: {
  1290. name: I18N('OTHERS'),
  1291. title: I18N('OTHERS_TITLE'),
  1292. onClick: async function () {
  1293. const popupButtons = [
  1294. {
  1295. msg: I18N('GET_ENERGY'),
  1296. result: farmStamina,
  1297. title: I18N('GET_ENERGY_TITLE'),
  1298. },
  1299. {
  1300. msg: I18N('ITEM_EXCHANGE'),
  1301. result: fillActive,
  1302. title: I18N('ITEM_EXCHANGE_TITLE'),
  1303. },
  1304. {
  1305. msg: I18N('BUY_SOULS'),
  1306. result: function () {
  1307. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1308. },
  1309. title: I18N('BUY_SOULS_TITLE'),
  1310. },
  1311. {
  1312. msg: I18N('BUY_FOR_GOLD'),
  1313. result: function () {
  1314. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1315. },
  1316. title: I18N('BUY_FOR_GOLD_TITLE'),
  1317. },
  1318. {
  1319. msg: I18N('BUY_OUTLAND'),
  1320. result: bossOpenChestPay,
  1321. title: I18N('BUY_OUTLAND_TITLE'),
  1322. },
  1323. {
  1324. msg: I18N('CLAN_STAT'),
  1325. result: clanStatistic,
  1326. title: I18N('CLAN_STAT_TITLE'),
  1327. },
  1328. {
  1329. msg: I18N('EPIC_BRAWL'),
  1330. result: async function () {
  1331. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1332. const brawl = new epicBrawl();
  1333. brawl.start();
  1334. });
  1335. },
  1336. title: I18N('EPIC_BRAWL_TITLE'),
  1337. },
  1338. {
  1339. msg: I18N('ARTIFACTS_UPGRADE'),
  1340. result: updateArtifacts,
  1341. title: I18N('ARTIFACTS_UPGRADE_TITLE'),
  1342. },
  1343. {
  1344. msg: I18N('SKINS_UPGRADE'),
  1345. result: updateSkins,
  1346. title: I18N('SKINS_UPGRADE_TITLE'),
  1347. },
  1348. {
  1349. msg: I18N('SEASON_REWARD'),
  1350. result: farmBattlePass,
  1351. title: I18N('SEASON_REWARD_TITLE'),
  1352. },
  1353. {
  1354. msg: I18N('SELL_HERO_SOULS'),
  1355. result: sellHeroSoulsForGold,
  1356. title: I18N('SELL_HERO_SOULS_TITLE'),
  1357. },
  1358. {
  1359. msg: I18N('CHANGE_MAP'),
  1360. result: async function () {
  1361. const maps = Object.values(lib.data.seasonAdventure.list)
  1362. .filter((e) => e.map.cells.length > 2)
  1363. .map((i) => ({
  1364. msg: I18N('MAP_NUM', { num: i.id }),
  1365. result: i.id,
  1366. }));
  1367.  
  1368. const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [...maps, { result: false, isClose: true }]);
  1369. if (result) {
  1370. cheats.changeIslandMap(result);
  1371. }
  1372. },
  1373. title: I18N('CHANGE_MAP_TITLE'),
  1374. },
  1375. {
  1376. msg: I18N('HERO_POWER'),
  1377. result: async () => {
  1378. const calls = ['userGetInfo', 'heroGetAll'].map((name) => ({
  1379. name,
  1380. args: {},
  1381. ident: name,
  1382. }));
  1383. const [maxHeroSumPower, heroSumPower] = await Send({ calls }).then((e) => [
  1384. e.results[0].result.response.maxSumPower.heroes,
  1385. Object.values(e.results[1].result.response).reduce((a, e) => a + e.power, 0),
  1386. ]);
  1387. const power = maxHeroSumPower - heroSumPower;
  1388. let msg =
  1389. I18N('MAX_POWER_REACHED', { power: maxHeroSumPower.toLocaleString() }) +
  1390. '<br>' +
  1391. I18N('CURRENT_POWER', { power: heroSumPower.toLocaleString() }) +
  1392. '<br>' +
  1393. I18N('POWER_TO_MAX', { power: power.toLocaleString(), color: power >= 4000 ? 'green' : 'red' });
  1394. await popup.confirm(msg, [{ msg: I18N('BTN_OK'), result: 0 }]);
  1395. },
  1396. title: I18N('HERO_POWER_TITLE'),
  1397. },
  1398. ];
  1399. popupButtons.push({ result: false, isClose: true });
  1400. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1401. if (typeof answer === 'function') {
  1402. answer();
  1403. }
  1404. },
  1405. },
  1406. testTitanArena: {
  1407. isCombine: true,
  1408. combineList: [
  1409. {
  1410. name: I18N('TITAN_ARENA'),
  1411. title: I18N('TITAN_ARENA_TITLE'),
  1412. onClick: function () {
  1413. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1414. },
  1415. },
  1416. {
  1417. name: '>>',
  1418. onClick: cheats.goTitanValley,
  1419. title: I18N('TITAN_VALLEY_TITLE'),
  1420. color: 'green',
  1421. },
  1422. ],
  1423. },
  1424. testDungeon: {
  1425. isCombine: true,
  1426. combineList: [
  1427. {
  1428. name: I18N('DUNGEON'),
  1429. onClick: function () {
  1430. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1431. },
  1432. title: I18N('DUNGEON_TITLE'),
  1433. },
  1434. {
  1435. name: '>>',
  1436. onClick: cheats.goClanIsland,
  1437. title: I18N('GUILD_ISLAND_TITLE'),
  1438. color: 'green',
  1439. },
  1440. ],
  1441. },
  1442. testAdventure: {
  1443. isCombine: true,
  1444. combineList: [
  1445. {
  1446. name: I18N('ADVENTURE'),
  1447. onClick: () => {
  1448. testAdventure();
  1449. },
  1450. title: I18N('ADVENTURE_TITLE'),
  1451. },
  1452. {
  1453. name: I18N('AUTO_RAID_ADVENTURE'),
  1454. onClick: autoRaidAdventure,
  1455. title: I18N('AUTO_RAID_ADVENTURE_TITLE'),
  1456. },
  1457. {
  1458. name: '>>',
  1459. onClick: cheats.goSanctuary,
  1460. title: I18N('SANCTUARY_TITLE'),
  1461. color: 'green',
  1462. },
  1463. ],
  1464. },
  1465. // Архидемон
  1466. bossRatingEvent: {
  1467. name: I18N('ARCHDEMON'),
  1468. title: I18N('ARCHDEMON_TITLE'),
  1469. onClick: function () {
  1470. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1471. },
  1472. hide: true,
  1473. },
  1474. // Горнило душ
  1475. bossRatingEvent: {
  1476. name: I18N('FURNACE_OF_SOULS'),
  1477. title: I18N('ARCHDEMON_TITLE'),
  1478. onClick: function () {
  1479. confShow(`${I18N('RUN_SCRIPT')} ${I18N('FURNACE_OF_SOULS')}?`, bossRatingEventSouls);
  1480. },
  1481. hide: true,
  1482. },
  1483. rewardsAndMailFarm: {
  1484. name: I18N('REWARDS_AND_MAIL'),
  1485. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1486. onClick: function () {
  1487. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1488. },
  1489. },
  1490. goToClanWar: {
  1491. name: I18N('GUILD_WAR'),
  1492. title: I18N('GUILD_WAR_TITLE'),
  1493. onClick: cheats.goClanWar,
  1494. dot: true,
  1495. },
  1496. dailyQuests: {
  1497. name: I18N('DAILY_QUESTS'),
  1498. title: I18N('DAILY_QUESTS_TITLE'),
  1499. onClick: async function () {
  1500. const quests = new dailyQuests(
  1501. () => {},
  1502. () => {}
  1503. );
  1504. await quests.autoInit();
  1505. quests.start();
  1506. },
  1507. },
  1508. newDay: {
  1509. name: I18N('SYNC'),
  1510. title: I18N('SYNC_TITLE'),
  1511. onClick: function () {
  1512. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1513. },
  1514. },
  1515. };
  1516. /**
  1517. * Display buttons
  1518. *
  1519. * Вывести кнопочки
  1520. */
  1521. function addControlButtons() {
  1522. for (let name in buttons) {
  1523. button = buttons[name];
  1524. if (button.hide) {
  1525. continue;
  1526. }
  1527. if (button.isCombine) {
  1528. button['button'] = scriptMenu.addCombinedButton(button.combineList);
  1529. continue;
  1530. }
  1531. button['button'] = scriptMenu.addButton(button);
  1532. }
  1533. }
  1534. /**
  1535. * Adds links
  1536. *
  1537. * Добавляет ссылки
  1538. */
  1539. function addBottomUrls() {
  1540. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1541. }
  1542. /**
  1543. * Stop repetition of the mission
  1544. *
  1545. * Остановить повтор миссии
  1546. */
  1547. let isStopSendMission = false;
  1548. /**
  1549. * There is a repetition of the mission
  1550. *
  1551. * Идет повтор миссии
  1552. */
  1553. let isSendsMission = false;
  1554. /**
  1555. * Data on the past mission
  1556. *
  1557. * Данные о прошедшей мисии
  1558. */
  1559. let lastMissionStart = {}
  1560. /**
  1561. * Start time of the last battle in the company
  1562. *
  1563. * Время начала последнего боя в кампании
  1564. */
  1565. let lastMissionBattleStart = 0;
  1566. /**
  1567. * Data for calculating the last battle with the boss
  1568. *
  1569. * Данные для расчете последнего боя с боссом
  1570. */
  1571. let lastBossBattle = null;
  1572. /**
  1573. * Information about the last battle
  1574. *
  1575. * Данные о прошедшей битве
  1576. */
  1577. let lastBattleArg = {}
  1578. let lastBossBattleStart = null;
  1579. this.addBattleTimer = 4;
  1580. this.invasionTimer = 2500;
  1581. const invasionInfo = {
  1582. id: 225,
  1583. buff: 0,
  1584. bossLvl: 130,
  1585. };
  1586. const invasionDataPacks = {
  1587. 130: { buff: 0, pet: 6005, heroes: [9, 62, 10, 1, 66], favor: { 9: 6006 } },
  1588. 140: { buff: 0, pet: 6005, heroes: [9, 62, 10, 1, 66], favor: {} },
  1589. 150: { buff: 0, pet: 6005, heroes: [9, 62, 10, 1, 66], favor: {} },
  1590. 160: { buff: 0, pet: 6005, heroes: [64, 66, 13, 9, 4], favor: { 4: 6006, 9: 6004, 13: 6003, 64: 6005, 66: 6002 } },
  1591. 170: { buff: 0, pet: 6005, heroes: [9, 62, 10, 1, 66], favor: { 1: 6006, 9: 6005, 10: 6008, 62: 6003, 66: 6002 } },
  1592. 180: { buff: 0, pet: 6006, heroes: [62, 10, 2, 4, 66], favor: { 2: 6005, 4: 6001, 10: 6006, 62: 6003 } },
  1593. 190: { buff: 40, pet: 6005, heroes: [9, 2, 43, 45, 66], favor: { 9: 6005, 45: 6002, 66: 6006 } },
  1594. 200: { buff: 20, pet: 6005, heroes: [9, 62, 1, 48, 66], favor: { 9: 6007, 62: 6003 } },
  1595. 210: { buff: 10, pet: 6008, heroes: [9, 10, 4, 32, 66], favor: { 9: 6005, 10: 6003, 32: 6007, 66: 6006 } },
  1596. 220: { buff: 20, pet: 6004, heroes: [9, 1, 48, 43, 66], favor: { 9: 6005, 43: 6006, 48: 6000, 66: 6002 } },
  1597. 230: { buff: 45, pet: 6001, heroes: [9, 7, 40, 43, 66], favor: { 7: 6006, 9: 6005, 40: 6004, 43: 6006, 66: 6006 } },
  1598. 240: { buff: 50, pet: 6009, heroes: [9, 40, 43, 51, 66], favor: { 9: 6005, 40: 6004, 43: 6002, 66: 6007 } },
  1599. 250: { buff: 70, pet: 6005, heroes: [9, 10, 13, 43, 66], favor: { 9: 6005, 10: 6002, 13: 6002, 43: 6006, 66: 6006 } },
  1600. 260: { buff: 80, pet: 6008, heroes: [9, 40, 43, 4, 66], favor: { 4: 6001, 9: 6006, 43: 6006 } },
  1601. 270: { buff: 115, pet: 6001, heroes: [9, 13, 43, 51, 66], favor: { 9: 6006, 43: 6006, 51: 6001 } },
  1602. 280: { buff: 80, pet: 6008, heroes: [9, 13, 43, 56, 66], favor: { 9: 6004, 13: 6006, 43: 6006, 66: 6006 } },
  1603. 290: { buff: 60, pet: 6005, heroes: [9, 10, 43, 56, 66], favor: { 9: 6005, 10: 6002, 43: 6006 } },
  1604. 300: { buff: 75, pet: 6006, heroes: [9, 62, 1, 45, 66], favor: { 1: 6006, 9: 6005, 45: 6002, 66: 6007 } },
  1605. };
  1606. /**
  1607. * The name of the function of the beginning of the battle
  1608. *
  1609. * Имя функции начала боя
  1610. */
  1611. let nameFuncStartBattle = '';
  1612. /**
  1613. * The name of the function of the end of the battle
  1614. *
  1615. * Имя функции конца боя
  1616. */
  1617. let nameFuncEndBattle = '';
  1618. /**
  1619. * Data for calculating the last battle
  1620. *
  1621. * Данные для расчета последнего боя
  1622. */
  1623. let lastBattleInfo = null;
  1624. /**
  1625. * The ability to cancel the battle
  1626. *
  1627. * Возможность отменить бой
  1628. */
  1629. let isCancalBattle = true;
  1630.  
  1631. function setIsCancalBattle(value) {
  1632. isCancalBattle = value;
  1633. }
  1634.  
  1635. /**
  1636. * Certificator of the last open nesting doll
  1637. *
  1638. * Идетификатор последней открытой матрешки
  1639. */
  1640. let lastRussianDollId = null;
  1641. /**
  1642. * Cancel the training guide
  1643. *
  1644. * Отменить обучающее руководство
  1645. */
  1646. this.isCanceledTutorial = false;
  1647.  
  1648. /**
  1649. * Data from the last question of the quiz
  1650. *
  1651. * Данные последнего вопроса викторины
  1652. */
  1653. let lastQuestion = null;
  1654. /**
  1655. * Answer to the last question of the quiz
  1656. *
  1657. * Ответ на последний вопрос викторины
  1658. */
  1659. let lastAnswer = null;
  1660. /**
  1661. * Flag for opening keys or titan artifact spheres
  1662. *
  1663. * Флаг открытия ключей или сфер артефактов титанов
  1664. */
  1665. let artifactChestOpen = false;
  1666. /**
  1667. * The name of the function to open keys or orbs of titan artifacts
  1668. *
  1669. * Имя функции открытия ключей или сфер артефактов титанов
  1670. */
  1671. let artifactChestOpenCallName = '';
  1672. let correctShowOpenArtifact = 0;
  1673. /**
  1674. * Data for the last battle in the dungeon
  1675. * (Fix endless cards)
  1676. *
  1677. * Данные для последнего боя в подземке
  1678. * (Исправление бесконечных карт)
  1679. */
  1680. let lastDungeonBattleData = null;
  1681. /**
  1682. * Start time of the last battle in the dungeon
  1683. *
  1684. * Время начала последнего боя в подземелье
  1685. */
  1686. let lastDungeonBattleStart = 0;
  1687. /**
  1688. * Subscription end time
  1689. *
  1690. * Время окончания подписки
  1691. */
  1692. let subEndTime = 0;
  1693. /**
  1694. * Number of prediction cards
  1695. *
  1696. * Количество карт предсказаний
  1697. */
  1698. let countPredictionCard = 0;
  1699.  
  1700. /**
  1701. * Brawl pack
  1702. *
  1703. * Пачка для потасовок
  1704. */
  1705. let brawlsPack = null;
  1706. /**
  1707. * Autobrawl started
  1708. *
  1709. * Автопотасовка запущена
  1710. */
  1711. let isBrawlsAutoStart = false;
  1712. let clanDominationGetInfo = null;
  1713. /**
  1714. * Copies the text to the clipboard
  1715. *
  1716. * Копирует тест в буфер обмена
  1717. * @param {*} text copied text // копируемый текст
  1718. */
  1719. function copyText(text) {
  1720. let copyTextarea = document.createElement("textarea");
  1721. copyTextarea.style.opacity = "0";
  1722. copyTextarea.textContent = text;
  1723. document.body.appendChild(copyTextarea);
  1724. copyTextarea.select();
  1725. document.execCommand("copy");
  1726. document.body.removeChild(copyTextarea);
  1727. delete copyTextarea;
  1728. }
  1729. /**
  1730. * Returns the history of requests
  1731. *
  1732. * Возвращает историю запросов
  1733. */
  1734. this.getRequestHistory = function() {
  1735. return requestHistory;
  1736. }
  1737. /**
  1738. * Generates a random integer from min to max
  1739. *
  1740. * Гененирует случайное целое число от min до max
  1741. */
  1742. const random = function (min, max) {
  1743. return Math.floor(Math.random() * (max - min + 1) + min);
  1744. }
  1745. const randf = function (min, max) {
  1746. return Math.random() * (max - min + 1) + min;
  1747. };
  1748. /**
  1749. * Clearing the request history
  1750. *
  1751. * Очистка истоии запросов
  1752. */
  1753. setInterval(function () {
  1754. let now = Date.now();
  1755. for (let i in requestHistory) {
  1756. const time = +i.split('_')[0];
  1757. if (now - time > 300000) {
  1758. delete requestHistory[i];
  1759. }
  1760. }
  1761. }, 300000);
  1762. /**
  1763. * Displays the dialog box
  1764. *
  1765. * Отображает диалоговое окно
  1766. */
  1767. function confShow(message, yesCallback, noCallback) {
  1768. let buts = [];
  1769. message = message || I18N('DO_YOU_WANT');
  1770. noCallback = noCallback || (() => {});
  1771. if (yesCallback) {
  1772. buts = [
  1773. { msg: I18N('BTN_RUN'), result: true},
  1774. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true},
  1775. ]
  1776. } else {
  1777. yesCallback = () => {};
  1778. buts = [
  1779. { msg: I18N('BTN_OK'), result: true},
  1780. ];
  1781. }
  1782. popup.confirm(message, buts).then((e) => {
  1783. // dialogPromice = null;
  1784. if (e) {
  1785. yesCallback();
  1786. } else {
  1787. noCallback();
  1788. }
  1789. });
  1790. }
  1791. /**
  1792. * Override/proxy the method for creating a WS package send
  1793. *
  1794. * Переопределяем/проксируем метод создания отправки WS пакета
  1795. */
  1796. WebSocket.prototype.send = function (data) {
  1797. if (!this.isSetOnMessage) {
  1798. const oldOnmessage = this.onmessage;
  1799. this.onmessage = function (event) {
  1800. try {
  1801. const data = JSON.parse(event.data);
  1802. if (!this.isWebSocketLogin && data.result.type == "iframeEvent.login") {
  1803. this.isWebSocketLogin = true;
  1804. } else if (data.result.type == "iframeEvent.login") {
  1805. return;
  1806. }
  1807. } catch (e) { }
  1808. return oldOnmessage.apply(this, arguments);
  1809. }
  1810. this.isSetOnMessage = true;
  1811. }
  1812. original.SendWebSocket.call(this, data);
  1813. }
  1814. /**
  1815. * Overriding/Proxying the Ajax Request Creation Method
  1816. *
  1817. * Переопределяем/проксируем метод создания Ajax запроса
  1818. */
  1819. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1820. this.uniqid = Date.now() + '_' + random(1000000, 10000000);
  1821. this.errorRequest = false;
  1822. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1823. if (!apiUrl) {
  1824. apiUrl = url;
  1825. const socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1826. console.log(socialInfo);
  1827. }
  1828. requestHistory[this.uniqid] = {
  1829. method,
  1830. url,
  1831. error: [],
  1832. headers: {},
  1833. request: null,
  1834. response: null,
  1835. signature: [],
  1836. calls: {},
  1837. };
  1838. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1839. this.errorRequest = true;
  1840. }
  1841. return original.open.call(this, method, url, async, user, password);
  1842. };
  1843. /**
  1844. * Overriding/Proxying the header setting method for the AJAX request
  1845. *
  1846. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1847. */
  1848. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1849. if (this.uniqid in requestHistory) {
  1850. requestHistory[this.uniqid].headers[name] = value;
  1851. } else {
  1852. check = true;
  1853. }
  1854.  
  1855. if (name == 'X-Auth-Signature') {
  1856. requestHistory[this.uniqid].signature.push(value);
  1857. if (!check) {
  1858. return;
  1859. }
  1860. }
  1861.  
  1862. return original.setRequestHeader.call(this, name, value);
  1863. };
  1864. /**
  1865. * Overriding/Proxying the AJAX Request Sending Method
  1866. *
  1867. * Переопределяем/проксируем метод отправки AJAX запроса
  1868. */
  1869. XMLHttpRequest.prototype.send = async function (sourceData) {
  1870. if (this.uniqid in requestHistory) {
  1871. let tempData = null;
  1872. if (getClass(sourceData) == "ArrayBuffer") {
  1873. tempData = decoder.decode(sourceData);
  1874. } else {
  1875. tempData = sourceData;
  1876. }
  1877. requestHistory[this.uniqid].request = tempData;
  1878. let headers = requestHistory[this.uniqid].headers;
  1879. lastHeaders = Object.assign({}, headers);
  1880. /**
  1881. * Game loading event
  1882. *
  1883. * Событие загрузки игры
  1884. */
  1885. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1886. isLoadGame = true;
  1887. if (cheats.libGame) {
  1888. lib.setData(cheats.libGame);
  1889. } else {
  1890. lib.setData(await cheats.LibLoad());
  1891. }
  1892. addControls();
  1893. addControlButtons();
  1894. addBottomUrls();
  1895.  
  1896. if (isChecked('sendExpedition')) {
  1897. const isTimeBetweenDays = isTimeBetweenNewDays();
  1898. if (!isTimeBetweenDays) {
  1899. checkExpedition();
  1900. } else {
  1901. setProgress(I18N('EXPEDITIONS_NOTTIME'), true);
  1902. }
  1903. }
  1904.  
  1905. getAutoGifts();
  1906.  
  1907. cheats.activateHacks();
  1908. justInfo();
  1909. if (isChecked('dailyQuests')) {
  1910. testDailyQuests();
  1911. }
  1912.  
  1913. if (isChecked('buyForGold')) {
  1914. buyInStoreForGold();
  1915. }
  1916. }
  1917. /**
  1918. * Outgoing request data processing
  1919. *
  1920. * Обработка данных исходящего запроса
  1921. */
  1922. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1923. /**
  1924. * Handling incoming request data
  1925. *
  1926. * Обработка данных входящего запроса
  1927. */
  1928. const oldReady = this.onreadystatechange;
  1929. this.onreadystatechange = async function (e) {
  1930. if (this.errorRequest) {
  1931. return oldReady.apply(this, arguments);
  1932. }
  1933. if(this.readyState == 4 && this.status == 200) {
  1934. isTextResponse = this.responseType === "text" || this.responseType === "";
  1935. let response = isTextResponse ? this.responseText : this.response;
  1936. requestHistory[this.uniqid].response = response;
  1937. /**
  1938. * Replacing incoming request data
  1939. *
  1940. * Заменна данных входящего запроса
  1941. */
  1942. if (isTextResponse) {
  1943. await checkChangeResponse.call(this, response);
  1944. }
  1945. /**
  1946. * A function to run after the request is executed
  1947. *
  1948. * Функция запускаемая после выполения запроса
  1949. */
  1950. if (typeof this.onReadySuccess == 'function') {
  1951. setTimeout(this.onReadySuccess, 500);
  1952. }
  1953. /** Удаляем из истории запросов битвы с боссом */
  1954. if ('invasion_bossStart' in requestHistory[this.uniqid].calls) delete requestHistory[this.uniqid];
  1955. }
  1956. if (oldReady) {
  1957. try {
  1958. return oldReady.apply(this, arguments);
  1959. } catch(e) {
  1960. console.log(oldReady);
  1961. console.error('Error in oldReady:', e);
  1962. }
  1963.  
  1964. }
  1965. }
  1966. }
  1967. if (this.errorRequest) {
  1968. const oldReady = this.onreadystatechange;
  1969. this.onreadystatechange = function () {
  1970. Object.defineProperty(this, 'status', {
  1971. writable: true
  1972. });
  1973. this.status = 200;
  1974. Object.defineProperty(this, 'readyState', {
  1975. writable: true
  1976. });
  1977. this.readyState = 4;
  1978. Object.defineProperty(this, 'responseText', {
  1979. writable: true
  1980. });
  1981. this.responseText = JSON.stringify({
  1982. "result": true
  1983. });
  1984. if (typeof this.onReadySuccess == 'function') {
  1985. setTimeout(this.onReadySuccess, 200);
  1986. }
  1987. return oldReady.apply(this, arguments);
  1988. }
  1989. this.onreadystatechange();
  1990. } else {
  1991. try {
  1992. return original.send.call(this, sourceData);
  1993. } catch(e) {
  1994. debugger;
  1995. }
  1996. }
  1997. };
  1998. /**
  1999. * Processing and substitution of outgoing data
  2000. *
  2001. * Обработка и подмена исходящих данных
  2002. */
  2003. async function checkChangeSend(sourceData, tempData) {
  2004. try {
  2005. /**
  2006. * A function that replaces battle data with incorrect ones to cancel combatя
  2007. *
  2008. * Функция заменяющая данные боя на неверные для отмены боя
  2009. */
  2010. const fixBattle = function (heroes) {
  2011. for (const ids in heroes) {
  2012. hero = heroes[ids];
  2013. hero.energy = random(1, 999);
  2014. if (hero.hp > 0) {
  2015. hero.hp = random(1, hero.hp);
  2016. }
  2017. }
  2018. }
  2019. /**
  2020. * Dialog window 2
  2021. *
  2022. * Диалоговое окно 2
  2023. */
  2024. const showMsg = async function (msg, ansF, ansS) {
  2025. if (typeof popup == 'object') {
  2026. return await popup.confirm(msg, [
  2027. {msg: ansF, result: false},
  2028. {msg: ansS, result: true},
  2029. ]);
  2030. } else {
  2031. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  2032. }
  2033. }
  2034. /**
  2035. * Dialog window 3
  2036. *
  2037. * Диалоговое окно 3
  2038. */
  2039. const showMsgs = async function (msg, ansF, ansS, ansT) {
  2040. return await popup.confirm(msg, [
  2041. {msg: ansF, result: 0},
  2042. {msg: ansS, result: 1},
  2043. {msg: ansT, result: 2},
  2044. ]);
  2045. }
  2046.  
  2047. let changeRequest = false;
  2048. testData = JSON.parse(tempData);
  2049. for (const call of testData.calls) {
  2050. if (!artifactChestOpen) {
  2051. requestHistory[this.uniqid].calls[call.name] = call.ident;
  2052. }
  2053. /**
  2054. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  2055. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  2056. */
  2057. if ((call.name == 'adventure_endBattle' ||
  2058. call.name == 'adventureSolo_endBattle' ||
  2059. call.name == 'clanWarEndBattle' &&
  2060. isChecked('cancelBattle') ||
  2061. call.name == 'crossClanWar_endBattle' &&
  2062. isChecked('cancelBattle') ||
  2063. call.name == 'brawl_endBattle' ||
  2064. call.name == 'towerEndBattle' ||
  2065. call.name == 'invasion_bossEnd' ||
  2066. call.name == 'titanArenaEndBattle' ||
  2067. call.name == 'bossEndBattle' ||
  2068. call.name == 'clanRaid_endNodeBattle') &&
  2069. isCancalBattle) {
  2070. nameFuncEndBattle = call.name;
  2071.  
  2072. if (isChecked('tryFixIt_v2') &&
  2073. !call.args.result.win &&
  2074. (call.name == 'brawl_endBattle' ||
  2075. //call.name == 'crossClanWar_endBattle' ||
  2076. call.name == 'epicBrawl_endBattle' ||
  2077. //call.name == 'clanWarEndBattle' ||
  2078. call.name == 'adventure_endBattle' ||
  2079. call.name == 'titanArenaEndBattle' ||
  2080. call.name == 'bossEndBattle' ||
  2081. call.name == 'adventureSolo_endBattle') &&
  2082. lastBattleInfo) {
  2083. const noFixWin = call.name == 'clanWarEndBattle' || call.name == 'crossClanWar_endBattle';
  2084. const cloneBattle = structuredClone(lastBattleInfo);
  2085. lastBattleInfo = null;
  2086. try {
  2087. const { BestOrWinFixBattle } = HWHClasses;
  2088. const bFix = new BestOrWinFixBattle(cloneBattle);
  2089. bFix.setNoMakeWin(noFixWin);
  2090. let endTime = Date.now() + 3e4;
  2091. if (endTime < cloneBattle.endTime) {
  2092. endTime = cloneBattle.endTime;
  2093. }
  2094. const result = await bFix.start(cloneBattle.endTime, 150);
  2095.  
  2096. if (result.result.win) {
  2097. call.args.result = result.result;
  2098. call.args.progress = result.progress;
  2099. changeRequest = true;
  2100. } else if (result.value) {
  2101. if (
  2102. await popup.confirm(I18N('DEFEAT') + '<br>' + I18N('BEST_RESULT', { value: result.value }), [
  2103. { msg: I18N('BTN_CANCEL'), result: 0 },
  2104. { msg: I18N('BTN_ACCEPT'), result: 1 },
  2105. ])
  2106. ) {
  2107. call.args.result = result.result;
  2108. call.args.progress = result.progress;
  2109. changeRequest = true;
  2110. }
  2111. }
  2112. } catch (error) {
  2113. console.error(error);
  2114. }
  2115. }
  2116.  
  2117. if (!call.args.result.win) {
  2118. let resultPopup = false;
  2119. if (call.name == 'adventure_endBattle' ||
  2120. //call.name == 'invasion_bossEnd' ||
  2121. call.name == 'bossEndBattle' ||
  2122. call.name == 'adventureSolo_endBattle') {
  2123. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2124. } else if (call.name == 'clanWarEndBattle' ||
  2125. call.name == 'crossClanWar_endBattle') {
  2126. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  2127. } else if (call.name !== 'epicBrawl_endBattle' && call.name !== 'titanArenaEndBattle') {
  2128. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  2129. }
  2130. if (resultPopup) {
  2131. if (call.name == 'invasion_bossEnd') {
  2132. this.errorRequest = true;
  2133. }
  2134. fixBattle(call.args.progress[0].attackers.heroes);
  2135. fixBattle(call.args.progress[0].defenders.heroes);
  2136. changeRequest = true;
  2137. if (resultPopup > 1) {
  2138. this.onReadySuccess = testAutoBattle;
  2139. // setTimeout(bossBattle, 1000);
  2140. }
  2141. }
  2142. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  2143. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2144. if (resultPopup) {
  2145. fixBattle(call.args.progress[0].attackers.heroes);
  2146. fixBattle(call.args.progress[0].defenders.heroes);
  2147. changeRequest = true;
  2148. if (resultPopup > 1) {
  2149. this.onReadySuccess = testAutoBattle;
  2150. }
  2151. }
  2152. }
  2153. // Потасовки
  2154. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {}
  2155. }
  2156. /**
  2157. * Save pack for Brawls
  2158. *
  2159. * Сохраняем пачку для потасовок
  2160. */
  2161. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_startBattle') {
  2162. console.log(JSON.stringify(call.args));
  2163. brawlsPack = call.args;
  2164. if (
  2165. await popup.confirm(
  2166. I18N('START_AUTO_BRAWLS'),
  2167. [
  2168. { msg: I18N('BTN_NO'), result: false },
  2169. { msg: I18N('BTN_YES'), result: true },
  2170. ],
  2171. [
  2172. {
  2173. name: 'isAuto',
  2174. label: I18N('BRAWL_AUTO_PACK'),
  2175. checked: false,
  2176. },
  2177. ]
  2178. )
  2179. ) {
  2180. isBrawlsAutoStart = true;
  2181. const isAuto = popup.getCheckBoxes().find((e) => e.name === 'isAuto');
  2182. this.errorRequest = true;
  2183. testBrawls(isAuto.checked);
  2184. }
  2185. }
  2186. /**
  2187. * Canceled fight in Asgard
  2188. * Отмена боя в Асгарде
  2189. */
  2190. if (call.name == 'clanRaid_endBossBattle' && isChecked('cancelBattle')) {
  2191. const bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  2192. let maxDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  2193. const lastDamage = maxDamage;
  2194.  
  2195. const testFunc = [];
  2196.  
  2197. if (testFuntions.masterFix) {
  2198. testFunc.push({ msg: 'masterFix', isInput: true, default: 100 });
  2199. }
  2200.  
  2201. const resultPopup = await popup.confirm(
  2202. `${I18N('MSG_YOU_APPLIED')} ${lastDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  2203. [
  2204. { msg: I18N('BTN_OK'), result: false },
  2205. { msg: I18N('BTN_AUTO_F5'), result: 1 },
  2206. { msg: I18N('BTN_TRY_FIX_IT'), result: 2 },
  2207. ...testFunc,
  2208. ],
  2209. [
  2210. {
  2211. name: 'isStat',
  2212. label: I18N('CALC_STAT'),
  2213. checked: false,
  2214. },
  2215. ]
  2216. );
  2217. if (resultPopup) {
  2218. if (resultPopup == 2) {
  2219. setProgress(I18N('LETS_FIX'), false);
  2220. await new Promise((e) => setTimeout(e, 0));
  2221. const cloneBattle = structuredClone(lastBossBattle);
  2222. const endTime = cloneBattle.endTime - 1e4;
  2223. console.log('fixBossBattleStart');
  2224.  
  2225. const { BossFixBattle } = HWHClasses;
  2226. const bFix = new BossFixBattle(cloneBattle);
  2227. const result = await bFix.start(endTime, 300);
  2228. console.log(result);
  2229.  
  2230. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2231. lastDamage: lastDamage.toLocaleString()
  2232. });
  2233. if (result.value > lastDamage) {
  2234. call.args.result = result.result;
  2235. call.args.progress = result.progress;
  2236. msgResult = I18N('DAMAGE_FIXED', {
  2237. lastDamage: lastDamage.toLocaleString(),
  2238. maxDamage: result.value.toLocaleString(),
  2239. });
  2240. }
  2241. console.log(lastDamage, '>', result.value);
  2242. setProgress(
  2243. msgResult +
  2244. '<br/>' +
  2245. I18N('COUNT_FIXED', {
  2246. count: result.maxCount,
  2247. }),
  2248. false,
  2249. hideProgress
  2250. );
  2251. } else if (resultPopup > 3) {
  2252. const cloneBattle = structuredClone(lastBossBattle);
  2253. const { masterFixBattle } = HWHClasses;
  2254. const mFix = new masterFixBattle(cloneBattle);
  2255. const result = await mFix.start(cloneBattle.endTime, resultPopup);
  2256. console.log(result);
  2257. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2258. lastDamage: lastDamage.toLocaleString(),
  2259. });
  2260. if (result.value > lastDamage) {
  2261. maxDamage = result.value;
  2262. call.args.result = result.result;
  2263. call.args.progress = result.progress;
  2264. msgResult = I18N('DAMAGE_FIXED', {
  2265. lastDamage: lastDamage.toLocaleString(),
  2266. maxDamage: maxDamage.toLocaleString(),
  2267. });
  2268. }
  2269. console.log('Урон:', lastDamage, maxDamage);
  2270. setProgress(msgResult, false, hideProgress);
  2271. } else {
  2272. fixBattle(call.args.progress[0].attackers.heroes);
  2273. fixBattle(call.args.progress[0].defenders.heroes);
  2274. }
  2275. changeRequest = true;
  2276. }
  2277. const isStat = popup.getCheckBoxes().find((e) => e.name === 'isStat');
  2278. if (isStat.checked) {
  2279. this.onReadySuccess = testBossBattle;
  2280. }
  2281. }
  2282. /**
  2283. * Save the Asgard Boss Attack Pack
  2284. * Сохраняем пачку для атаки босса Асгарда
  2285. */
  2286. if (call.name == 'clanRaid_startBossBattle') {
  2287. console.log(JSON.stringify(call.args));
  2288. }
  2289. /**
  2290. * Saving the request to start the last battle
  2291. * Сохранение запроса начала последнего боя
  2292. */
  2293. if (
  2294. call.name == 'clanWarAttack' ||
  2295. call.name == 'crossClanWar_startBattle' ||
  2296. call.name == 'adventure_turnStartBattle' ||
  2297. call.name == 'adventureSolo_turnStartBattle' ||
  2298. call.name == 'bossAttack' ||
  2299. call.name == 'invasion_bossStart' ||
  2300. call.name == 'towerStartBattle'
  2301. ) {
  2302. nameFuncStartBattle = call.name;
  2303. lastBattleArg = call.args;
  2304.  
  2305. if (call.name == 'invasion_bossStart') {
  2306. const timePassed = Date.now() - lastBossBattleStart;
  2307. if (timePassed < invasionTimer) {
  2308. await new Promise((e) => setTimeout(e, invasionTimer - timePassed));
  2309. }
  2310. invasionTimer -= 1;
  2311. }
  2312. lastBossBattleStart = Date.now();
  2313. }
  2314. if (call.name == 'invasion_bossEnd') {
  2315. const lastBattle = lastBattleInfo;
  2316. if (lastBattle && call.args.result.win) {
  2317. lastBattle.progress = call.args.progress;
  2318. const result = await Calc(lastBattle);
  2319. let timer = getTimer(result.battleTime, 1) + addBattleTimer;
  2320. const period = Math.ceil((Date.now() - lastBossBattleStart) / 1000);
  2321. console.log(timer, period);
  2322. if (period < timer) {
  2323. timer = timer - period;
  2324. await countdownTimer(timer);
  2325. }
  2326. }
  2327. }
  2328. /**
  2329. * Disable spending divination cards
  2330. * Отключить трату карт предсказаний
  2331. */
  2332. if (call.name == 'dungeonEndBattle') {
  2333. if (call.args.isRaid) {
  2334. if (countPredictionCard <= 0) {
  2335. delete call.args.isRaid;
  2336. changeRequest = true;
  2337. } else if (countPredictionCard > 0) {
  2338. countPredictionCard--;
  2339. }
  2340. }
  2341. console.log(`Cards: ${countPredictionCard}`);
  2342. /**
  2343. * Fix endless cards
  2344. * Исправление бесконечных карт
  2345. */
  2346. const lastBattle = lastDungeonBattleData;
  2347. if (lastBattle && !call.args.isRaid) {
  2348. if (changeRequest) {
  2349. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2350. } else {
  2351. lastBattle.progress = call.args.progress;
  2352. }
  2353. const result = await Calc(lastBattle);
  2354.  
  2355. if (changeRequest) {
  2356. call.args.progress = result.progress;
  2357. call.args.result = result.result;
  2358. }
  2359. let timer = result.battleTimer + addBattleTimer;
  2360. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  2361. console.log(timer, period);
  2362. if (period < timer) {
  2363. timer = timer - period;
  2364. await countdownTimer(timer);
  2365. }
  2366. }
  2367. }
  2368. /**
  2369. * Quiz Answer
  2370. * Ответ на викторину
  2371. */
  2372. if (call.name == 'quizAnswer') {
  2373. /**
  2374. * Automatically changes the answer to the correct one if there is one.
  2375. * Автоматически меняет ответ на правильный если он есть
  2376. */
  2377. if (lastAnswer && isChecked('getAnswer')) {
  2378. call.args.answerId = lastAnswer;
  2379. lastAnswer = null;
  2380. changeRequest = true;
  2381. }
  2382. }
  2383. /**
  2384. * Present
  2385. * Подарки
  2386. */
  2387. if (call.name == 'freebieCheck') {
  2388. freebieCheckInfo = call;
  2389. }
  2390. /** missionTimer */
  2391. if (call.name == 'missionEnd' && missionBattle) {
  2392. let startTimer = false;
  2393. if (!call.args.result.win) {
  2394. startTimer = await popup.confirm(I18N('DEFEAT_TURN_TIMER'), [
  2395. { msg: I18N('BTN_NO'), result: false },
  2396. { msg: I18N('BTN_YES'), result: true },
  2397. ]);
  2398. }
  2399.  
  2400. if (call.args.result.win || startTimer) {
  2401. missionBattle.progress = call.args.progress;
  2402. missionBattle.result = call.args.result;
  2403. const result = await Calc(missionBattle);
  2404.  
  2405. let timer = result.battleTimer + addBattleTimer;
  2406. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  2407. if (period < timer) {
  2408. timer = timer - period;
  2409. await countdownTimer(timer);
  2410. }
  2411. missionBattle = null;
  2412. } else {
  2413. this.errorRequest = true;
  2414. }
  2415. }
  2416. /**
  2417. * Getting mission data for auto-repeat
  2418. * Получение данных миссии для автоповтора
  2419. */
  2420. if (isChecked('repeatMission') &&
  2421. call.name == 'missionEnd') {
  2422. let missionInfo = {
  2423. id: call.args.id,
  2424. result: call.args.result,
  2425. heroes: call.args.progress[0].attackers.heroes,
  2426. count: 0,
  2427. }
  2428. setTimeout(async () => {
  2429. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2430. { msg: I18N('BTN_REPEAT'), result: true},
  2431. { msg: I18N('BTN_NO'), result: false},
  2432. ])) {
  2433. isStopSendMission = false;
  2434. isSendsMission = true;
  2435. sendsMission(missionInfo);
  2436. }
  2437. }, 0);
  2438. }
  2439. /**
  2440. * Getting mission data
  2441. * Получение данных миссии
  2442. * missionTimer
  2443. */
  2444. if (call.name == 'missionStart') {
  2445. lastMissionStart = call.args;
  2446. lastMissionBattleStart = Date.now();
  2447. }
  2448. /**
  2449. * Specify the quantity for Titan Orbs and Pet Eggs
  2450. * Указать количество для сфер титанов и яиц петов
  2451. */
  2452. if (isChecked('countControl') &&
  2453. (call.name == 'pet_chestOpen' ||
  2454. call.name == 'titanUseSummonCircle') &&
  2455. call.args.amount > 1) {
  2456. const startAmount = call.args.amount;
  2457. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2458. { msg: I18N('BTN_OPEN'), isInput: true, default: 1},
  2459. ]);
  2460. if (result) {
  2461. const item = call.name == 'pet_chestOpen' ? { id: 90, type: 'consumable' } : { id: 13, type: 'coin' };
  2462. cheats.updateInventory({
  2463. [item.type]: {
  2464. [item.id]: -(result - startAmount),
  2465. },
  2466. });
  2467. call.args.amount = result;
  2468. changeRequest = true;
  2469. }
  2470. }
  2471. /**
  2472. * Specify the amount for keys and spheres of titan artifacts
  2473. * Указать колличество для ключей и сфер артефактов титанов
  2474. */
  2475. if (isChecked('countControl') &&
  2476. (call.name == 'artifactChestOpen' ||
  2477. call.name == 'titanArtifactChestOpen') &&
  2478. call.args.amount > 1 &&
  2479. call.args.free &&
  2480. !changeRequest) {
  2481. artifactChestOpenCallName = call.name;
  2482. const startAmount = call.args.amount;
  2483. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2484. { msg: I18N('BTN_OPEN'), isInput: true, default: 1 },
  2485. ]);
  2486. if (result) {
  2487. const openChests = result;
  2488. let sphere = result < 10 ? 1 : 10;
  2489. call.args.amount = sphere;
  2490. for (let count = openChests - sphere; count > 0; count -= sphere) {
  2491. if (count < 10) sphere = 1;
  2492. const ident = artifactChestOpenCallName + "_" + count;
  2493. testData.calls.push({
  2494. name: artifactChestOpenCallName,
  2495. args: {
  2496. amount: sphere,
  2497. free: true,
  2498. },
  2499. ident: ident
  2500. });
  2501. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2502. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2503. }
  2504. requestHistory[this.uniqid].calls[call.name].push(ident);
  2505. }
  2506.  
  2507. const consumableId = call.name == 'artifactChestOpen' ? 45 : 55;
  2508. cheats.updateInventory({
  2509. consumable: {
  2510. [consumableId]: -(openChests - startAmount),
  2511. },
  2512. });
  2513. artifactChestOpen = true;
  2514. changeRequest = true;
  2515. }
  2516. }
  2517. if (call.name == 'consumableUseLootBox') {
  2518. lastRussianDollId = call.args.libId;
  2519. /**
  2520. * Specify quantity for gold caskets
  2521. * Указать количество для золотых шкатулок
  2522. */
  2523. if (isChecked('countControl') &&
  2524. call.args.libId == 148 &&
  2525. call.args.amount > 1) {
  2526. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2527. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2528. ]);
  2529. call.args.amount = result;
  2530. changeRequest = true;
  2531. }
  2532. if (isChecked('countControl') && call.args.libId >= 362 && call.args.libId <= 389) {
  2533. this.massOpen = call.args.libId;
  2534. }
  2535. }
  2536. if (call.name == 'invasion_bossStart' && isChecked('tryFixIt_v2') && call.args.id == invasionInfo.id) {
  2537. const pack = invasionDataPacks[invasionInfo.bossLvl];
  2538. if (pack) {
  2539. if (pack.buff != invasionInfo.buff) {
  2540. setProgress(
  2541. I18N('INVASION_BOSS_BUFF', {
  2542. bossLvl: invasionInfo.bossLvl,
  2543. needBuff: pack.buff,
  2544. haveBuff: invasionInfo.buff,
  2545. }),
  2546. false
  2547. );
  2548. } else {
  2549. call.args.pet = pack.pet;
  2550. call.args.heroes = pack.heroes;
  2551. call.args.favor = pack.favor;
  2552. changeRequest = true;
  2553. }
  2554. }
  2555. }
  2556. if (call.name == 'workshopBuff_create') {
  2557. const pack = invasionDataPacks[invasionInfo.bossLvl];
  2558. if (pack) {
  2559. const addBuff = call.args.amount * 5;
  2560. if (pack.buff < addBuff + invasionInfo.buff) {
  2561. this.errorRequest = true;
  2562. }
  2563. setProgress(
  2564. I18N('INVASION_BOSS_BUFF', {
  2565. bossLvl: invasionInfo.bossLvl,
  2566. needBuff: pack.buff,
  2567. haveBuff: invasionInfo.buff,
  2568. }),
  2569. false
  2570. );
  2571. }
  2572. }
  2573. /**
  2574. * Changing the maximum number of raids in the campaign
  2575. * Изменение максимального количества рейдов в кампании
  2576. */
  2577. // if (call.name == 'missionRaid') {
  2578. // if (isChecked('countControl') && call.args.times > 1) {
  2579. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2580. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2581. // ]));
  2582. // call.args.times = result > call.args.times ? call.args.times : result;
  2583. // changeRequest = true;
  2584. // }
  2585. // }
  2586. }
  2587.  
  2588. let headers = requestHistory[this.uniqid].headers;
  2589. if (changeRequest) {
  2590. sourceData = JSON.stringify(testData);
  2591. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2592. }
  2593.  
  2594. let signature = headers['X-Auth-Signature'];
  2595. if (signature) {
  2596. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2597. }
  2598. } catch (err) {
  2599. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2600. }
  2601. return sourceData;
  2602. }
  2603. /**
  2604. * Processing and substitution of incoming data
  2605. *
  2606. * Обработка и подмена входящих данных
  2607. */
  2608. async function checkChangeResponse(response) {
  2609. try {
  2610. isChange = false;
  2611. let nowTime = Math.round(Date.now() / 1000);
  2612. callsIdent = requestHistory[this.uniqid].calls;
  2613. respond = JSON.parse(response);
  2614. /**
  2615. * If the request returned an error removes the error (removes synchronization errors)
  2616. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2617. */
  2618. if (respond.error) {
  2619. isChange = true;
  2620. console.error(respond.error);
  2621. if (isChecked('showErrors')) {
  2622. popup.confirm(I18N('ERROR_MSG', {
  2623. name: respond.error.name,
  2624. description: respond.error.description,
  2625. }));
  2626. }
  2627. if (respond.error.name != 'AccountBan') {
  2628. delete respond.error;
  2629. respond.results = [];
  2630. }
  2631. }
  2632. let mainReward = null;
  2633. const allReward = {};
  2634. let countTypeReward = 0;
  2635. let readQuestInfo = false;
  2636. for (const call of respond.results) {
  2637. /**
  2638. * Obtaining initial data for completing quests
  2639. * Получение исходных данных для выполнения квестов
  2640. */
  2641. if (readQuestInfo) {
  2642. questsInfo[call.ident] = call.result.response;
  2643. }
  2644. /**
  2645. * Getting a user ID
  2646. * Получение идетификатора пользователя
  2647. */
  2648. if (call.ident == callsIdent['registration']) {
  2649. userId = call.result.response.userId;
  2650. if (localStorage['userId'] != userId) {
  2651. localStorage['newGiftSendIds'] = '';
  2652. localStorage['userId'] = userId;
  2653. }
  2654. await openOrMigrateDatabase(userId);
  2655. readQuestInfo = true;
  2656. }
  2657. /**
  2658. * Hiding donation offers 1
  2659. * Скрываем предложения доната 1
  2660. */
  2661. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2662. const billings = call.result.response?.billings;
  2663. const bundle = call.result.response?.bundle;
  2664. if (billings && bundle) {
  2665. call.result.response.billings = call.result.response.billings.filter((e) => ['repeatableOffer'].includes(e.type));
  2666. call.result.response.bundle = [];
  2667. isChange = true;
  2668. }
  2669. }
  2670. /**
  2671. * Hiding donation offers 2
  2672. * Скрываем предложения доната 2
  2673. */
  2674. if (getSaveVal('noOfferDonat') &&
  2675. (call.ident == callsIdent['offerGetAll'] ||
  2676. call.ident == callsIdent['specialOffer_getAll'])) {
  2677. let offers = call.result.response;
  2678. if (offers) {
  2679. call.result.response = offers.filter(
  2680. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2681. );
  2682. isChange = true;
  2683. }
  2684. }
  2685. /**
  2686. * Hiding donation offers 3
  2687. * Скрываем предложения доната 3
  2688. */
  2689. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2690. delete call.result.bundleUpdate;
  2691. isChange = true;
  2692. }
  2693. /**
  2694. * Hiding donation offers 4
  2695. * Скрываем предложения доната 4
  2696. */
  2697. if (call.result?.specialOffers) {
  2698. const offers = call.result.specialOffers;
  2699. call.result.specialOffers = offers.filter(
  2700. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2701. );
  2702. isChange = true;
  2703. }
  2704. /**
  2705. * Copies a quiz question to the clipboard
  2706. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2707. */
  2708. if (call.ident == callsIdent['quizGetNewQuestion']) {
  2709. let quest = call.result.response;
  2710. console.log(quest.question);
  2711. copyText(quest.question);
  2712. setProgress(I18N('QUESTION_COPY'), true);
  2713. quest.lang = null;
  2714. if (typeof NXFlashVars !== 'undefined') {
  2715. quest.lang = NXFlashVars.interface_lang;
  2716. }
  2717. lastQuestion = quest;
  2718. if (isChecked('getAnswer')) {
  2719. const answer = await getAnswer(lastQuestion);
  2720. let showText = '';
  2721. if (answer) {
  2722. lastAnswer = answer;
  2723. console.log(answer);
  2724. showText = `${I18N('ANSWER_KNOWN')}: ${answer}`;
  2725. } else {
  2726. showText = I18N('ANSWER_NOT_KNOWN');
  2727. }
  2728.  
  2729. try {
  2730. const hint = hintQuest(quest);
  2731. if (hint) {
  2732. showText += I18N('HINT') + hint;
  2733. }
  2734. } catch(e) {}
  2735.  
  2736. setProgress(showText, true);
  2737. }
  2738. }
  2739. /**
  2740. * Submits a question with an answer to the database
  2741. * Отправляет вопрос с ответом в базу данных
  2742. */
  2743. if (call.ident == callsIdent['quizAnswer']) {
  2744. const answer = call.result.response;
  2745. if (lastQuestion) {
  2746. const answerInfo = {
  2747. answer,
  2748. question: lastQuestion,
  2749. lang: null,
  2750. }
  2751. if (typeof NXFlashVars !== 'undefined') {
  2752. answerInfo.lang = NXFlashVars.interface_lang;
  2753. }
  2754. lastQuestion = null;
  2755. setTimeout(sendAnswerInfo, 0, answerInfo);
  2756. }
  2757. }
  2758. /**
  2759. * Get user data
  2760. * Получить даныне пользователя
  2761. */
  2762. if (call.ident == callsIdent['userGetInfo']) {
  2763. let user = call.result.response;
  2764. document.title = user.name;
  2765. userInfo = Object.assign({}, user);
  2766. delete userInfo.refillable;
  2767. if (!questsInfo['userGetInfo']) {
  2768. questsInfo['userGetInfo'] = user;
  2769. }
  2770. }
  2771. /**
  2772. * Start of the battle for recalculation
  2773. * Начало боя для прерасчета
  2774. */
  2775. if (call.ident == callsIdent['clanWarAttack'] ||
  2776. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2777. call.ident == callsIdent['bossAttack'] ||
  2778. call.ident == callsIdent['battleGetReplay'] ||
  2779. call.ident == callsIdent['brawl_startBattle'] ||
  2780. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2781. call.ident == callsIdent['invasion_bossStart'] ||
  2782. call.ident == callsIdent['titanArenaStartBattle'] ||
  2783. call.ident == callsIdent['towerStartBattle'] ||
  2784. call.ident == callsIdent['epicBrawl_startBattle'] ||
  2785. call.ident == callsIdent['adventure_turnStartBattle']) {
  2786. let battle = call.result.response.battle || call.result.response.replay;
  2787. if (call.ident == callsIdent['brawl_startBattle'] ||
  2788. call.ident == callsIdent['bossAttack'] ||
  2789. call.ident == callsIdent['towerStartBattle'] ||
  2790. call.ident == callsIdent['invasion_bossStart']) {
  2791. battle = call.result.response;
  2792. }
  2793. lastBattleInfo = battle;
  2794. if (call.ident == callsIdent['battleGetReplay'] && call.result.response.replay.type === "clan_raid") {
  2795. if (call?.result?.response?.replay?.result?.damage) {
  2796. const damages = Object.values(call.result.response.replay.result.damage);
  2797. const bossDamage = damages.reduce((a, v) => a + v, 0);
  2798. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2799. continue;
  2800. }
  2801. }
  2802. if (!isChecked('preCalcBattle')) {
  2803. continue;
  2804. }
  2805. const preCalcBattle = structuredClone(battle);
  2806. setProgress(I18N('BEING_RECALC'));
  2807. let battleDuration = 120;
  2808. try {
  2809. const typeBattle = getBattleType(preCalcBattle.type);
  2810. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2811. } catch (e) { }
  2812. //console.log(battle.type);
  2813. function getBattleInfo(battle, isRandSeed) {
  2814. return new Promise(function (resolve) {
  2815. if (isRandSeed) {
  2816. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2817. }
  2818. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2819. });
  2820. }
  2821. let actions = [getBattleInfo(preCalcBattle, false)];
  2822. let countTestBattle = getInput('countTestBattle');
  2823. if (call.ident == callsIdent['invasion_bossStart'] ) {
  2824. countTestBattle = 0;
  2825. }
  2826. if (call.ident == callsIdent['battleGetReplay']) {
  2827. preCalcBattle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', 0, 0] } }];
  2828. }
  2829. for (let i = 0; i < countTestBattle; i++) {
  2830. actions.push(getBattleInfo(preCalcBattle, true));
  2831. }
  2832. Promise.all(actions)
  2833. .then(e => {
  2834. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2835. let firstBattle = e.shift();
  2836. const timer = Math.floor(battleDuration - firstBattle.time);
  2837. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2838. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2839. let msg = `${I18N('THIS_TIME')} ${firstBattle.win ? I18N('VICTORY') : I18N('DEFEAT')}`;
  2840. if (e.length) {
  2841. const countWin = e.reduce((w, s) => w + s.win, 0);
  2842. msg += ` ${I18N('CHANCE_TO_WIN')}: ${Math.floor((countWin / e.length) * 100)}% (${e.length})`;
  2843. }
  2844. msg += `, ${min}:${sec}`
  2845. setProgress(msg, false, hideProgress)
  2846. });
  2847. }
  2848. /**
  2849. * Start of the Asgard boss fight
  2850. * Начало боя с боссом Асгарда
  2851. */
  2852. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2853. lastBossBattle = call.result.response.battle;
  2854. lastBossBattle.endTime = Date.now() + 160 * 1000;
  2855. if (isChecked('preCalcBattle')) {
  2856. const result = await Calc(lastBossBattle).then(e => e.progress[0].defenders.heroes[1].extra);
  2857. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2858. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2859. }
  2860. }
  2861. /**
  2862. * Cancel tutorial
  2863. * Отмена туториала
  2864. */
  2865. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2866. let chains = call.result.response.chains;
  2867. for (let n in chains) {
  2868. chains[n] = 9999;
  2869. }
  2870. isChange = true;
  2871. }
  2872. /**
  2873. * Opening keys and spheres of titan artifacts
  2874. * Открытие ключей и сфер артефактов титанов
  2875. */
  2876. if (artifactChestOpen &&
  2877. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2878. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2879. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2880.  
  2881. reward.forEach(e => {
  2882. for (let f in e) {
  2883. if (!allReward[f]) {
  2884. allReward[f] = {};
  2885. }
  2886. for (let o in e[f]) {
  2887. if (!allReward[f][o]) {
  2888. allReward[f][o] = e[f][o];
  2889. countTypeReward++;
  2890. } else {
  2891. allReward[f][o] += e[f][o];
  2892. }
  2893. }
  2894. }
  2895. });
  2896.  
  2897. if (!call.ident.includes(artifactChestOpenCallName)) {
  2898. mainReward = call.result.response;
  2899. }
  2900. }
  2901.  
  2902. if (countTypeReward > 20) {
  2903. correctShowOpenArtifact = 3;
  2904. } else {
  2905. correctShowOpenArtifact = 0;
  2906. }
  2907. /**
  2908. * Sum the result of opening Pet Eggs
  2909. * Суммирование результата открытия яиц питомцев
  2910. */
  2911. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2912. const rewards = call.result.response.rewards;
  2913. if (rewards.length > 10) {
  2914. /**
  2915. * Removing pet cards
  2916. * Убираем карточки петов
  2917. */
  2918. for (const reward of rewards) {
  2919. if (reward.petCard) {
  2920. delete reward.petCard;
  2921. }
  2922. }
  2923. }
  2924. rewards.forEach(e => {
  2925. for (let f in e) {
  2926. if (!allReward[f]) {
  2927. allReward[f] = {};
  2928. }
  2929. for (let o in e[f]) {
  2930. if (!allReward[f][o]) {
  2931. allReward[f][o] = e[f][o];
  2932. } else {
  2933. allReward[f][o] += e[f][o];
  2934. }
  2935. }
  2936. }
  2937. });
  2938. call.result.response.rewards = [allReward];
  2939. isChange = true;
  2940. }
  2941. /**
  2942. * Removing titan cards
  2943. * Убираем карточки титанов
  2944. */
  2945. if (call.ident == callsIdent['titanUseSummonCircle']) {
  2946. if (call.result.response.rewards.length > 10) {
  2947. for (const reward of call.result.response.rewards) {
  2948. if (reward.titanCard) {
  2949. delete reward.titanCard;
  2950. }
  2951. }
  2952. isChange = true;
  2953. }
  2954. }
  2955. /**
  2956. * Auto-repeat opening matryoshkas
  2957. * АвтоПовтор открытия матрешек
  2958. */
  2959. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2960. let [countLootBox, lootBox] = Object.entries(call.result.response).pop();
  2961. countLootBox = +countLootBox;
  2962. let newCount = 0;
  2963. if (lootBox?.consumable && lootBox.consumable[lastRussianDollId]) {
  2964. newCount += lootBox.consumable[lastRussianDollId];
  2965. delete lootBox.consumable[lastRussianDollId];
  2966. }
  2967. if (
  2968. newCount &&
  2969. (await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2970. { msg: I18N('BTN_OPEN'), result: true },
  2971. { msg: I18N('BTN_NO'), result: false, isClose: true },
  2972. ]))
  2973. ) {
  2974. const [count, recursionResult] = await openRussianDolls(lastRussianDollId, newCount);
  2975. countLootBox += +count;
  2976. mergeItemsObj(lootBox, recursionResult);
  2977. isChange = true;
  2978. }
  2979.  
  2980. if (this.massOpen) {
  2981. if (
  2982. await popup.confirm(I18N('OPEN_ALL_EQUIP_BOXES'), [
  2983. { msg: I18N('BTN_OPEN'), result: true },
  2984. { msg: I18N('BTN_NO'), result: false, isClose: true },
  2985. ])
  2986. ) {
  2987. const consumable = await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'inventoryGet' }] }).then((e) =>
  2988. Object.entries(e.results[0].result.response.consumable)
  2989. );
  2990. const calls = [];
  2991. const deleteItems = {};
  2992. for (const [libId, amount] of consumable) {
  2993. if (libId != this.massOpen && libId >= 362 && libId <= 389) {
  2994. calls.push({
  2995. name: 'consumableUseLootBox',
  2996. args: { libId, amount },
  2997. ident: 'consumableUseLootBox_' + libId,
  2998. });
  2999. deleteItems[libId] = -amount;
  3000. }
  3001. }
  3002. const responses = await Send({ calls }).then((e) => e.results.map((r) => r.result.response).flat());
  3003.  
  3004. for (const loot of responses) {
  3005. const [count, result] = Object.entries(loot).pop();
  3006. countLootBox += +count;
  3007.  
  3008. mergeItemsObj(lootBox, result);
  3009. }
  3010. isChange = true;
  3011.  
  3012. this.onReadySuccess = () => {
  3013. cheats.updateInventory({ consumable: deleteItems });
  3014. cheats.refreshInventory();
  3015. };
  3016. }
  3017. }
  3018.  
  3019. if (isChange) {
  3020. call.result.response = {
  3021. [countLootBox]: lootBox,
  3022. };
  3023. }
  3024. }
  3025. /**
  3026. * Dungeon recalculation (fix endless cards)
  3027. * Прерасчет подземки (исправление бесконечных карт)
  3028. */
  3029. if (call.ident == callsIdent['dungeonStartBattle']) {
  3030. lastDungeonBattleData = call.result.response;
  3031. lastDungeonBattleStart = Date.now();
  3032. }
  3033. /**
  3034. * Getting the number of prediction cards
  3035. * Получение количества карт предсказаний
  3036. */
  3037. if (call.ident == callsIdent['inventoryGet']) {
  3038. countPredictionCard = call.result.response.consumable[81] || 0;
  3039. }
  3040. /**
  3041. * Getting subscription status
  3042. * Получение состояния подписки
  3043. */
  3044. if (call.ident == callsIdent['subscriptionGetInfo']) {
  3045. const subscription = call.result.response.subscription;
  3046. if (subscription) {
  3047. subEndTime = subscription.endTime * 1000;
  3048. }
  3049. }
  3050. /**
  3051. * Getting prediction cards
  3052. * Получение карт предсказаний
  3053. */
  3054. if (call.ident == callsIdent['questFarm']) {
  3055. const consumable = call.result.response?.consumable;
  3056. if (consumable && consumable[81]) {
  3057. countPredictionCard += consumable[81];
  3058. console.log(`Cards: ${countPredictionCard}`);
  3059. }
  3060. }
  3061. /**
  3062. * Hiding extra servers
  3063. * Скрытие лишних серверов
  3064. */
  3065. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  3066. let servers = call.result.response.users.map(s => s.serverId)
  3067. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  3068. isChange = true;
  3069. }
  3070. /**
  3071. * Displays player positions in the adventure
  3072. * Отображает позиции игроков в приключении
  3073. */
  3074. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  3075. const users = Object.values(call.result.response.users);
  3076. const mapIdent = call.result.response.mapIdent;
  3077. const adventureId = call.result.response.adventureId;
  3078. const maps = {
  3079. adv_strongford_3pl_hell: 9,
  3080. adv_valley_3pl_hell: 10,
  3081. adv_ghirwil_3pl_hell: 11,
  3082. adv_angels_3pl_hell: 12,
  3083. }
  3084. let msg = I18N('MAP') + (mapIdent in maps ? maps[mapIdent] : adventureId);
  3085. msg += '<br>' + I18N('PLAYER_POS');
  3086. for (const user of users) {
  3087. msg += `<br>${user.user.name} - ${user.currentNode}`;
  3088. }
  3089. setProgress(msg, false, hideProgress);
  3090. }
  3091. /**
  3092. * Automatic launch of a raid at the end of the adventure
  3093. * Автоматический запуск рейда при окончании приключения
  3094. */
  3095. if (call.ident == callsIdent['adventure_end']) {
  3096. autoRaidAdventure()
  3097. }
  3098. /** Удаление лавки редкостей */
  3099. if (call.ident == callsIdent['missionRaid']) {
  3100. if (call.result?.heroesMerchant) {
  3101. delete call.result.heroesMerchant;
  3102. isChange = true;
  3103. }
  3104. }
  3105. /** missionTimer */
  3106. if (call.ident == callsIdent['missionStart']) {
  3107. missionBattle = call.result.response;
  3108. }
  3109. /** Награды турнира стихий */
  3110. if (call.ident == callsIdent['hallOfFameGetTrophies']) {
  3111. const trophys = call.result.response;
  3112. const calls = [];
  3113. for (const week in trophys) {
  3114. const trophy = trophys[week];
  3115. if (!trophy.championRewardFarmed) {
  3116. calls.push({
  3117. name: 'hallOfFameFarmTrophyReward',
  3118. args: { trophyId: week, rewardType: 'champion' },
  3119. ident: 'body_champion_' + week,
  3120. });
  3121. }
  3122. if (Object.keys(trophy.clanReward).length && !trophy.clanRewardFarmed) {
  3123. calls.push({
  3124. name: 'hallOfFameFarmTrophyReward',
  3125. args: { trophyId: week, rewardType: 'clan' },
  3126. ident: 'body_clan_' + week,
  3127. });
  3128. }
  3129. }
  3130. if (calls.length) {
  3131. Send({ calls })
  3132. .then((e) => e.results.map((e) => e.result.response))
  3133. .then(async results => {
  3134. let coin18 = 0,
  3135. coin19 = 0,
  3136. gold = 0,
  3137. starmoney = 0;
  3138. for (const r of results) {
  3139. coin18 += r?.coin ? +r.coin[18] : 0;
  3140. coin19 += r?.coin ? +r.coin[19] : 0;
  3141. gold += r?.gold ? +r.gold : 0;
  3142. starmoney += r?.starmoney ? +r.starmoney : 0;
  3143. }
  3144.  
  3145. let msg = I18N('ELEMENT_TOURNAMENT_REWARD') + '<br>';
  3146. if (coin18) {
  3147. msg += cheats.translate('LIB_COIN_NAME_18') + `: ${coin18}<br>`;
  3148. }
  3149. if (coin19) {
  3150. msg += cheats.translate('LIB_COIN_NAME_19') + `: ${coin19}<br>`;
  3151. }
  3152. if (gold) {
  3153. msg += cheats.translate('LIB_PSEUDO_COIN') + `: ${gold}<br>`;
  3154. }
  3155. if (starmoney) {
  3156. msg += cheats.translate('LIB_PSEUDO_STARMONEY') + `: ${starmoney}<br>`;
  3157. }
  3158.  
  3159. await popup.confirm(msg, [{ msg: I18N('BTN_OK'), result: 0 }]);
  3160. });
  3161. }
  3162. }
  3163. if (call.ident == callsIdent['clanDomination_getInfo']) {
  3164. clanDominationGetInfo = call.result.response;
  3165. }
  3166. if (call.ident == callsIdent['clanRaid_endBossBattle']) {
  3167. console.log(call.result.response);
  3168. const damage = Object.values(call.result.response.damage).reduce((a, e) => a + e);
  3169. if (call.result.response.result.afterInvalid) {
  3170. addProgress('<br>' + I18N('SERVER_NOT_ACCEPT'));
  3171. }
  3172. addProgress('<br>Server > ' + I18N('BOSS_DAMAGE') + damage.toLocaleString());
  3173. }
  3174. if (call.ident == callsIdent['invasion_getInfo']) {
  3175. const r = call.result.response;
  3176. if (r?.actions?.length) {
  3177. const boss = r.actions.find((e) => e.payload.id === invasionInfo.id);
  3178. if (boss) {
  3179. invasionInfo.buff = r.buffAmount;
  3180. invasionInfo.bossLvl = boss.payload.level;
  3181. if (isChecked('tryFixIt_v2')) {
  3182. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3183. if (pack) {
  3184. setProgress(
  3185. I18N('INVASION_BOSS_BUFF', {
  3186. bossLvl: invasionInfo.bossLvl,
  3187. needBuff: pack.buff,
  3188. haveBuff: invasionInfo.buff,
  3189. }),
  3190. false
  3191. );
  3192. }
  3193. }
  3194. }
  3195. }
  3196. }
  3197. if (call.ident == callsIdent['workshopBuff_create']) {
  3198. const r = call.result.response;
  3199. if (r.id == 1) {
  3200. invasionInfo.buff = r.amount;
  3201. if (isChecked('tryFixIt_v2')) {
  3202. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3203. if (pack) {
  3204. setProgress(
  3205. I18N('INVASION_BOSS_BUFF', {
  3206. bossLvl: invasionInfo.bossLvl,
  3207. needBuff: pack.buff,
  3208. haveBuff: invasionInfo.buff,
  3209. }),
  3210. false
  3211. );
  3212. }
  3213. }
  3214. }
  3215. }
  3216. /*
  3217. if (call.ident == callsIdent['chatGetAll'] && call.args.chatType == 'clanDomination' && !callsIdent['clanDomination_mapState']) {
  3218. this.onReadySuccess = async function () {
  3219. const result = await Send({
  3220. calls: [
  3221. {
  3222. name: 'clanDomination_mapState',
  3223. args: {},
  3224. ident: 'clanDomination_mapState',
  3225. },
  3226. ],
  3227. }).then((e) => e.results[0].result.response);
  3228. let townPositions = result.townPositions;
  3229. let positions = {};
  3230. for (let pos in townPositions) {
  3231. let townPosition = townPositions[pos];
  3232. positions[townPosition.position] = townPosition;
  3233. }
  3234. Object.assign(clanDominationGetInfo, {
  3235. townPositions: positions,
  3236. });
  3237. let userPositions = result.userPositions;
  3238. for (let pos in clanDominationGetInfo.townPositions) {
  3239. let townPosition = clanDominationGetInfo.townPositions[pos];
  3240. if (townPosition.status) {
  3241. userPositions[townPosition.userId] = +pos;
  3242. }
  3243. }
  3244. cheats.updateMap(result);
  3245. };
  3246. }
  3247. if (call.ident == callsIdent['clanDomination_mapState']) {
  3248. const townPositions = call.result.response.townPositions;
  3249. const userPositions = call.result.response.userPositions;
  3250. for (let pos in townPositions) {
  3251. let townPos = townPositions[pos];
  3252. if (townPos.status) {
  3253. userPositions[townPos.userId] = townPos.position;
  3254. }
  3255. }
  3256. isChange = true;
  3257. }
  3258. */
  3259. }
  3260.  
  3261. if (mainReward && artifactChestOpen) {
  3262. console.log(allReward);
  3263. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  3264. artifactChestOpen = false;
  3265. artifactChestOpenCallName = '';
  3266. isChange = true;
  3267. }
  3268. } catch(err) {
  3269. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  3270. }
  3271.  
  3272. if (isChange) {
  3273. Object.defineProperty(this, 'responseText', {
  3274. writable: true
  3275. });
  3276. this.responseText = JSON.stringify(respond);
  3277. }
  3278. }
  3279.  
  3280. /**
  3281. * Request an answer to a question
  3282. *
  3283. * Запрос ответа на вопрос
  3284. */
  3285. async function getAnswer(question) {
  3286. // c29tZSBzdHJhbmdlIHN5bWJvbHM=
  3287. const quizAPI = new ZingerYWebsiteAPI('getAnswer.php', arguments, { question });
  3288. return new Promise((resolve, reject) => {
  3289. quizAPI.request().then((data) => {
  3290. if (data.result) {
  3291. resolve(data.result);
  3292. } else {
  3293. resolve(false);
  3294. }
  3295. }).catch((error) => {
  3296. console.error(error);
  3297. resolve(false);
  3298. });
  3299. })
  3300. }
  3301.  
  3302. /**
  3303. * Submitting a question and answer to a database
  3304. *
  3305. * Отправка вопроса и ответа в базу данных
  3306. */
  3307. function sendAnswerInfo(answerInfo) {
  3308. // c29tZSBub25zZW5zZQ==
  3309. const quizAPI = new ZingerYWebsiteAPI('setAnswer.php', arguments, { answerInfo });
  3310. quizAPI.request().then((data) => {
  3311. if (data.result) {
  3312. console.log(I18N('SENT_QUESTION'));
  3313. }
  3314. });
  3315. }
  3316.  
  3317. /**
  3318. * Returns the battle type by preset type
  3319. *
  3320. * Возвращает тип боя по типу пресета
  3321. */
  3322. function getBattleType(strBattleType) {
  3323. if (!strBattleType) {
  3324. return null;
  3325. }
  3326. switch (strBattleType) {
  3327. case 'titan_pvp':
  3328. return 'get_titanPvp';
  3329. case 'titan_pvp_manual':
  3330. case 'titan_clan_pvp':
  3331. case 'clan_pvp_titan':
  3332. case 'clan_global_pvp_titan':
  3333. case 'brawl_titan':
  3334. case 'challenge_titan':
  3335. case 'titan_mission':
  3336. return 'get_titanPvpManual';
  3337. case 'clan_raid': // Asgard Boss // Босс асгарда
  3338. case 'adventure': // Adventures // Приключения
  3339. case 'clan_global_pvp':
  3340. case 'epic_brawl':
  3341. case 'clan_pvp':
  3342. return 'get_clanPvp';
  3343. case 'dungeon_titan':
  3344. case 'titan_tower':
  3345. return 'get_titan';
  3346. case 'tower':
  3347. case 'clan_dungeon':
  3348. return 'get_tower';
  3349. case 'pve':
  3350. case 'mission':
  3351. return 'get_pve';
  3352. case 'mission_boss':
  3353. return 'get_missionBoss';
  3354. case 'challenge':
  3355. case 'pvp_manual':
  3356. return 'get_pvpManual';
  3357. case 'grand':
  3358. case 'arena':
  3359. case 'pvp':
  3360. case 'clan_domination':
  3361. return 'get_pvp';
  3362. case 'core':
  3363. return 'get_core';
  3364. default: {
  3365. if (strBattleType.includes('invasion')) {
  3366. return 'get_invasion';
  3367. }
  3368. if (strBattleType.includes('boss')) {
  3369. return 'get_boss';
  3370. }
  3371. if (strBattleType.includes('titan_arena')) {
  3372. return 'get_titanPvpManual';
  3373. }
  3374. return 'get_clanPvp';
  3375. }
  3376. }
  3377. }
  3378. /**
  3379. * Returns the class name of the passed object
  3380. *
  3381. * Возвращает название класса переданного объекта
  3382. */
  3383. function getClass(obj) {
  3384. return {}.toString.call(obj).slice(8, -1);
  3385. }
  3386. /**
  3387. * Calculates the request signature
  3388. *
  3389. * Расчитывает сигнатуру запроса
  3390. */
  3391. this.getSignature = function(headers, data) {
  3392. const sign = {
  3393. signature: '',
  3394. length: 0,
  3395. add: function (text) {
  3396. this.signature += text;
  3397. if (this.length < this.signature.length) {
  3398. this.length = 3 * (this.signature.length + 1) >> 1;
  3399. }
  3400. },
  3401. }
  3402. sign.add(headers["X-Request-Id"]);
  3403. sign.add(':');
  3404. sign.add(headers["X-Auth-Token"]);
  3405. sign.add(':');
  3406. sign.add(headers["X-Auth-Session-Id"]);
  3407. sign.add(':');
  3408. sign.add(data);
  3409. sign.add(':');
  3410. sign.add('LIBRARY-VERSION=1');
  3411. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  3412.  
  3413. return md5(sign.signature);
  3414. }
  3415.  
  3416. class HotkeyManager {
  3417. constructor() {
  3418. if (HotkeyManager.instance) {
  3419. return HotkeyManager.instance;
  3420. }
  3421. this.hotkeys = [];
  3422. document.addEventListener('keydown', this.handleKeyDown.bind(this));
  3423. HotkeyManager.instance = this;
  3424. }
  3425.  
  3426. handleKeyDown(event) {
  3427. const key = event.key.toLowerCase();
  3428. const mods = {
  3429. ctrl: event.ctrlKey,
  3430. alt: event.altKey,
  3431. shift: event.shiftKey,
  3432. };
  3433.  
  3434. this.hotkeys.forEach((hotkey) => {
  3435. if (hotkey.key === key && hotkey.ctrl === mods.ctrl && hotkey.alt === mods.alt && hotkey.shift === mods.shift) {
  3436. hotkey.callback(hotkey);
  3437. }
  3438. });
  3439. }
  3440.  
  3441. add(key, opt = {}, callback) {
  3442. this.hotkeys.push({
  3443. key: key.toLowerCase(),
  3444. callback,
  3445. ctrl: opt.ctrl || false,
  3446. alt: opt.alt || false,
  3447. shift: opt.shift || false,
  3448. });
  3449. }
  3450.  
  3451. remove(key, opt = {}) {
  3452. this.hotkeys = this.hotkeys.filter((hotkey) => {
  3453. return !(
  3454. hotkey.key === key.toLowerCase() &&
  3455. hotkey.ctrl === (opt.ctrl || false) &&
  3456. hotkey.alt === (opt.alt || false) &&
  3457. hotkey.shift === (opt.shift || false)
  3458. );
  3459. });
  3460. }
  3461.  
  3462. static getInst() {
  3463. if (!HotkeyManager.instance) {
  3464. new HotkeyManager();
  3465. }
  3466. return HotkeyManager.instance;
  3467. }
  3468. }
  3469.  
  3470. class MouseClicker {
  3471. constructor(element) {
  3472. if (MouseClicker.instance) {
  3473. return MouseClicker.instance;
  3474. }
  3475. this.element = element;
  3476. this.mouse = {
  3477. bubbles: true,
  3478. cancelable: true,
  3479. clientX: 0,
  3480. clientY: 0,
  3481. };
  3482. this.element.addEventListener('mousemove', this.handleMouseMove.bind(this));
  3483. this.clickInfo = {};
  3484. this.nextTimeoutId = 1;
  3485. MouseClicker.instance = this;
  3486. }
  3487.  
  3488. handleMouseMove(event) {
  3489. this.mouse.clientX = event.clientX;
  3490. this.mouse.clientY = event.clientY;
  3491. }
  3492.  
  3493. click(options) {
  3494. options = options || this.mouse;
  3495. this.element.dispatchEvent(new MouseEvent('mousedown', options));
  3496. this.element.dispatchEvent(new MouseEvent('mouseup', options));
  3497. }
  3498.  
  3499. start(interval = 1000, clickCount = Infinity) {
  3500. const currentMouse = { ...this.mouse };
  3501. const timeoutId = this.nextTimeoutId++;
  3502. let count = 0;
  3503.  
  3504. const clickTimeout = () => {
  3505. this.click(currentMouse);
  3506. count++;
  3507. if (count < clickCount) {
  3508. this.clickInfo[timeoutId].timeout = setTimeout(clickTimeout, interval);
  3509. } else {
  3510. delete this.clickInfo[timeoutId];
  3511. }
  3512. };
  3513.  
  3514. this.clickInfo[timeoutId] = {
  3515. timeout: setTimeout(clickTimeout, interval),
  3516. count: clickCount,
  3517. };
  3518. return timeoutId;
  3519. }
  3520.  
  3521. stop(timeoutId) {
  3522. if (this.clickInfo[timeoutId]) {
  3523. clearTimeout(this.clickInfo[timeoutId].timeout);
  3524. delete this.clickInfo[timeoutId];
  3525. }
  3526. }
  3527.  
  3528. stopAll() {
  3529. for (const timeoutId in this.clickInfo) {
  3530. clearTimeout(this.clickInfo[timeoutId].timeout);
  3531. }
  3532. this.clickInfo = {};
  3533. }
  3534.  
  3535. static getInst(element) {
  3536. if (!MouseClicker.instance) {
  3537. new MouseClicker(element);
  3538. }
  3539. return MouseClicker.instance;
  3540. }
  3541. }
  3542.  
  3543. let extintionsList = [];
  3544. /**
  3545. * Creates an interface
  3546. *
  3547. * Создает интерфейс
  3548. */
  3549. function createInterface() {
  3550. popup.init();
  3551. scriptMenu.init({
  3552. showMenu: true
  3553. });
  3554. scriptMenu.addHeader(GM_info.script.name, justInfo);
  3555. const versionHeader = scriptMenu.addHeader('v' + GM_info.script.version);
  3556. if (extintionsList.length) {
  3557. versionHeader.title = '';
  3558. versionHeader.style.color = 'red';
  3559. for (const extintion of extintionsList) {
  3560. const { name, ver, author } = extintion;
  3561. versionHeader.title += name + ', v' + ver + ' by ' + author + '\n';
  3562. }
  3563. }
  3564. // AutoClicker
  3565. const hkm = new HotkeyManager();
  3566. const fc = document.getElementById('flash-content') || document.getElementById('game');
  3567. const mc = new MouseClicker(fc);
  3568. function toggleClicker(self, timeout) {
  3569. if (self.onClick) {
  3570. console.log('Останавливаем клики');
  3571. mc.stop(self.onClick);
  3572. self.onClick = false;
  3573. } else {
  3574. console.log('Стартуем клики');
  3575. self.onClick = mc.start(timeout);
  3576. }
  3577. }
  3578. hkm.add('C', { ctrl: true, alt: true }, (self) => {
  3579. console.log('"Ctrl + Alt + C"');
  3580. toggleClicker(self, 20);
  3581. });
  3582. hkm.add('V', { ctrl: true, alt: true }, (self) => {
  3583. console.log('"Ctrl + Alt + V"');
  3584. toggleClicker(self, 100);
  3585. });
  3586. }
  3587.  
  3588. function addExtentionName(name, ver, author) {
  3589. extintionsList.push({
  3590. name,
  3591. ver,
  3592. author,
  3593. });
  3594. }
  3595.  
  3596. function addControls() {
  3597. createInterface();
  3598. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  3599. for (let name in checkboxes) {
  3600. if (checkboxes[name].hide) {
  3601. continue;
  3602. }
  3603. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  3604. /**
  3605. * Getting the state of checkboxes from storage
  3606. * Получаем состояние чекбоксов из storage
  3607. */
  3608. let val = storage.get(name, null);
  3609. if (val != null) {
  3610. checkboxes[name].cbox.checked = val;
  3611. } else {
  3612. storage.set(name, checkboxes[name].default);
  3613. checkboxes[name].cbox.checked = checkboxes[name].default;
  3614. }
  3615. /**
  3616. * Tracing the change event of the checkbox for writing to storage
  3617. * Отсеживание события изменения чекбокса для записи в storage
  3618. */
  3619. checkboxes[name].cbox.dataset['name'] = name;
  3620. checkboxes[name].cbox.addEventListener('change', async function (event) {
  3621. const nameCheckbox = this.dataset['name'];
  3622. /*
  3623. if (this.checked && nameCheckbox == 'cancelBattle') {
  3624. this.checked = false;
  3625. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  3626. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  3627. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  3628. ])) {
  3629. return;
  3630. }
  3631. this.checked = true;
  3632. }
  3633. */
  3634. storage.set(nameCheckbox, this.checked);
  3635. })
  3636. }
  3637.  
  3638. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  3639. for (let name in inputs) {
  3640. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  3641. /**
  3642. * Get inputText state from storage
  3643. * Получаем состояние inputText из storage
  3644. */
  3645. let val = storage.get(name, null);
  3646. if (val != null) {
  3647. inputs[name].input.value = val;
  3648. } else {
  3649. storage.set(name, inputs[name].default);
  3650. inputs[name].input.value = inputs[name].default;
  3651. }
  3652. /**
  3653. * Tracing a field change event for a record in storage
  3654. * Отсеживание события изменения поля для записи в storage
  3655. */
  3656. inputs[name].input.dataset['name'] = name;
  3657. inputs[name].input.addEventListener('input', function () {
  3658. const inputName = this.dataset['name'];
  3659. let value = +this.value;
  3660. if (!value || Number.isNaN(value)) {
  3661. value = storage.get(inputName, inputs[inputName].default);
  3662. inputs[name].input.value = value;
  3663. }
  3664. storage.set(inputName, value);
  3665. })
  3666. }
  3667. }
  3668.  
  3669. /**
  3670. * Sending a request
  3671. *
  3672. * Отправка запроса
  3673. */
  3674. function send(json, callback, pr) {
  3675. if (typeof json == 'string') {
  3676. json = JSON.parse(json);
  3677. }
  3678. for (const call of json.calls) {
  3679. if (!call?.context?.actionTs) {
  3680. call.context = {
  3681. actionTs: Math.floor(performance.now())
  3682. }
  3683. }
  3684. }
  3685. json = JSON.stringify(json);
  3686. /**
  3687. * We get the headlines of the previous intercepted request
  3688. * Получаем заголовки предыдущего перехваченого запроса
  3689. */
  3690. let headers = lastHeaders;
  3691. /**
  3692. * We increase the header of the query Certifier by 1
  3693. * Увеличиваем заголовок идетификатора запроса на 1
  3694. */
  3695. headers["X-Request-Id"]++;
  3696. /**
  3697. * We calculate the title with the signature
  3698. * Расчитываем заголовок с сигнатурой
  3699. */
  3700. headers["X-Auth-Signature"] = getSignature(headers, json);
  3701. /**
  3702. * Create a new ajax request
  3703. * Создаем новый AJAX запрос
  3704. */
  3705. let xhr = new XMLHttpRequest;
  3706. /**
  3707. * Indicate the previously saved URL for API queries
  3708. * Указываем ранее сохраненный URL для API запросов
  3709. */
  3710. xhr.open('POST', apiUrl, true);
  3711. /**
  3712. * Add the function to the event change event
  3713. * Добавляем функцию к событию смены статуса запроса
  3714. */
  3715. xhr.onreadystatechange = function() {
  3716. /**
  3717. * If the result of the request is obtained, we call the flask function
  3718. * Если результат запроса получен вызываем колбек функцию
  3719. */
  3720. if(xhr.readyState == 4) {
  3721. callback(xhr.response, pr);
  3722. }
  3723. };
  3724. /**
  3725. * Indicate the type of request
  3726. * Указываем тип запроса
  3727. */
  3728. xhr.responseType = 'json';
  3729. /**
  3730. * We set the request headers
  3731. * Задаем заголовки запроса
  3732. */
  3733. for(let nameHeader in headers) {
  3734. let head = headers[nameHeader];
  3735. xhr.setRequestHeader(nameHeader, head);
  3736. }
  3737. /**
  3738. * Sending a request
  3739. * Отправляем запрос
  3740. */
  3741. xhr.send(json);
  3742. }
  3743.  
  3744. let hideTimeoutProgress = 0;
  3745. /**
  3746. * Hide progress
  3747. *
  3748. * Скрыть прогресс
  3749. */
  3750. function hideProgress(timeout) {
  3751. timeout = timeout || 0;
  3752. clearTimeout(hideTimeoutProgress);
  3753. hideTimeoutProgress = setTimeout(function () {
  3754. scriptMenu.setStatus('');
  3755. }, timeout);
  3756. }
  3757. /**
  3758. * Progress display
  3759. *
  3760. * Отображение прогресса
  3761. */
  3762. function setProgress(text, hide, onclick) {
  3763. scriptMenu.setStatus(text, onclick);
  3764. hide = hide || false;
  3765. if (hide) {
  3766. hideProgress(3000);
  3767. }
  3768. }
  3769.  
  3770. /**
  3771. * Progress added
  3772. *
  3773. * Дополнение прогресса
  3774. */
  3775. function addProgress(text) {
  3776. scriptMenu.addStatus(text);
  3777. }
  3778.  
  3779. /**
  3780. * Returns the timer value depending on the subscription
  3781. *
  3782. * Возвращает значение таймера в зависимости от подписки
  3783. */
  3784. function getTimer(time, div) {
  3785. let speedDiv = 5;
  3786. if (subEndTime < Date.now()) {
  3787. speedDiv = div || 1.5;
  3788. }
  3789. return Math.max(Math.ceil(time / speedDiv + 1.5), 4);
  3790. }
  3791.  
  3792. function startSlave() {
  3793. const { slaveFixBattle } = HWHClasses;
  3794. const sFix = new slaveFixBattle();
  3795. sFix.wsStart();
  3796. }
  3797.  
  3798. this.testFuntions = {
  3799. hideProgress,
  3800. setProgress,
  3801. addProgress,
  3802. masterFix: false,
  3803. startSlave,
  3804. };
  3805.  
  3806. this.HWHFuncs = {
  3807. send,
  3808. I18N,
  3809. isChecked,
  3810. getInput,
  3811. copyText,
  3812. confShow,
  3813. hideProgress,
  3814. setProgress,
  3815. addProgress,
  3816. getTimer,
  3817. addExtentionName,
  3818. getUserInfo,
  3819. setIsCancalBattle,
  3820. random,
  3821. };
  3822.  
  3823. this.HWHClasses = {
  3824. checkChangeSend,
  3825. checkChangeResponse,
  3826. };
  3827. /**
  3828. * Calculates HASH MD5 from string
  3829. *
  3830. * Расчитывает HASH MD5 из строки
  3831. *
  3832. * [js-md5]{@link https://github.com/emn178/js-md5}
  3833. *
  3834. * @namespace md5
  3835. * @version 0.7.3
  3836. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3837. * @copyright Chen, Yi-Cyuan 2014-2017
  3838. * @license MIT
  3839. */
  3840. !function(){"use strict";function t(t){if(t)d[0]=d[16]=d[1]=d[2]=d[3]=d[4]=d[5]=d[6]=d[7]=d[8]=d[9]=d[10]=d[11]=d[12]=d[13]=d[14]=d[15]=0,this.blocks=d,this.buffer8=l;else if(a){var r=new ArrayBuffer(68);this.buffer8=new Uint8Array(r),this.blocks=new Uint32Array(r)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}var r="input is invalid type",e="object"==typeof window,i=e?window:{};i.JS_MD5_NO_WINDOW&&(e=!1);var s=!e&&"object"==typeof self,h=!i.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;h?i=global:s&&(i=self);var f=!i.JS_MD5_NO_COMMON_JS&&"object"==typeof module&&module.exports,o="function"==typeof define&&define.amd,a=!i.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,n="0123456789abcdef".split(""),u=[128,32768,8388608,-2147483648],y=[0,8,16,24],c=["hex","array","digest","buffer","arrayBuffer","base64"],p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),d=[],l;if(a){var A=new ArrayBuffer(68);l=new Uint8Array(A),d=new Uint32Array(A)}!i.JS_MD5_NO_NODE_JS&&Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),!a||!i.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(t){return"object"==typeof t&&t.buffer&&t.buffer.constructor===ArrayBuffer});var b=function(r){return function(e){return new t(!0).update(e)[r]()}},v=function(){var r=b("hex");h&&(r=w(r)),r.create=function(){return new t},r.update=function(t){return r.create().update(t)};for(var e=0;e<c.length;++e){var i=c[e];r[i]=b(i)}return r},w=function(t){var e=eval("require('crypto')"),i=eval("require('buffer').Buffer"),s=function(s){if("string"==typeof s)return e.createHash("md5").update(s,"utf8").digest("hex");if(null===s||void 0===s)throw r;return s.constructor===ArrayBuffer&&(s=new Uint8Array(s)),Array.isArray(s)||ArrayBuffer.isView(s)||s.constructor===i?e.createHash("md5").update(new i(s)).digest("hex"):t(s)};return s};t.prototype.update=function(t){if(!this.finalized){var e,i=typeof t;if("string"!==i){if("object"!==i)throw r;if(null===t)throw r;if(a&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!(Array.isArray(t)||a&&ArrayBuffer.isView(t)))throw r;e=!0}for(var s,h,f=0,o=t.length,n=this.blocks,u=this.buffer8;f<o;){if(this.hashed&&(this.hashed=!1,n[0]=n[16],n[16]=n[1]=n[2]=n[3]=n[4]=n[5]=n[6]=n[7]=n[8]=n[9]=n[10]=n[11]=n[12]=n[13]=n[14]=n[15]=0),e)if(a)for(h=this.start;f<o&&h<64;++f)u[h++]=t[f];else for(h=this.start;f<o&&h<64;++f)n[h>>2]|=t[f]<<y[3&h++];else if(a)for(h=this.start;f<o&&h<64;++f)(s=t.charCodeAt(f))<128?u[h++]=s:s<2048?(u[h++]=192|s>>6,u[h++]=128|63&s):s<55296||s>=57344?(u[h++]=224|s>>12,u[h++]=128|s>>6&63,u[h++]=128|63&s):(s=65536+((1023&s)<<10|1023&t.charCodeAt(++f)),u[h++]=240|s>>18,u[h++]=128|s>>12&63,u[h++]=128|s>>6&63,u[h++]=128|63&s);else for(h=this.start;f<o&&h<64;++f)(s=t.charCodeAt(f))<128?n[h>>2]|=s<<y[3&h++]:s<2048?(n[h>>2]|=(192|s>>6)<<y[3&h++],n[h>>2]|=(128|63&s)<<y[3&h++]):s<55296||s>=57344?(n[h>>2]|=(224|s>>12)<<y[3&h++],n[h>>2]|=(128|s>>6&63)<<y[3&h++],n[h>>2]|=(128|63&s)<<y[3&h++]):(s=65536+((1023&s)<<10|1023&t.charCodeAt(++f)),n[h>>2]|=(240|s>>18)<<y[3&h++],n[h>>2]|=(128|s>>12&63)<<y[3&h++],n[h>>2]|=(128|s>>6&63)<<y[3&h++],n[h>>2]|=(128|63&s)<<y[3&h++]);this.lastByteIndex=h,this.bytes+=h-this.start,h>=64?(this.start=h-64,this.hash(),this.hashed=!0):this.start=h}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},t.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,r=this.lastByteIndex;t[r>>2]|=u[3&r],r>=56&&(this.hashed||this.hash(),t[0]=t[16],t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.bytes<<3,t[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},t.prototype.hash=function(){var t,r,e,i,s,h,f=this.blocks;this.first?r=((r=((t=((t=f[0]-680876937)<<7|t>>>25)-271733879<<0)^(e=((e=(-271733879^(i=((i=(-1732584194^2004318071&t)+f[1]-117830708)<<12|i>>>20)+t<<0)&(-271733879^t))+f[2]-1126478375)<<17|e>>>15)+i<<0)&(i^t))+f[3]-1316259209)<<22|r>>>10)+e<<0:(t=this.h0,r=this.h1,e=this.h2,r=((r+=((t=((t+=((i=this.h3)^r&(e^i))+f[0]-680876936)<<7|t>>>25)+r<<0)^(e=((e+=(r^(i=((i+=(e^t&(r^e))+f[1]-389564586)<<12|i>>>20)+t<<0)&(t^r))+f[2]+606105819)<<17|e>>>15)+i<<0)&(i^t))+f[3]-1044525330)<<22|r>>>10)+e<<0),r=((r+=((t=((t+=(i^r&(e^i))+f[4]-176418897)<<7|t>>>25)+r<<0)^(e=((e+=(r^(i=((i+=(e^t&(r^e))+f[5]+1200080426)<<12|i>>>20)+t<<0)&(t^r))+f[6]-1473231341)<<17|e>>>15)+i<<0)&(i^t))+f[7]-45705983)<<22|r>>>10)+e<<0,r=((r+=((t=((t+=(i^r&(e^i))+f[8]+1770035416)<<7|t>>>25)+r<<0)^(e=((e+=(r^(i=((i+=(e^t&(r^e))+f[9]-1958414417)<<12|i>>>20)+t<<0)&(t^r))+f[10]-42063)<<17|e>>>15)+i<<0)&(i^t))+f[11]-1990404162)<<22|r>>>10)+e<<0,r=((r+=((t=((t+=(i^r&(e^i))+f[12]+1804603682)<<7|t>>>25)+r<<0)^(e=((e+=(r^(i=((i+=(e^t&(r^e))+f[13]-40341101)<<12|i>>>20)+t<<0)&(t^r))+f[14]-1502002290)<<17|e>>>15)+i<<0)&(i^t))+f[15]+1236535329)<<22|r>>>10)+e<<0,r=((r+=((i=((i+=(r^e&((t=((t+=(e^i&(r^e))+f[1]-165796510)<<5|t>>>27)+r<<0)^r))+f[6]-1069501632)<<9|i>>>23)+t<<0)^t&((e=((e+=(t^r&(i^t))+f[11]+643717713)<<14|e>>>18)+i<<0)^i))+f[0]-373897302)<<20|r>>>12)+e<<0,r=((r+=((i=((i+=(r^e&((t=((t+=(e^i&(r^e))+f[5]-701558691)<<5|t>>>27)+r<<0)^r))+f[10]+38016083)<<9|i>>>23)+t<<0)^t&((e=((e+=(t^r&(i^t))+f[15]-660478335)<<14|e>>>18)+i<<0)^i))+f[4]-405537848)<<20|r>>>12)+e<<0,r=((r+=((i=((i+=(r^e&((t=((t+=(e^i&(r^e))+f[9]+568446438)<<5|t>>>27)+r<<0)^r))+f[14]-1019803690)<<9|i>>>23)+t<<0)^t&((e=((e+=(t^r&(i^t))+f[3]-187363961)<<14|e>>>18)+i<<0)^i))+f[8]+1163531501)<<20|r>>>12)+e<<0,r=((r+=((i=((i+=(r^e&((t=((t+=(e^i&(r^e))+f[13]-1444681467)<<5|t>>>27)+r<<0)^r))+f[2]-51403784)<<9|i>>>23)+t<<0)^t&((e=((e+=(t^r&(i^t))+f[7]+1735328473)<<14|e>>>18)+i<<0)^i))+f[12]-1926607734)<<20|r>>>12)+e<<0,r=((r+=((h=(i=((i+=((s=r^e)^(t=((t+=(s^i)+f[5]-378558)<<4|t>>>28)+r<<0))+f[8]-2022574463)<<11|i>>>21)+t<<0)^t)^(e=((e+=(h^r)+f[11]+1839030562)<<16|e>>>16)+i<<0))+f[14]-35309556)<<23|r>>>9)+e<<0,r=((r+=((h=(i=((i+=((s=r^e)^(t=((t+=(s^i)+f[1]-1530992060)<<4|t>>>28)+r<<0))+f[4]+1272893353)<<11|i>>>21)+t<<0)^t)^(e=((e+=(h^r)+f[7]-155497632)<<16|e>>>16)+i<<0))+f[10]-1094730640)<<23|r>>>9)+e<<0,r=((r+=((h=(i=((i+=((s=r^e)^(t=((t+=(s^i)+f[13]+681279174)<<4|t>>>28)+r<<0))+f[0]-358537222)<<11|i>>>21)+t<<0)^t)^(e=((e+=(h^r)+f[3]-722521979)<<16|e>>>16)+i<<0))+f[6]+76029189)<<23|r>>>9)+e<<0,r=((r+=((h=(i=((i+=((s=r^e)^(t=((t+=(s^i)+f[9]-640364487)<<4|t>>>28)+r<<0))+f[12]-421815835)<<11|i>>>21)+t<<0)^t)^(e=((e+=(h^r)+f[15]+530742520)<<16|e>>>16)+i<<0))+f[2]-995338651)<<23|r>>>9)+e<<0,r=((r+=((i=((i+=(r^((t=((t+=(e^(r|~i))+f[0]-198630844)<<6|t>>>26)+r<<0)|~e))+f[7]+1126891415)<<10|i>>>22)+t<<0)^((e=((e+=(t^(i|~r))+f[14]-1416354905)<<15|e>>>17)+i<<0)|~t))+f[5]-57434055)<<21|r>>>11)+e<<0,r=((r+=((i=((i+=(r^((t=((t+=(e^(r|~i))+f[12]+1700485571)<<6|t>>>26)+r<<0)|~e))+f[3]-1894986606)<<10|i>>>22)+t<<0)^((e=((e+=(t^(i|~r))+f[10]-1051523)<<15|e>>>17)+i<<0)|~t))+f[1]-2054922799)<<21|r>>>11)+e<<0,r=((r+=((i=((i+=(r^((t=((t+=(e^(r|~i))+f[8]+1873313359)<<6|t>>>26)+r<<0)|~e))+f[15]-30611744)<<10|i>>>22)+t<<0)^((e=((e+=(t^(i|~r))+f[6]-1560198380)<<15|e>>>17)+i<<0)|~t))+f[13]+1309151649)<<21|r>>>11)+e<<0,r=((r+=((i=((i+=(r^((t=((t+=(e^(r|~i))+f[4]-145523070)<<6|t>>>26)+r<<0)|~e))+f[11]-1120210379)<<10|i>>>22)+t<<0)^((e=((e+=(t^(i|~r))+f[2]+718787259)<<15|e>>>17)+i<<0)|~t))+f[9]-343485551)<<21|r>>>11)+e<<0,this.first?(this.h0=t+1732584193<<0,this.h1=r-271733879<<0,this.h2=e-1732584194<<0,this.h3=i+271733878<<0,this.first=!1):(this.h0=this.h0+t<<0,this.h1=this.h1+r<<0,this.h2=this.h2+e<<0,this.h3=this.h3+i<<0)},t.prototype.hex=function(){this.finalize();var t=this.h0,r=this.h1,e=this.h2,i=this.h3;return n[t>>4&15]+n[15&t]+n[t>>12&15]+n[t>>8&15]+n[t>>20&15]+n[t>>16&15]+n[t>>28&15]+n[t>>24&15]+n[r>>4&15]+n[15&r]+n[r>>12&15]+n[r>>8&15]+n[r>>20&15]+n[r>>16&15]+n[r>>28&15]+n[r>>24&15]+n[e>>4&15]+n[15&e]+n[e>>12&15]+n[e>>8&15]+n[e>>20&15]+n[e>>16&15]+n[e>>28&15]+n[e>>24&15]+n[i>>4&15]+n[15&i]+n[i>>12&15]+n[i>>8&15]+n[i>>20&15]+n[i>>16&15]+n[i>>28&15]+n[i>>24&15]},t.prototype.toString=t.prototype.hex,t.prototype.digest=function(){this.finalize();var t=this.h0,r=this.h1,e=this.h2,i=this.h3;return[255&t,t>>8&255,t>>16&255,t>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255,255&e,e>>8&255,e>>16&255,e>>24&255,255&i,i>>8&255,i>>16&255,i>>24&255]},t.prototype.array=t.prototype.digest,t.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(16),r=new Uint32Array(t);return r[0]=this.h0,r[1]=this.h1,r[2]=this.h2,r[3]=this.h3,t},t.prototype.buffer=t.prototype.arrayBuffer,t.prototype.base64=function(){for(var t,r,e,i="",s=this.array(),h=0;h<15;)t=s[h++],r=s[h++],e=s[h++],i+=p[t>>>2]+p[63&(t<<4|r>>>4)]+p[63&(r<<2|e>>>6)]+p[63&e];return t=s[h],i+=p[t>>>2]+p[t<<4&63]+"=="};var _=v();f?module.exports=_:(i.md5=_,o&&define(function(){return _}))}();
  3841.  
  3842. class Caller {
  3843. static globalHooks = {
  3844. onError: null,
  3845. };
  3846.  
  3847. constructor(calls = null) {
  3848. this.calls = [];
  3849. this.results = {};
  3850. if (calls) {
  3851. this.add(calls);
  3852. }
  3853. }
  3854.  
  3855. static setGlobalHook(event, callback) {
  3856. if (this.globalHooks[event] !== undefined) {
  3857. this.globalHooks[event] = callback;
  3858. } else {
  3859. throw new Error(`Unknown event: ${event}`);
  3860. }
  3861. }
  3862.  
  3863. addCall(call) {
  3864. const { name = call, args = {} } = typeof call === 'object' ? call : { name: call };
  3865. this.calls.push({ name, args });
  3866. return this;
  3867. }
  3868.  
  3869. add(name) {
  3870. if (Array.isArray(name)) {
  3871. name.forEach((call) => this.addCall(call));
  3872. } else {
  3873. this.addCall(name);
  3874. }
  3875. return this;
  3876. }
  3877.  
  3878. handleError(error) {
  3879. const errorName = error.name;
  3880. const errorDescription = error.description;
  3881.  
  3882. if (Caller.globalHooks.onError) {
  3883. const shouldThrow = Caller.globalHooks.onError(error);
  3884. if (shouldThrow === false) {
  3885. return;
  3886. }
  3887. }
  3888.  
  3889. if (error.call) {
  3890. const callInfo = error.call;
  3891. throw new Error(`${errorName} in ${callInfo.name}: ${errorDescription}\n` + `Args: ${JSON.stringify(callInfo.args)}\n`);
  3892. } else if (errorName === 'common\\rpc\\exception\\InvalidRequest') {
  3893. throw new Error(`Invalid request: ${errorDescription}`);
  3894. } else {
  3895. throw new Error(`Unknown error: ${errorName} - ${errorDescription}`);
  3896. }
  3897. }
  3898.  
  3899. async send() {
  3900. if (!this.calls.length) {
  3901. throw new Error('No calls to send.');
  3902. }
  3903.  
  3904. const identToNameMap = {};
  3905. const callsWithIdent = this.calls.map((call, index) => {
  3906. const ident = this.calls.length === 1 ? 'body' : `group_${index}_body`;
  3907. identToNameMap[ident] = call.name;
  3908. return { ...call, ident };
  3909. });
  3910.  
  3911. try {
  3912. const response = await Send({ calls: callsWithIdent });
  3913.  
  3914. if (response.error) {
  3915. this.handleError(response.error);
  3916. }
  3917.  
  3918. if (!response.results) {
  3919. throw new Error('Invalid response format: missing "results" field');
  3920. }
  3921.  
  3922. response.results.forEach((result) => {
  3923. const name = identToNameMap[result.ident];
  3924. if (!this.results[name]) {
  3925. this.results[name] = [];
  3926. }
  3927. this.results[name].push(result.result.response);
  3928. });
  3929. } catch (error) {
  3930. throw error;
  3931. }
  3932. return this;
  3933. }
  3934.  
  3935. result(name, forceArray = false) {
  3936. const results = name ? this.results[name] || [] : Object.values(this.results).flat();
  3937. return forceArray || results.length !== 1 ? results : results[0];
  3938. }
  3939.  
  3940. async execute(name) {
  3941. try {
  3942. await this.send();
  3943. return this.result(name);
  3944. } catch (error) {
  3945. throw error;
  3946. }
  3947. }
  3948.  
  3949. clear() {
  3950. this.calls = [];
  3951. this.results = {};
  3952. return this;
  3953. }
  3954.  
  3955. isEmpty() {
  3956. return this.calls.length === 0 && Object.keys(this.results).length === 0;
  3957. }
  3958. }
  3959.  
  3960. this.Caller = Caller;
  3961.  
  3962. /*
  3963. // Примеры использования
  3964. (async () => {
  3965. // Короткий вызов
  3966. await new Caller('inventoryGet').execute();
  3967. // Простой вызов
  3968. let result = await new Caller().add('inventoryGet').execute();
  3969. console.log('Inventory Get Result:', result);
  3970.  
  3971. // Сложный вызов
  3972. let caller = new Caller();
  3973. await caller
  3974. .add([
  3975. {
  3976. name: 'inventoryGet',
  3977. args: {},
  3978. },
  3979. {
  3980. name: 'heroGetAll',
  3981. args: {},
  3982. },
  3983. ])
  3984. .send();
  3985. console.log('Inventory Get Result:', caller.result('inventoryGet'));
  3986. console.log('Hero Get All Result:', caller.result('heroGetAll'));
  3987.  
  3988. // Очистка всех данных
  3989. caller.clear();
  3990. })();
  3991. */
  3992.  
  3993. /**
  3994. * Script for beautiful dialog boxes
  3995. *
  3996. * Скрипт для красивых диалоговых окошек
  3997. */
  3998. const popup = new (function () {
  3999. this.popUp,
  4000. this.downer,
  4001. this.middle,
  4002. this.msgText,
  4003. this.buttons = [];
  4004. this.checkboxes = [];
  4005. this.dialogPromice = null;
  4006. this.isInit = false;
  4007.  
  4008. this.init = function () {
  4009. if (this.isInit) {
  4010. return;
  4011. }
  4012. addStyle();
  4013. addBlocks();
  4014. addEventListeners();
  4015. this.isInit = true;
  4016. }
  4017.  
  4018. const addEventListeners = () => {
  4019. document.addEventListener('keyup', (e) => {
  4020. if (e.key == 'Escape') {
  4021. if (this.dialogPromice) {
  4022. const { func, result } = this.dialogPromice;
  4023. this.dialogPromice = null;
  4024. popup.hide();
  4025. func(result);
  4026. }
  4027. }
  4028. });
  4029. }
  4030.  
  4031. const addStyle = () => {
  4032. let style = document.createElement('style');
  4033. style.innerText = `
  4034. .PopUp_ {
  4035. position: absolute;
  4036. min-width: 300px;
  4037. max-width: 500px;
  4038. max-height: 600px;
  4039. background-color: #190e08e6;
  4040. z-index: 10001;
  4041. top: 169px;
  4042. left: 345px;
  4043. border: 3px #ce9767 solid;
  4044. border-radius: 10px;
  4045. display: flex;
  4046. flex-direction: column;
  4047. justify-content: space-around;
  4048. padding: 15px 9px;
  4049. box-sizing: border-box;
  4050. }
  4051.  
  4052. .PopUp_back {
  4053. position: absolute;
  4054. background-color: #00000066;
  4055. width: 100%;
  4056. height: 100%;
  4057. z-index: 10000;
  4058. top: 0;
  4059. left: 0;
  4060. }
  4061.  
  4062. .PopUp_close {
  4063. width: 40px;
  4064. height: 40px;
  4065. position: absolute;
  4066. right: -18px;
  4067. top: -18px;
  4068. border: 3px solid #c18550;
  4069. border-radius: 20px;
  4070. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4071. background-position-y: 3px;
  4072. box-shadow: -1px 1px 3px black;
  4073. cursor: pointer;
  4074. box-sizing: border-box;
  4075. }
  4076.  
  4077. .PopUp_close:hover {
  4078. filter: brightness(1.2);
  4079. }
  4080.  
  4081. .PopUp_crossClose {
  4082. width: 100%;
  4083. height: 100%;
  4084. background-size: 65%;
  4085. background-position: center;
  4086. background-repeat: no-repeat;
  4087. background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='%23f4cd73' d='M 0.826 12.559 C 0.431 12.963 3.346 15.374 3.74 14.97 C 4.215 15.173 8.167 10.457 7.804 10.302 C 7.893 10.376 11.454 14.64 11.525 14.372 C 12.134 15.042 15.118 12.086 14.638 11.689 C 14.416 11.21 10.263 7.477 10.402 7.832 C 10.358 7.815 11.731 7.101 14.872 3.114 C 14.698 2.145 13.024 1.074 12.093 1.019 C 11.438 0.861 8.014 5.259 8.035 5.531 C 7.86 5.082 3.61 1.186 3.522 1.59 C 2.973 1.027 0.916 4.611 1.17 4.873 C 0.728 4.914 5.088 7.961 5.61 7.995 C 5.225 7.532 0.622 12.315 0.826 12.559 Z'/%3e%3c/svg%3e")
  4088. }
  4089.  
  4090. .PopUp_blocks {
  4091. width: 100%;
  4092. height: 50%;
  4093. display: flex;
  4094. justify-content: space-evenly;
  4095. align-items: center;
  4096. flex-wrap: wrap;
  4097. justify-content: center;
  4098. }
  4099.  
  4100. .PopUp_blocks:last-child {
  4101. margin-top: 25px;
  4102. }
  4103.  
  4104. .PopUp_buttons {
  4105. display: flex;
  4106. margin: 7px 10px;
  4107. flex-direction: column;
  4108. }
  4109.  
  4110. .PopUp_button {
  4111. background-color: #52A81C;
  4112. border-radius: 5px;
  4113. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  4114. cursor: pointer;
  4115. padding: 4px 12px 6px;
  4116. }
  4117.  
  4118. .PopUp_input {
  4119. text-align: center;
  4120. font-size: 16px;
  4121. height: 27px;
  4122. border: 1px solid #cf9250;
  4123. border-radius: 9px 9px 0px 0px;
  4124. background: transparent;
  4125. color: #fce1ac;
  4126. padding: 1px 10px;
  4127. box-sizing: border-box;
  4128. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  4129. }
  4130.  
  4131. .PopUp_checkboxes {
  4132. display: flex;
  4133. flex-direction: column;
  4134. margin: 15px 15px -5px 15px;
  4135. align-items: flex-start;
  4136. }
  4137.  
  4138. .PopUp_ContCheckbox {
  4139. margin: 2px 0px;
  4140. }
  4141.  
  4142. .PopUp_checkbox {
  4143. position: absolute;
  4144. z-index: -1;
  4145. opacity: 0;
  4146. }
  4147. .PopUp_checkbox+label {
  4148. display: inline-flex;
  4149. align-items: center;
  4150. user-select: none;
  4151.  
  4152. font-size: 15px;
  4153. font-family: sans-serif;
  4154. font-weight: 600;
  4155. font-stretch: condensed;
  4156. letter-spacing: 1px;
  4157. color: #fce1ac;
  4158. text-shadow: 0px 0px 1px;
  4159. }
  4160. .PopUp_checkbox+label::before {
  4161. content: '';
  4162. display: inline-block;
  4163. width: 20px;
  4164. height: 20px;
  4165. border: 1px solid #cf9250;
  4166. border-radius: 7px;
  4167. margin-right: 7px;
  4168. }
  4169. .PopUp_checkbox:checked+label::before {
  4170. background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%2388cb13' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3e%3c/svg%3e");
  4171. }
  4172.  
  4173. .PopUp_input::placeholder {
  4174. color: #fce1ac75;
  4175. }
  4176.  
  4177. .PopUp_input:focus {
  4178. outline: 0;
  4179. }
  4180.  
  4181. .PopUp_input + .PopUp_button {
  4182. border-radius: 0px 0px 5px 5px;
  4183. padding: 2px 18px 5px;
  4184. }
  4185.  
  4186. .PopUp_button:hover {
  4187. filter: brightness(1.2);
  4188. }
  4189.  
  4190. .PopUp_button:active {
  4191. box-shadow: inset 0px 5px 10px, inset 0px 1px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  4192. }
  4193.  
  4194. .PopUp_text {
  4195. font-size: 22px;
  4196. font-family: sans-serif;
  4197. font-weight: 600;
  4198. font-stretch: condensed;
  4199. letter-spacing: 1px;
  4200. text-align: center;
  4201. }
  4202.  
  4203. .PopUp_buttonText {
  4204. color: #E4FF4C;
  4205. text-shadow: 0px 1px 2px black;
  4206. }
  4207.  
  4208. .PopUp_msgText {
  4209. color: #FDE5B6;
  4210. text-shadow: 0px 0px 2px;
  4211. }
  4212.  
  4213. .PopUp_hideBlock {
  4214. display: none;
  4215. }
  4216. `;
  4217. document.head.appendChild(style);
  4218. }
  4219.  
  4220. const addBlocks = () => {
  4221. this.back = document.createElement('div');
  4222. this.back.classList.add('PopUp_back');
  4223. this.back.classList.add('PopUp_hideBlock');
  4224. document.body.append(this.back);
  4225.  
  4226. this.popUp = document.createElement('div');
  4227. this.popUp.classList.add('PopUp_');
  4228. this.back.append(this.popUp);
  4229.  
  4230. let upper = document.createElement('div')
  4231. upper.classList.add('PopUp_blocks');
  4232. this.popUp.append(upper);
  4233.  
  4234. this.middle = document.createElement('div')
  4235. this.middle.classList.add('PopUp_blocks');
  4236. this.middle.classList.add('PopUp_checkboxes');
  4237. this.popUp.append(this.middle);
  4238.  
  4239. this.downer = document.createElement('div')
  4240. this.downer.classList.add('PopUp_blocks');
  4241. this.popUp.append(this.downer);
  4242.  
  4243. this.msgText = document.createElement('div');
  4244. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  4245. upper.append(this.msgText);
  4246. }
  4247.  
  4248. this.showBack = function () {
  4249. this.back.classList.remove('PopUp_hideBlock');
  4250. }
  4251.  
  4252. this.hideBack = function () {
  4253. this.back.classList.add('PopUp_hideBlock');
  4254. }
  4255.  
  4256. this.show = function () {
  4257. if (this.checkboxes.length) {
  4258. this.middle.classList.remove('PopUp_hideBlock');
  4259. }
  4260. this.showBack();
  4261. this.popUp.classList.remove('PopUp_hideBlock');
  4262. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  4263. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  4264. }
  4265.  
  4266. this.hide = function () {
  4267. this.hideBack();
  4268. this.popUp.classList.add('PopUp_hideBlock');
  4269. }
  4270.  
  4271. this.addAnyButton = (option) => {
  4272. const contButton = document.createElement('div');
  4273. contButton.classList.add('PopUp_buttons');
  4274. this.downer.append(contButton);
  4275.  
  4276. let inputField = {
  4277. value: option.result || option.default
  4278. }
  4279. if (option.isInput) {
  4280. inputField = document.createElement('input');
  4281. inputField.type = 'text';
  4282. if (option.placeholder) {
  4283. inputField.placeholder = option.placeholder;
  4284. }
  4285. if (option.default) {
  4286. inputField.value = option.default;
  4287. }
  4288. inputField.classList.add('PopUp_input');
  4289. contButton.append(inputField);
  4290. }
  4291.  
  4292. const button = document.createElement('div');
  4293. button.classList.add('PopUp_button');
  4294. button.title = option.title || '';
  4295. contButton.append(button);
  4296.  
  4297. const buttonText = document.createElement('div');
  4298. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  4299. buttonText.innerHTML = option.msg;
  4300. button.append(buttonText);
  4301.  
  4302. return { button, contButton, inputField };
  4303. }
  4304.  
  4305. this.addCloseButton = () => {
  4306. let button = document.createElement('div')
  4307. button.classList.add('PopUp_close');
  4308. this.popUp.append(button);
  4309.  
  4310. let crossClose = document.createElement('div')
  4311. crossClose.classList.add('PopUp_crossClose');
  4312. button.append(crossClose);
  4313.  
  4314. return { button, contButton: button };
  4315. }
  4316.  
  4317. this.addButton = (option, buttonClick) => {
  4318.  
  4319. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  4320. if (option.isClose) {
  4321. this.dialogPromice = { func: buttonClick, result: option.result };
  4322. }
  4323. button.addEventListener('click', () => {
  4324. let result = '';
  4325. if (option.isInput) {
  4326. result = inputField.value;
  4327. }
  4328. if (option.isClose || option.isCancel) {
  4329. this.dialogPromice = null;
  4330. }
  4331. buttonClick(result);
  4332. });
  4333.  
  4334. this.buttons.push(contButton);
  4335. }
  4336.  
  4337. this.clearButtons = () => {
  4338. while (this.buttons.length) {
  4339. this.buttons.pop().remove();
  4340. }
  4341. }
  4342.  
  4343. this.addCheckBox = (checkBox) => {
  4344. const contCheckbox = document.createElement('div');
  4345. contCheckbox.classList.add('PopUp_ContCheckbox');
  4346. this.middle.append(contCheckbox);
  4347.  
  4348. const checkbox = document.createElement('input');
  4349. checkbox.type = 'checkbox';
  4350. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  4351. checkbox.dataset.name = checkBox.name;
  4352. checkbox.checked = checkBox.checked;
  4353. checkbox.label = checkBox.label;
  4354. checkbox.title = checkBox.title || '';
  4355. checkbox.classList.add('PopUp_checkbox');
  4356. contCheckbox.appendChild(checkbox)
  4357.  
  4358. const checkboxLabel = document.createElement('label');
  4359. checkboxLabel.innerText = checkBox.label;
  4360. checkboxLabel.title = checkBox.title || '';
  4361. checkboxLabel.setAttribute('for', checkbox.id);
  4362. contCheckbox.appendChild(checkboxLabel);
  4363.  
  4364. this.checkboxes.push(checkbox);
  4365. }
  4366.  
  4367. this.clearCheckBox = () => {
  4368. this.middle.classList.add('PopUp_hideBlock');
  4369. while (this.checkboxes.length) {
  4370. this.checkboxes.pop().parentNode.remove();
  4371. }
  4372. }
  4373.  
  4374. this.setMsgText = (text) => {
  4375. this.msgText.innerHTML = text;
  4376. }
  4377.  
  4378. this.getCheckBoxes = () => {
  4379. const checkBoxes = [];
  4380.  
  4381. for (const checkBox of this.checkboxes) {
  4382. checkBoxes.push({
  4383. name: checkBox.dataset.name,
  4384. label: checkBox.label,
  4385. checked: checkBox.checked
  4386. });
  4387. }
  4388.  
  4389. return checkBoxes;
  4390. }
  4391.  
  4392. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  4393. if (!this.isInit) {
  4394. this.init();
  4395. }
  4396. this.clearButtons();
  4397. this.clearCheckBox();
  4398. return new Promise((complete, failed) => {
  4399. this.setMsgText(msg);
  4400. if (!buttOpt) {
  4401. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  4402. }
  4403. for (const checkBox of checkBoxes) {
  4404. this.addCheckBox(checkBox);
  4405. }
  4406. for (let butt of buttOpt) {
  4407. this.addButton(butt, (result) => {
  4408. result = result || butt.result;
  4409. complete(result);
  4410. popup.hide();
  4411. });
  4412. if (butt.isCancel) {
  4413. this.dialogPromice = { func: complete, result: butt.result };
  4414. }
  4415. }
  4416. this.show();
  4417. });
  4418. }
  4419. });
  4420.  
  4421. this.HWHFuncs.popup = popup;
  4422.  
  4423. /**
  4424. * Script control panel
  4425. *
  4426. * Панель управления скриптом
  4427. */
  4428. class ScriptMenu {
  4429. constructor() {
  4430. this.mainMenu = null;
  4431. this.buttons = [];
  4432. this.checkboxes = [];
  4433. this.option = {
  4434. showMenu: false,
  4435. showDetails: {},
  4436. };
  4437. }
  4438.  
  4439. init(option = {}) {
  4440. this.option = Object.assign(this.option, option);
  4441. this.option.showDetails = this.loadShowDetails();
  4442. this.addStyle();
  4443. this.addBlocks();
  4444. }
  4445.  
  4446. addStyle() {
  4447. const style = document.createElement('style');
  4448. style.innerText = `
  4449. .scriptMenu_status {
  4450. position: absolute;
  4451. z-index: 10001;
  4452. top: -1px;
  4453. left: 30%;
  4454. cursor: pointer;
  4455. border-radius: 0px 0px 10px 10px;
  4456. background: #190e08e6;
  4457. border: 1px #ce9767 solid;
  4458. font-size: 18px;
  4459. font-family: sans-serif;
  4460. font-weight: 600;
  4461. font-stretch: condensed;
  4462. letter-spacing: 1px;
  4463. color: #fce1ac;
  4464. text-shadow: 0px 0px 1px;
  4465. transition: 0.5s;
  4466. padding: 2px 10px 3px;
  4467. }
  4468. .scriptMenu_statusHide {
  4469. top: -35px;
  4470. height: 30px;
  4471. overflow: hidden;
  4472. }
  4473. .scriptMenu_label {
  4474. position: absolute;
  4475. top: 30%;
  4476. left: -4px;
  4477. z-index: 9999;
  4478. cursor: pointer;
  4479. width: 30px;
  4480. height: 30px;
  4481. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  4482. border: 1px solid #1a2f04;
  4483. border-radius: 5px;
  4484. box-shadow:
  4485. inset 0px 2px 4px #83ce26,
  4486. inset 0px -4px 6px #1a2f04,
  4487. 0px 0px 2px black,
  4488. 0px 0px 0px 2px #ce9767;
  4489. }
  4490. .scriptMenu_label:hover {
  4491. filter: brightness(1.2);
  4492. }
  4493. .scriptMenu_arrowLabel {
  4494. width: 100%;
  4495. height: 100%;
  4496. background-size: 75%;
  4497. background-position: center;
  4498. background-repeat: no-repeat;
  4499. background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='%2388cb13' d='M7.596 7.304a.802.802 0 0 1 0 1.392l-6.363 3.692C.713 12.69 0 12.345 0 11.692V4.308c0-.653.713-.998 1.233-.696l6.363 3.692Z'/%3e%3cpath fill='%2388cb13' d='M15.596 7.304a.802.802 0 0 1 0 1.392l-6.363 3.692C8.713 12.69 8 12.345 8 11.692V4.308c0-.653.713-.998 1.233-.696l6.363 3.692Z'/%3e%3c/svg%3e");
  4500. box-shadow: 0px 1px 2px #000;
  4501. border-radius: 5px;
  4502. filter: drop-shadow(0px 1px 2px #000D);
  4503. }
  4504. .scriptMenu_main {
  4505. position: absolute;
  4506. max-width: 285px;
  4507. z-index: 9999;
  4508. top: 50%;
  4509. transform: translateY(-40%);
  4510. background: #190e08e6;
  4511. border: 1px #ce9767 solid;
  4512. border-radius: 0px 10px 10px 0px;
  4513. border-left: none;
  4514. padding: 5px 10px 5px 5px;
  4515. box-sizing: border-box;
  4516. font-size: 15px;
  4517. font-family: sans-serif;
  4518. font-weight: 600;
  4519. font-stretch: condensed;
  4520. letter-spacing: 1px;
  4521. color: #fce1ac;
  4522. text-shadow: 0px 0px 1px;
  4523. transition: 1s;
  4524. display: flex;
  4525. flex-direction: column;
  4526. flex-wrap: nowrap;
  4527. }
  4528. .scriptMenu_showMenu {
  4529. display: none;
  4530. }
  4531. .scriptMenu_showMenu:checked~.scriptMenu_main {
  4532. left: 0px;
  4533. }
  4534. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  4535. left: -300px;
  4536. }
  4537. .scriptMenu_divInput {
  4538. margin: 2px;
  4539. }
  4540. .scriptMenu_divInputText {
  4541. margin: 2px;
  4542. align-self: center;
  4543. display: flex;
  4544. }
  4545. .scriptMenu_checkbox {
  4546. position: absolute;
  4547. z-index: -1;
  4548. opacity: 0;
  4549. }
  4550. .scriptMenu_checkbox+label {
  4551. display: inline-flex;
  4552. align-items: center;
  4553. user-select: none;
  4554. }
  4555. .scriptMenu_checkbox+label::before {
  4556. content: '';
  4557. display: inline-block;
  4558. width: 20px;
  4559. height: 20px;
  4560. border: 1px solid #cf9250;
  4561. border-radius: 7px;
  4562. margin-right: 7px;
  4563. }
  4564. .scriptMenu_checkbox:checked+label::before {
  4565. background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%2388cb13' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3e%3c/svg%3e");
  4566. }
  4567. .scriptMenu_close {
  4568. width: 40px;
  4569. height: 40px;
  4570. position: absolute;
  4571. right: -18px;
  4572. top: -18px;
  4573. border: 3px solid #c18550;
  4574. border-radius: 20px;
  4575. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4576. background-position-y: 3px;
  4577. box-shadow: -1px 1px 3px black;
  4578. cursor: pointer;
  4579. box-sizing: border-box;
  4580. }
  4581. .scriptMenu_close:hover {
  4582. filter: brightness(1.2);
  4583. }
  4584. .scriptMenu_crossClose {
  4585. width: 100%;
  4586. height: 100%;
  4587. background-size: 65%;
  4588. background-position: center;
  4589. background-repeat: no-repeat;
  4590. background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='%23f4cd73' d='M 0.826 12.559 C 0.431 12.963 3.346 15.374 3.74 14.97 C 4.215 15.173 8.167 10.457 7.804 10.302 C 7.893 10.376 11.454 14.64 11.525 14.372 C 12.134 15.042 15.118 12.086 14.638 11.689 C 14.416 11.21 10.263 7.477 10.402 7.832 C 10.358 7.815 11.731 7.101 14.872 3.114 C 14.698 2.145 13.024 1.074 12.093 1.019 C 11.438 0.861 8.014 5.259 8.035 5.531 C 7.86 5.082 3.61 1.186 3.522 1.59 C 2.973 1.027 0.916 4.611 1.17 4.873 C 0.728 4.914 5.088 7.961 5.61 7.995 C 5.225 7.532 0.622 12.315 0.826 12.559 Z'/%3e%3c/svg%3e")
  4591. }
  4592. .scriptMenu_button {
  4593. user-select: none;
  4594. cursor: pointer;
  4595. padding: 5px 14px 8px;
  4596. }
  4597. .scriptMenu_button:hover {
  4598. filter: brightness(1.2);
  4599. }
  4600. .scriptMenu_buttonText {
  4601. color: #fce5b7;
  4602. text-shadow: 0px 1px 2px black;
  4603. text-align: center;
  4604. }
  4605. .scriptMenu_header {
  4606. text-align: center;
  4607. align-self: center;
  4608. font-size: 15px;
  4609. margin: 0px 15px;
  4610. }
  4611. .scriptMenu_header a {
  4612. color: #fce5b7;
  4613. text-decoration: none;
  4614. }
  4615. .scriptMenu_InputText {
  4616. text-align: center;
  4617. width: 130px;
  4618. height: 24px;
  4619. border: 1px solid #cf9250;
  4620. border-radius: 9px;
  4621. background: transparent;
  4622. color: #fce1ac;
  4623. padding: 0px 10px;
  4624. box-sizing: border-box;
  4625. }
  4626. .scriptMenu_InputText:focus {
  4627. filter: brightness(1.2);
  4628. outline: 0;
  4629. }
  4630. .scriptMenu_InputText::placeholder {
  4631. color: #fce1ac75;
  4632. }
  4633. .scriptMenu_Summary {
  4634. cursor: pointer;
  4635. margin-left: 7px;
  4636. }
  4637. .scriptMenu_Details {
  4638. align-self: center;
  4639. }
  4640. .scriptMenu_buttonGroup {
  4641. display: flex;
  4642. justify-content: center;
  4643. user-select: none;
  4644. cursor: pointer;
  4645. padding: 0;
  4646. margin: 3px 0;
  4647. }
  4648. .scriptMenu_buttonGroup .scriptMenu_button {
  4649. width: 100%;
  4650. padding: 5px 8px 8px;
  4651. }
  4652. .scriptMenu_mainButton {
  4653. border-radius: 5px;
  4654. margin: 3px 0;
  4655. }
  4656. .scriptMenu_combineButtonLeft {
  4657. border-top-left-radius: 5px;
  4658. border-bottom-left-radius: 5px;
  4659. margin-right: 2px;
  4660. }
  4661. .scriptMenu_combineButtonCenter {
  4662. border-radius: 0px;
  4663. margin-right: 2px;
  4664. }
  4665. .scriptMenu_combineButtonRight {
  4666. border-top-right-radius: 5px;
  4667. border-bottom-right-radius: 5px;
  4668. }
  4669. .scriptMenu_beigeButton {
  4670. border: 1px solid #442901;
  4671. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  4672. box-shadow: inset 0px 2px 4px #e9b282, inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 2px black, 0px 0px 0px 1px #ce9767;
  4673. }
  4674. .scriptMenu_beigeButton:active {
  4675. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4676. }
  4677. .scriptMenu_greenButton {
  4678. border: 1px solid #1a2f04;
  4679. background: radial-gradient(circle, #47a41b 0%, #1a2f04 150%);
  4680. box-shadow: inset 0px 2px 4px #83ce26, inset 0px -4px 6px #1a2f04, 0px 0px 2px black, 0px 0px 0px 1px #ce9767;
  4681. }
  4682. .scriptMenu_greenButton:active {
  4683. box-shadow: inset 0px 4px 6px #1a2f04, inset 0px 4px 6px #1a2f04, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4684. }
  4685. .scriptMenu_redButton {
  4686. border: 1px solid #440101;
  4687. background: radial-gradient(circle, rgb(198, 34, 34) 80%, rgb(0, 0, 0) 110%);
  4688. box-shadow: inset 0px 2px 4px #e98282, inset 0px -4px 6px #440101, inset 0px 1px 6px #440101, inset 0px 0px 6px, 0px 0px 2px black, 0px 0px 0px 1px #ce9767;
  4689. }
  4690. .scriptMenu_redButton:active {
  4691. box-shadow: inset 0px 4px 6px #440101, inset 0px 4px 6px #440101, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4692. }
  4693. .scriptMenu_attention {
  4694. position: relative;
  4695. }
  4696. .scriptMenu_attention .scriptMenu_dot {
  4697. display: block;
  4698. }
  4699. .scriptMenu_dot {
  4700. position: absolute;
  4701. top: -7px;
  4702. right: -7px;
  4703. width: 20px;
  4704. height: 20px;
  4705. border-radius: 50%;
  4706. border: 1px solid #c18550;
  4707. background: radial-gradient(circle, #f000 25%, black 100%);
  4708. box-shadow: 0px 0px 2px black;
  4709. background-position: 0px -1px;
  4710. font-size: 10px;
  4711. text-align: center;
  4712. color: white;
  4713. text-shadow: 1px 1px 1px black;
  4714. padding: 2px 0px;
  4715. box-sizing: border-box;
  4716. display: none;
  4717. }
  4718. `;
  4719. document.head.appendChild(style);
  4720. }
  4721.  
  4722. addBlocks() {
  4723. const main = document.createElement('div');
  4724. document.body.appendChild(main);
  4725.  
  4726. this.status = document.createElement('div');
  4727. this.status.classList.add('scriptMenu_status');
  4728. this.setStatus('');
  4729. main.appendChild(this.status);
  4730.  
  4731. const label = document.createElement('label');
  4732. label.classList.add('scriptMenu_label');
  4733. label.setAttribute('for', 'checkbox_showMenu');
  4734. main.appendChild(label);
  4735.  
  4736. const arrowLabel = document.createElement('div');
  4737. arrowLabel.classList.add('scriptMenu_arrowLabel');
  4738. label.appendChild(arrowLabel);
  4739.  
  4740. const checkbox = document.createElement('input');
  4741. checkbox.type = 'checkbox';
  4742. checkbox.id = 'checkbox_showMenu';
  4743. checkbox.checked = this.option.showMenu;
  4744. checkbox.classList.add('scriptMenu_showMenu');
  4745. main.appendChild(checkbox);
  4746.  
  4747. this.mainMenu = document.createElement('div');
  4748. this.mainMenu.classList.add('scriptMenu_main');
  4749. main.appendChild(this.mainMenu);
  4750.  
  4751. const closeButton = document.createElement('label');
  4752. closeButton.classList.add('scriptMenu_close');
  4753. closeButton.setAttribute('for', 'checkbox_showMenu');
  4754. this.mainMenu.appendChild(closeButton);
  4755.  
  4756. const crossClose = document.createElement('div');
  4757. crossClose.classList.add('scriptMenu_crossClose');
  4758. closeButton.appendChild(crossClose);
  4759. }
  4760.  
  4761. getButtonColor(color) {
  4762. const buttonColors = {
  4763. green: 'scriptMenu_greenButton',
  4764. red: 'scriptMenu_redButton',
  4765. beige: 'scriptMenu_beigeButton',
  4766. };
  4767. return buttonColors[color] || buttonColors['beige'];
  4768. }
  4769.  
  4770. setStatus(text, onclick) {
  4771. if (!text) {
  4772. this.status.classList.add('scriptMenu_statusHide');
  4773. this.status.innerHTML = '';
  4774. } else {
  4775. this.status.classList.remove('scriptMenu_statusHide');
  4776. this.status.innerHTML = text;
  4777. }
  4778.  
  4779. if (typeof onclick === 'function') {
  4780. this.status.addEventListener('click', onclick, { once: true });
  4781. }
  4782. }
  4783.  
  4784. addStatus(text) {
  4785. if (!this.status.innerHTML) {
  4786. this.status.classList.remove('scriptMenu_statusHide');
  4787. }
  4788. this.status.innerHTML += text;
  4789. }
  4790.  
  4791. addHeader(text, onClick, main = this.mainMenu) {
  4792. const header = document.createElement('div');
  4793. header.classList.add('scriptMenu_header');
  4794. header.innerHTML = text;
  4795. if (typeof onClick === 'function') {
  4796. header.addEventListener('click', onClick);
  4797. }
  4798. main.appendChild(header);
  4799. }
  4800.  
  4801. addButton(btn, main = this.mainMenu) {
  4802. const { name, onClick, title, color, dot, classes = [], isCombine } = btn;
  4803. const button = document.createElement('div');
  4804. if (!isCombine) {
  4805. classes.push('scriptMenu_mainButton');
  4806. }
  4807. button.classList.add('scriptMenu_button', this.getButtonColor(color), ...classes);
  4808. button.title = title;
  4809. button.addEventListener('click', onClick);
  4810. main.appendChild(button);
  4811.  
  4812. const buttonText = document.createElement('div');
  4813. buttonText.classList.add('scriptMenu_buttonText');
  4814. buttonText.innerText = name;
  4815. button.appendChild(buttonText);
  4816.  
  4817. if (dot) {
  4818. const dotAtention = document.createElement('div');
  4819. dotAtention.classList.add('scriptMenu_dot');
  4820. dotAtention.title = dot;
  4821. button.appendChild(dotAtention);
  4822. }
  4823.  
  4824. this.buttons.push(button);
  4825. return button;
  4826. }
  4827.  
  4828. addCombinedButton(buttonList, main = this.mainMenu) {
  4829. const buttonGroup = document.createElement('div');
  4830. buttonGroup.classList.add('scriptMenu_buttonGroup');
  4831. let count = 0;
  4832.  
  4833. for (const btn of buttonList) {
  4834. btn.isCombine = true;
  4835. btn.classes ??= [];
  4836. if (count === 0) {
  4837. btn.classes.push('scriptMenu_combineButtonLeft');
  4838. } else if (count === buttonList.length - 1) {
  4839. btn.classes.push('scriptMenu_combineButtonRight');
  4840. } else {
  4841. btn.classes.push('scriptMenu_combineButtonCenter');
  4842. }
  4843. this.addButton(btn, buttonGroup);
  4844. count++;
  4845. }
  4846.  
  4847. const dotAtention = document.createElement('div');
  4848. dotAtention.classList.add('scriptMenu_dot');
  4849. buttonGroup.appendChild(dotAtention);
  4850.  
  4851. main.appendChild(buttonGroup);
  4852. return buttonGroup;
  4853. }
  4854.  
  4855. addCheckbox(label, title, main = this.mainMenu) {
  4856. const divCheckbox = document.createElement('div');
  4857. divCheckbox.classList.add('scriptMenu_divInput');
  4858. divCheckbox.title = title;
  4859. main.appendChild(divCheckbox);
  4860.  
  4861. const checkbox = document.createElement('input');
  4862. checkbox.type = 'checkbox';
  4863. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  4864. checkbox.classList.add('scriptMenu_checkbox');
  4865. divCheckbox.appendChild(checkbox);
  4866.  
  4867. const checkboxLabel = document.createElement('label');
  4868. checkboxLabel.innerText = label;
  4869. checkboxLabel.setAttribute('for', checkbox.id);
  4870. divCheckbox.appendChild(checkboxLabel);
  4871.  
  4872. this.checkboxes.push(checkbox);
  4873. return checkbox;
  4874. }
  4875.  
  4876. addInputText(title, placeholder, main = this.mainMenu) {
  4877. const divInputText = document.createElement('div');
  4878. divInputText.classList.add('scriptMenu_divInputText');
  4879. divInputText.title = title;
  4880. main.appendChild(divInputText);
  4881.  
  4882. const newInputText = document.createElement('input');
  4883. newInputText.type = 'text';
  4884. if (placeholder) {
  4885. newInputText.placeholder = placeholder;
  4886. }
  4887. newInputText.classList.add('scriptMenu_InputText');
  4888. divInputText.appendChild(newInputText);
  4889. return newInputText;
  4890. }
  4891.  
  4892. addDetails(summaryText, name = null) {
  4893. const details = document.createElement('details');
  4894. details.classList.add('scriptMenu_Details');
  4895. this.mainMenu.appendChild(details);
  4896.  
  4897. const summary = document.createElement('summary');
  4898. summary.classList.add('scriptMenu_Summary');
  4899. summary.innerText = summaryText;
  4900. if (name) {
  4901. const self = this;
  4902. details.open = this.option.showDetails[name];
  4903. details.dataset.name = name;
  4904. summary.addEventListener('click', () => {
  4905. self.option.showDetails[details.dataset.name] = !details.open;
  4906. self.saveShowDetails(self.option.showDetails);
  4907. });
  4908. }
  4909. details.appendChild(summary);
  4910.  
  4911. return details;
  4912. }
  4913.  
  4914. saveShowDetails(value) {
  4915. try {
  4916. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  4917. } catch (e) {
  4918. console.log('¯\\_(ツ)_/¯');
  4919. }
  4920. }
  4921.  
  4922. loadShowDetails() {
  4923. let showDetails = null;
  4924. try {
  4925. showDetails = localStorage.getItem('scriptMenu_showDetails');
  4926. } catch (e) {
  4927. console.log('¯\\_(ツ)_/¯');
  4928. }
  4929.  
  4930. if (!showDetails) {
  4931. return {};
  4932. }
  4933.  
  4934. try {
  4935. showDetails = JSON.parse(showDetails);
  4936. } catch (e) {
  4937. return {};
  4938. }
  4939.  
  4940. return showDetails;
  4941. }
  4942. }
  4943.  
  4944. const scriptMenu = new ScriptMenu();
  4945.  
  4946. /**
  4947. * Пример использования
  4948. const scriptMenu = new ScriptMenu();
  4949. scriptMenu.init();
  4950. scriptMenu.addHeader('v1.508');
  4951. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  4952. scriptMenu.addButton({
  4953. text: 'Запуск!',
  4954. onClick: () => console.log('click'),
  4955. title: 'подсказака',
  4956. });
  4957. scriptMenu.addInputText('input подсказака');
  4958. */
  4959.  
  4960. /**
  4961. * Game Library
  4962. *
  4963. * Игровая библиотека
  4964. */
  4965. class Library {
  4966. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  4967.  
  4968. constructor() {
  4969. if (!Library.instance) {
  4970. Library.instance = this;
  4971. }
  4972.  
  4973. return Library.instance;
  4974. }
  4975.  
  4976. async load() {
  4977. try {
  4978. await this.getUrlLib();
  4979. console.log(this.defaultLibUrl);
  4980. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  4981. } catch (error) {
  4982. console.error('Не удалось загрузить библиотеку', error)
  4983. }
  4984. }
  4985.  
  4986. async getUrlLib() {
  4987. try {
  4988. const db = new Database('hw_cache', 'cache');
  4989. await db.open();
  4990. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  4991. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  4992. } catch(e) {}
  4993. }
  4994.  
  4995. getData(id) {
  4996. return this.data[id];
  4997. }
  4998.  
  4999. setData(data) {
  5000. this.data = data;
  5001. }
  5002. }
  5003.  
  5004. this.lib = new Library();
  5005. /**
  5006. * Database
  5007. *
  5008. * База данных
  5009. */
  5010. class Database {
  5011. constructor(dbName, storeName) {
  5012. this.dbName = dbName;
  5013. this.storeName = storeName;
  5014. this.db = null;
  5015. }
  5016.  
  5017. async open() {
  5018. return new Promise((resolve, reject) => {
  5019. const request = indexedDB.open(this.dbName);
  5020.  
  5021. request.onerror = () => {
  5022. reject(new Error(`Failed to open database ${this.dbName}`));
  5023. };
  5024.  
  5025. request.onsuccess = () => {
  5026. this.db = request.result;
  5027. resolve();
  5028. };
  5029.  
  5030. request.onupgradeneeded = (event) => {
  5031. const db = event.target.result;
  5032. if (!db.objectStoreNames.contains(this.storeName)) {
  5033. db.createObjectStore(this.storeName);
  5034. }
  5035. };
  5036. });
  5037. }
  5038.  
  5039. async set(key, value) {
  5040. return new Promise((resolve, reject) => {
  5041. const transaction = this.db.transaction([this.storeName], 'readwrite');
  5042. const store = transaction.objectStore(this.storeName);
  5043. const request = store.put(value, key);
  5044.  
  5045. request.onerror = () => {
  5046. reject(new Error(`Failed to save value with key ${key}`));
  5047. };
  5048.  
  5049. request.onsuccess = () => {
  5050. resolve();
  5051. };
  5052. });
  5053. }
  5054.  
  5055. async get(key, def) {
  5056. return new Promise((resolve, reject) => {
  5057. const transaction = this.db.transaction([this.storeName], 'readonly');
  5058. const store = transaction.objectStore(this.storeName);
  5059. const request = store.get(key);
  5060.  
  5061. request.onerror = () => {
  5062. resolve(def);
  5063. };
  5064.  
  5065. request.onsuccess = () => {
  5066. resolve(request.result);
  5067. };
  5068. });
  5069. }
  5070.  
  5071. async delete(key) {
  5072. return new Promise((resolve, reject) => {
  5073. const transaction = this.db.transaction([this.storeName], 'readwrite');
  5074. const store = transaction.objectStore(this.storeName);
  5075. const request = store.delete(key);
  5076.  
  5077. request.onerror = () => {
  5078. reject(new Error(`Failed to delete value with key ${key}`));
  5079. };
  5080.  
  5081. request.onsuccess = () => {
  5082. resolve();
  5083. };
  5084. });
  5085. }
  5086. }
  5087.  
  5088. /**
  5089. * Returns the stored value
  5090. *
  5091. * Возвращает сохраненное значение
  5092. */
  5093. function getSaveVal(saveName, def) {
  5094. const result = storage.get(saveName, def);
  5095. return result;
  5096. }
  5097. this.HWHFuncs.getSaveVal = getSaveVal;
  5098.  
  5099. /**
  5100. * Stores value
  5101. *
  5102. * Сохраняет значение
  5103. */
  5104. function setSaveVal(saveName, value) {
  5105. storage.set(saveName, value);
  5106. }
  5107. this.HWHFuncs.setSaveVal = setSaveVal;
  5108.  
  5109. /**
  5110. * Database initialization
  5111. *
  5112. * Инициализация базы данных
  5113. */
  5114. const db = new Database(GM_info.script.name, 'settings');
  5115.  
  5116. /**
  5117. * Data store
  5118. *
  5119. * Хранилище данных
  5120. */
  5121. const storage = {
  5122. userId: 0,
  5123. /**
  5124. * Default values
  5125. *
  5126. * Значения по умолчанию
  5127. */
  5128. values: [
  5129. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  5130. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  5131. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  5132. name: GM_info.script.name,
  5133. get: function (key, def) {
  5134. if (key in this.values) {
  5135. return this.values[key];
  5136. }
  5137. return def;
  5138. },
  5139. set: function (key, value) {
  5140. this.values[key] = value;
  5141. db.set(this.userId, this.values).catch(
  5142. e => null
  5143. );
  5144. localStorage[this.name + ':' + key] = value;
  5145. },
  5146. delete: function (key) {
  5147. delete this.values[key];
  5148. db.set(this.userId, this.values);
  5149. delete localStorage[this.name + ':' + key];
  5150. }
  5151. }
  5152.  
  5153. /**
  5154. * Returns all keys from localStorage that start with prefix (for migration)
  5155. *
  5156. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  5157. */
  5158. function getAllValuesStartingWith(prefix) {
  5159. const values = [];
  5160. for (let i = 0; i < localStorage.length; i++) {
  5161. const key = localStorage.key(i);
  5162. if (key.startsWith(prefix)) {
  5163. const val = localStorage.getItem(key);
  5164. const keyValue = key.split(':')[1];
  5165. values.push({ key: keyValue, val });
  5166. }
  5167. }
  5168. return values;
  5169. }
  5170.  
  5171. /**
  5172. * Opens or migrates to a database
  5173. *
  5174. * Открывает или мигрирует в базу данных
  5175. */
  5176. async function openOrMigrateDatabase(userId) {
  5177. storage.userId = userId;
  5178. try {
  5179. await db.open();
  5180. } catch(e) {
  5181. return;
  5182. }
  5183. let settings = await db.get(userId, false);
  5184.  
  5185. if (settings) {
  5186. storage.values = settings;
  5187. return;
  5188. }
  5189.  
  5190. const values = getAllValuesStartingWith(GM_info.script.name);
  5191. for (const value of values) {
  5192. let val = null;
  5193. try {
  5194. val = JSON.parse(value.val);
  5195. } catch {
  5196. break;
  5197. }
  5198. storage.values[value.key] = val;
  5199. }
  5200. await db.set(userId, storage.values);
  5201. }
  5202.  
  5203. class ZingerYWebsiteAPI {
  5204. /**
  5205. * Class for interaction with the API of the zingery.ru website
  5206. * Intended only for use with the HeroWarsHelper script:
  5207. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  5208. * Copyright ZingerY
  5209. */
  5210. url = 'https://zingery.ru/heroes/';
  5211. // YWJzb2x1dGVseSB1c2VsZXNzIGxpbmU=
  5212. constructor(urn, env, data = {}) {
  5213. this.urn = urn;
  5214. this.fd = {
  5215. now: Date.now(),
  5216. fp: this.constructor.toString().replaceAll(/\s/g, ''),
  5217. env: env.callee.toString().replaceAll(/\s/g, ''),
  5218. info: (({ name, version, author }) => [name, version, author])(GM_info.script),
  5219. ...data,
  5220. };
  5221. }
  5222.  
  5223. sign() {
  5224. return md5([...this.fd.info, ~(this.fd.now % 1e3), this.fd.fp].join('_'));
  5225. }
  5226.  
  5227. encode(data) {
  5228. return btoa(encodeURIComponent(JSON.stringify(data)));
  5229. }
  5230.  
  5231. decode(data) {
  5232. return JSON.parse(decodeURIComponent(atob(data)));
  5233. }
  5234.  
  5235. headers() {
  5236. return {
  5237. 'X-Request-Signature': this.sign(),
  5238. 'X-Script-Name': GM_info.script.name,
  5239. 'X-Script-Version': GM_info.script.version,
  5240. 'X-Script-Author': GM_info.script.author,
  5241. 'X-Script-ZingerY': 42,
  5242. };
  5243. }
  5244.  
  5245. async request() {
  5246. try {
  5247. const response = await fetch(this.url + this.urn, {
  5248. method: 'POST',
  5249. headers: this.headers(),
  5250. body: this.encode(this.fd),
  5251. });
  5252. const text = await response.text();
  5253. return this.decode(text);
  5254. } catch (e) {
  5255. console.error(e);
  5256. return [];
  5257. }
  5258. }
  5259. /**
  5260. * Класс для взаимодействия с API сайта zingery.ru
  5261. * Предназначен только для использования со скриптом HeroWarsHelper:
  5262. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  5263. * Copyright ZingerY
  5264. */
  5265. }
  5266.  
  5267. /**
  5268. * Sending expeditions
  5269. *
  5270. * Отправка экспедиций
  5271. */
  5272. function checkExpedition() {
  5273. const { Expedition } = HWHClasses;
  5274. return new Promise((resolve, reject) => {
  5275. const expedition = new Expedition(resolve, reject);
  5276. expedition.start();
  5277. });
  5278. }
  5279.  
  5280. class Expedition {
  5281. checkExpedInfo = {
  5282. calls: [
  5283. {
  5284. name: 'expeditionGet',
  5285. args: {},
  5286. ident: 'expeditionGet',
  5287. },
  5288. {
  5289. name: 'heroGetAll',
  5290. args: {},
  5291. ident: 'heroGetAll',
  5292. },
  5293. ],
  5294. };
  5295.  
  5296. constructor(resolve, reject) {
  5297. this.resolve = resolve;
  5298. this.reject = reject;
  5299. }
  5300.  
  5301. async start() {
  5302. const data = await Send(JSON.stringify(this.checkExpedInfo));
  5303.  
  5304. const expedInfo = data.results[0].result.response;
  5305. const dataHeroes = data.results[1].result.response;
  5306. const dataExped = { useHeroes: [], exped: [] };
  5307. const calls = [];
  5308.  
  5309. /**
  5310. * Adding expeditions to collect
  5311. * Добавляем экспедиции для сбора
  5312. */
  5313. let countGet = 0;
  5314. for (var n in expedInfo) {
  5315. const exped = expedInfo[n];
  5316. const dateNow = Date.now() / 1000;
  5317. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  5318. countGet++;
  5319. calls.push({
  5320. name: 'expeditionFarm',
  5321. args: { expeditionId: exped.id },
  5322. ident: 'expeditionFarm_' + exped.id,
  5323. });
  5324. } else {
  5325. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  5326. }
  5327. if (exped.status == 1) {
  5328. dataExped.exped.push({ id: exped.id, power: exped.power });
  5329. }
  5330. }
  5331. dataExped.exped = dataExped.exped.sort((a, b) => b.power - a.power);
  5332.  
  5333. /**
  5334. * Putting together a list of heroes
  5335. * Собираем список героев
  5336. */
  5337. const heroesArr = [];
  5338. for (let n in dataHeroes) {
  5339. const hero = dataHeroes[n];
  5340. if (hero.power > 0 && !dataExped.useHeroes.includes(hero.id)) {
  5341. let heroPower = hero.power;
  5342. // Лара Крофт * 3
  5343. if (hero.id == 63 && hero.color >= 16) {
  5344. heroPower *= 3;
  5345. }
  5346. heroesArr.push({ id: hero.id, power: heroPower });
  5347. }
  5348. }
  5349.  
  5350. /**
  5351. * Adding expeditions to send
  5352. * Добавляем экспедиции для отправки
  5353. */
  5354. let countSend = 0;
  5355. heroesArr.sort((a, b) => a.power - b.power);
  5356. for (const exped of dataExped.exped) {
  5357. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  5358. if (heroesIds && heroesIds.length > 4) {
  5359. for (let q in heroesArr) {
  5360. if (heroesIds.includes(heroesArr[q].id)) {
  5361. delete heroesArr[q];
  5362. }
  5363. }
  5364. countSend++;
  5365. calls.push({
  5366. name: 'expeditionSendHeroes',
  5367. args: {
  5368. expeditionId: exped.id,
  5369. heroes: heroesIds,
  5370. },
  5371. ident: 'expeditionSendHeroes_' + exped.id,
  5372. });
  5373. }
  5374. }
  5375.  
  5376. if (calls.length) {
  5377. await Send({ calls });
  5378. this.end(I18N('EXPEDITIONS_SENT', {countGet, countSend}));
  5379. return;
  5380. }
  5381.  
  5382. this.end(I18N('EXPEDITIONS_NOTHING'));
  5383. }
  5384.  
  5385. /**
  5386. * Selection of heroes for expeditions
  5387. *
  5388. * Подбор героев для экспедиций
  5389. */
  5390. selectionHeroes(heroes, power) {
  5391. const resultHeroers = [];
  5392. const heroesIds = [];
  5393. for (let q = 0; q < 5; q++) {
  5394. for (let i in heroes) {
  5395. let hero = heroes[i];
  5396. if (heroesIds.includes(hero.id)) {
  5397. continue;
  5398. }
  5399.  
  5400. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5401. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  5402. if (hero.power > need) {
  5403. resultHeroers.push(hero);
  5404. heroesIds.push(hero.id);
  5405. break;
  5406. }
  5407. }
  5408. }
  5409.  
  5410. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5411. if (summ < power) {
  5412. return false;
  5413. }
  5414. return heroesIds;
  5415. }
  5416.  
  5417. /**
  5418. * Ends expedition script
  5419. *
  5420. * Завершает скрипт экспедиции
  5421. */
  5422. end(msg) {
  5423. setProgress(msg, true);
  5424. this.resolve();
  5425. }
  5426. }
  5427.  
  5428. this.HWHClasses.Expedition = Expedition;
  5429.  
  5430. /**
  5431. * Walkthrough of the dungeon
  5432. *
  5433. * Прохождение подземелья
  5434. */
  5435. function testDungeon() {
  5436. const { executeDungeon } = HWHClasses;
  5437. return new Promise((resolve, reject) => {
  5438. const dung = new executeDungeon(resolve, reject);
  5439. const titanit = getInput('countTitanit');
  5440. dung.start(titanit);
  5441. });
  5442. }
  5443.  
  5444. /**
  5445. * Walkthrough of the dungeon
  5446. *
  5447. * Прохождение подземелья
  5448. */
  5449. function executeDungeon(resolve, reject) {
  5450. dungeonActivity = 0;
  5451. maxDungeonActivity = 150;
  5452.  
  5453. titanGetAll = [];
  5454.  
  5455. teams = {
  5456. heroes: [],
  5457. earth: [],
  5458. fire: [],
  5459. neutral: [],
  5460. water: [],
  5461. }
  5462.  
  5463. titanStats = [];
  5464.  
  5465. titansStates = {};
  5466.  
  5467. let talentMsg = '';
  5468. let talentMsgReward = '';
  5469.  
  5470. callsExecuteDungeon = {
  5471. calls: [{
  5472. name: "dungeonGetInfo",
  5473. args: {},
  5474. ident: "dungeonGetInfo"
  5475. }, {
  5476. name: "teamGetAll",
  5477. args: {},
  5478. ident: "teamGetAll"
  5479. }, {
  5480. name: "teamGetFavor",
  5481. args: {},
  5482. ident: "teamGetFavor"
  5483. }, {
  5484. name: "clanGetInfo",
  5485. args: {},
  5486. ident: "clanGetInfo"
  5487. }, {
  5488. name: "titanGetAll",
  5489. args: {},
  5490. ident: "titanGetAll"
  5491. }, {
  5492. name: "inventoryGet",
  5493. args: {},
  5494. ident: "inventoryGet"
  5495. }]
  5496. }
  5497.  
  5498. this.start = function(titanit) {
  5499. maxDungeonActivity = titanit || getInput('countTitanit');
  5500. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  5501. }
  5502.  
  5503. /**
  5504. * Getting data on the dungeon
  5505. *
  5506. * Получаем данные по подземелью
  5507. */
  5508. function startDungeon(e) {
  5509. res = e.results;
  5510. dungeonGetInfo = res[0].result.response;
  5511. if (!dungeonGetInfo) {
  5512. endDungeon('noDungeon', res);
  5513. return;
  5514. }
  5515. teamGetAll = res[1].result.response;
  5516. teamGetFavor = res[2].result.response;
  5517. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  5518. titanGetAll = Object.values(res[4].result.response);
  5519. countPredictionCard = res[5].result.response.consumable[81];
  5520.  
  5521. teams.hero = {
  5522. favor: teamGetFavor.dungeon_hero,
  5523. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  5524. teamNum: 0,
  5525. }
  5526. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  5527. if (heroPet) {
  5528. teams.hero.pet = heroPet;
  5529. }
  5530.  
  5531. teams.neutral = {
  5532. favor: {},
  5533. heroes: getTitanTeam(titanGetAll, 'neutral'),
  5534. teamNum: 0,
  5535. };
  5536. teams.water = {
  5537. favor: {},
  5538. heroes: getTitanTeam(titanGetAll, 'water'),
  5539. teamNum: 0,
  5540. };
  5541. teams.fire = {
  5542. favor: {},
  5543. heroes: getTitanTeam(titanGetAll, 'fire'),
  5544. teamNum: 0,
  5545. };
  5546. teams.earth = {
  5547. favor: {},
  5548. heroes: getTitanTeam(titanGetAll, 'earth'),
  5549. teamNum: 0,
  5550. };
  5551.  
  5552.  
  5553. checkFloor(dungeonGetInfo);
  5554. }
  5555.  
  5556. function getTitanTeam(titans, type) {
  5557. switch (type) {
  5558. case 'neutral':
  5559. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5560. case 'water':
  5561. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  5562. case 'fire':
  5563. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  5564. case 'earth':
  5565. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  5566. }
  5567. }
  5568.  
  5569. function getNeutralTeam() {
  5570. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5571. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5572. }
  5573.  
  5574. function fixTitanTeam(titans) {
  5575. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  5576. return titans;
  5577. }
  5578.  
  5579. /**
  5580. * Checking the floor
  5581. *
  5582. * Проверяем этаж
  5583. */
  5584. async function checkFloor(dungeonInfo) {
  5585. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  5586. saveProgress();
  5587. return;
  5588. }
  5589. checkTalent(dungeonInfo);
  5590. // console.log(dungeonInfo, dungeonActivity);
  5591. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5592. if (dungeonActivity >= maxDungeonActivity) {
  5593. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  5594. return;
  5595. }
  5596. titansStates = dungeonInfo.states.titans;
  5597. titanStats = titanObjToArray(titansStates);
  5598. const floorChoices = dungeonInfo.floor.userData;
  5599. const floorType = dungeonInfo.floorType;
  5600. //const primeElement = dungeonInfo.elements.prime;
  5601. if (floorType == "battle") {
  5602. const calls = [];
  5603. for (let teamNum in floorChoices) {
  5604. attackerType = floorChoices[teamNum].attackerType;
  5605. const args = fixTitanTeam(teams[attackerType]);
  5606. if (attackerType == 'neutral') {
  5607. args.heroes = getNeutralTeam();
  5608. }
  5609. if (!args.heroes.length) {
  5610. continue;
  5611. }
  5612. args.teamNum = teamNum;
  5613. calls.push({
  5614. name: "dungeonStartBattle",
  5615. args,
  5616. ident: "body_" + teamNum
  5617. })
  5618. }
  5619. if (!calls.length) {
  5620. endDungeon('endDungeon', 'All Dead');
  5621. return;
  5622. }
  5623. const battleDatas = await Send(JSON.stringify({ calls }))
  5624. .then(e => e.results.map(n => n.result.response))
  5625. const battleResults = [];
  5626. for (n in battleDatas) {
  5627. battleData = battleDatas[n]
  5628. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5629. battleResults.push(await Calc(battleData).then(result => {
  5630. result.teamNum = n;
  5631. result.attackerType = floorChoices[n].attackerType;
  5632. return result;
  5633. }));
  5634. }
  5635. processingPromises(battleResults)
  5636. }
  5637. }
  5638.  
  5639. async function checkTalent(dungeonInfo) {
  5640. const talent = dungeonInfo.talent;
  5641. if (!talent) {
  5642. return;
  5643. }
  5644. const dungeonFloor = +dungeonInfo.floorNumber;
  5645. const talentFloor = +talent.floorRandValue;
  5646. let doorsAmount = 3 - talent.conditions.doorsAmount;
  5647.  
  5648. if (dungeonFloor === talentFloor && (!doorsAmount || !talent.conditions?.farmedDoors[dungeonFloor])) {
  5649. const reward = await Send({
  5650. calls: [
  5651. { name: 'heroTalent_getReward', args: { talentType: 'tmntDungeonTalent', reroll: false }, ident: 'group_0_body' },
  5652. { name: 'heroTalent_farmReward', args: { talentType: 'tmntDungeonTalent' }, ident: 'group_1_body' },
  5653. ],
  5654. }).then((e) => e.results[0].result.response);
  5655. const type = Object.keys(reward).pop();
  5656. const itemId = Object.keys(reward[type]).pop();
  5657. const count = reward[type][itemId];
  5658. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  5659. talentMsgReward += `<br> ${count} ${itemName}`;
  5660. doorsAmount++;
  5661. }
  5662. talentMsg = `<br>TMNT Talent: ${doorsAmount}/3 ${talentMsgReward}<br>`;
  5663. }
  5664.  
  5665. function processingPromises(results) {
  5666. let selectBattle = results[0];
  5667. if (results.length < 2) {
  5668. // console.log(selectBattle);
  5669. if (!selectBattle.result.win) {
  5670. endDungeon('dungeonEndBattle\n', selectBattle);
  5671. return;
  5672. }
  5673. endBattle(selectBattle);
  5674. return;
  5675. }
  5676.  
  5677. selectBattle = false;
  5678. let bestState = -1000;
  5679. for (const result of results) {
  5680. const recovery = getState(result);
  5681. if (recovery > bestState) {
  5682. bestState = recovery;
  5683. selectBattle = result
  5684. }
  5685. }
  5686. // console.log(selectBattle.teamNum, results);
  5687. if (!selectBattle || bestState <= -1000) {
  5688. endDungeon('dungeonEndBattle\n', results);
  5689. return;
  5690. }
  5691.  
  5692. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  5693. .then(endBattle);
  5694. }
  5695.  
  5696. /**
  5697. * Let's start the fight
  5698. *
  5699. * Начинаем бой
  5700. */
  5701. function startBattle(teamNum, attackerType) {
  5702. return new Promise(function (resolve, reject) {
  5703. args = fixTitanTeam(teams[attackerType]);
  5704. args.teamNum = teamNum;
  5705. if (attackerType == 'neutral') {
  5706. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5707. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5708. }
  5709. startBattleCall = {
  5710. calls: [{
  5711. name: "dungeonStartBattle",
  5712. args,
  5713. ident: "body"
  5714. }]
  5715. }
  5716. send(JSON.stringify(startBattleCall), resultBattle, {
  5717. resolve,
  5718. teamNum,
  5719. attackerType
  5720. });
  5721. });
  5722. }
  5723. /**
  5724. * Returns the result of the battle in a promise
  5725. *
  5726. * Возращает резульат боя в промис
  5727. */
  5728. function resultBattle(resultBattles, args) {
  5729. battleData = resultBattles.results[0].result.response;
  5730. battleType = "get_tower";
  5731. if (battleData.type == "dungeon_titan") {
  5732. battleType = "get_titan";
  5733. }
  5734. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5735. BattleCalc(battleData, battleType, function (result) {
  5736. result.teamNum = args.teamNum;
  5737. result.attackerType = args.attackerType;
  5738. args.resolve(result);
  5739. });
  5740. }
  5741. /**
  5742. * Finishing the fight
  5743. *
  5744. * Заканчиваем бой
  5745. */
  5746. async function endBattle(battleInfo) {
  5747. if (battleInfo.result.win) {
  5748. const args = {
  5749. result: battleInfo.result,
  5750. progress: battleInfo.progress,
  5751. }
  5752. if (countPredictionCard > 0) {
  5753. args.isRaid = true;
  5754. } else {
  5755. const timer = getTimer(battleInfo.battleTime);
  5756. console.log(timer);
  5757. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5758. }
  5759. const calls = [{
  5760. name: "dungeonEndBattle",
  5761. args,
  5762. ident: "body"
  5763. }];
  5764. lastDungeonBattleData = null;
  5765. send(JSON.stringify({ calls }), resultEndBattle);
  5766. } else {
  5767. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  5768. }
  5769. }
  5770.  
  5771. /**
  5772. * Getting and processing battle results
  5773. *
  5774. * Получаем и обрабатываем результаты боя
  5775. */
  5776. function resultEndBattle(e) {
  5777. if ('error' in e) {
  5778. popup.confirm(I18N('ERROR_MSG', {
  5779. name: e.error.name,
  5780. description: e.error.description,
  5781. }));
  5782. endDungeon('errorRequest', e);
  5783. return;
  5784. }
  5785. battleResult = e.results[0].result.response;
  5786. if ('error' in battleResult) {
  5787. endDungeon('errorBattleResult', battleResult);
  5788. return;
  5789. }
  5790. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  5791. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  5792. checkFloor(dungeonGetInfo);
  5793. }
  5794.  
  5795. /**
  5796. * Returns the coefficient of condition of the
  5797. * difference in titanium before and after the battle
  5798. *
  5799. * Возвращает коэффициент состояния титанов после боя
  5800. */
  5801. function getState(result) {
  5802. if (!result.result.win) {
  5803. return -1000;
  5804. }
  5805.  
  5806. let beforeSumFactor = 0;
  5807. const beforeTitans = result.battleData.attackers;
  5808. for (let titanId in beforeTitans) {
  5809. const titan = beforeTitans[titanId];
  5810. const state = titan.state;
  5811. let factor = 1;
  5812. if (state) {
  5813. const hp = state.hp / titan.hp;
  5814. const energy = state.energy / 1e3;
  5815. factor = hp + energy / 20
  5816. }
  5817. beforeSumFactor += factor;
  5818. }
  5819.  
  5820. let afterSumFactor = 0;
  5821. const afterTitans = result.progress[0].attackers.heroes;
  5822. for (let titanId in afterTitans) {
  5823. const titan = afterTitans[titanId];
  5824. const hp = titan.hp / beforeTitans[titanId].hp;
  5825. const energy = titan.energy / 1e3;
  5826. const factor = hp + energy / 20;
  5827. afterSumFactor += factor;
  5828. }
  5829. return afterSumFactor - beforeSumFactor;
  5830. }
  5831.  
  5832. /**
  5833. * Converts an object with IDs to an array with IDs
  5834. *
  5835. * Преобразует объект с идетификаторами в массив с идетификаторами
  5836. */
  5837. function titanObjToArray(obj) {
  5838. let titans = [];
  5839. for (let id in obj) {
  5840. obj[id].id = id;
  5841. titans.push(obj[id]);
  5842. }
  5843. return titans;
  5844. }
  5845.  
  5846. function saveProgress() {
  5847. let saveProgressCall = {
  5848. calls: [{
  5849. name: "dungeonSaveProgress",
  5850. args: {},
  5851. ident: "body"
  5852. }]
  5853. }
  5854. send(JSON.stringify(saveProgressCall), resultEndBattle);
  5855. }
  5856.  
  5857. function endDungeon(reason, info) {
  5858. console.warn(reason, info);
  5859. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  5860. resolve();
  5861. }
  5862. }
  5863.  
  5864. this.HWHClasses.executeDungeon = executeDungeon;
  5865.  
  5866. /**
  5867. * Passing the tower
  5868. *
  5869. * Прохождение башни
  5870. */
  5871. function testTower() {
  5872. const { executeTower } = HWHClasses;
  5873. return new Promise((resolve, reject) => {
  5874. tower = new executeTower(resolve, reject);
  5875. tower.start();
  5876. });
  5877. }
  5878.  
  5879. /**
  5880. * Passing the tower
  5881. *
  5882. * Прохождение башни
  5883. */
  5884. function executeTower(resolve, reject) {
  5885. lastTowerInfo = {};
  5886.  
  5887. scullCoin = 0;
  5888.  
  5889. heroGetAll = [];
  5890.  
  5891. heroesStates = {};
  5892.  
  5893. argsBattle = {
  5894. heroes: [],
  5895. favor: {},
  5896. };
  5897.  
  5898. callsExecuteTower = {
  5899. calls: [{
  5900. name: "towerGetInfo",
  5901. args: {},
  5902. ident: "towerGetInfo"
  5903. }, {
  5904. name: "teamGetAll",
  5905. args: {},
  5906. ident: "teamGetAll"
  5907. }, {
  5908. name: "teamGetFavor",
  5909. args: {},
  5910. ident: "teamGetFavor"
  5911. }, {
  5912. name: "inventoryGet",
  5913. args: {},
  5914. ident: "inventoryGet"
  5915. }, {
  5916. name: "heroGetAll",
  5917. args: {},
  5918. ident: "heroGetAll"
  5919. }]
  5920. }
  5921.  
  5922. buffIds = [
  5923. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  5924. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  5925. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  5926. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  5927. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  5928. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  5929. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  5930. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  5931. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  5932. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5933. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  5934. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5935. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  5936. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  5937. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  5938. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  5939. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  5940. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5941. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5942. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  5943. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  5944. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  5945. ]
  5946.  
  5947. this.start = function () {
  5948. send(JSON.stringify(callsExecuteTower), startTower);
  5949. }
  5950.  
  5951. /**
  5952. * Getting data on the Tower
  5953. *
  5954. * Получаем данные по башне
  5955. */
  5956. function startTower(e) {
  5957. res = e.results;
  5958. towerGetInfo = res[0].result.response;
  5959. if (!towerGetInfo) {
  5960. endTower('noTower', res);
  5961. return;
  5962. }
  5963. teamGetAll = res[1].result.response;
  5964. teamGetFavor = res[2].result.response;
  5965. inventoryGet = res[3].result.response;
  5966. heroGetAll = Object.values(res[4].result.response);
  5967.  
  5968. scullCoin = inventoryGet.coin[7] ?? 0;
  5969.  
  5970. argsBattle.favor = teamGetFavor.tower;
  5971. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5972. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  5973. if (pet) {
  5974. argsBattle.pet = pet;
  5975. }
  5976.  
  5977. checkFloor(towerGetInfo);
  5978. }
  5979.  
  5980. function fixHeroesTeam(argsBattle) {
  5981. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  5982. if (fixHeroes.length < 5) {
  5983. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  5984. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5985. Object.keys(argsBattle.favor).forEach(e => {
  5986. if (!fixHeroes.includes(+e)) {
  5987. delete argsBattle.favor[e];
  5988. }
  5989. })
  5990. }
  5991. argsBattle.heroes = fixHeroes;
  5992. return argsBattle;
  5993. }
  5994.  
  5995. /**
  5996. * Check the floor
  5997. *
  5998. * Проверяем этаж
  5999. */
  6000. function checkFloor(towerInfo) {
  6001. lastTowerInfo = towerInfo;
  6002. maySkipFloor = +towerInfo.maySkipFloor;
  6003. floorNumber = +towerInfo.floorNumber;
  6004. heroesStates = towerInfo.states.heroes;
  6005. floorInfo = towerInfo.floor;
  6006.  
  6007. /**
  6008. * Is there at least one chest open on the floor
  6009. * Открыт ли на этаже хоть один сундук
  6010. */
  6011. isOpenChest = false;
  6012. if (towerInfo.floorType == "chest") {
  6013. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  6014. }
  6015.  
  6016. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  6017. if (floorNumber > 49) {
  6018. if (isOpenChest) {
  6019. endTower('alreadyOpenChest 50 floor', floorNumber);
  6020. return;
  6021. }
  6022. }
  6023. /**
  6024. * If the chest is open and you can skip floors, then move on
  6025. * Если сундук открыт и можно скипать этажи, то переходим дальше
  6026. */
  6027. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  6028. if (floorNumber == 1) {
  6029. fullSkipTower();
  6030. return;
  6031. }
  6032. if (isOpenChest) {
  6033. nextOpenChest(floorNumber);
  6034. } else {
  6035. nextChestOpen(floorNumber);
  6036. }
  6037. return;
  6038. }
  6039.  
  6040. // console.log(towerInfo, scullCoin);
  6041. switch (towerInfo.floorType) {
  6042. case "battle":
  6043. if (floorNumber <= maySkipFloor) {
  6044. skipFloor();
  6045. return;
  6046. }
  6047. if (floorInfo.state == 2) {
  6048. nextFloor();
  6049. return;
  6050. }
  6051. startBattle().then(endBattle);
  6052. return;
  6053. case "buff":
  6054. checkBuff(towerInfo);
  6055. return;
  6056. case "chest":
  6057. openChest(floorNumber);
  6058. return;
  6059. default:
  6060. console.log('!', towerInfo.floorType, towerInfo);
  6061. break;
  6062. }
  6063. }
  6064.  
  6065. /**
  6066. * Let's start the fight
  6067. *
  6068. * Начинаем бой
  6069. */
  6070. function startBattle() {
  6071. return new Promise(function (resolve, reject) {
  6072. towerStartBattle = {
  6073. calls: [{
  6074. name: "towerStartBattle",
  6075. args: fixHeroesTeam(argsBattle),
  6076. ident: "body"
  6077. }]
  6078. }
  6079. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  6080. });
  6081. }
  6082. /**
  6083. * Returns the result of the battle in a promise
  6084. *
  6085. * Возращает резульат боя в промис
  6086. */
  6087. function resultBattle(resultBattles, resolve) {
  6088. battleData = resultBattles.results[0].result.response;
  6089. battleType = "get_tower";
  6090. BattleCalc(battleData, battleType, function (result) {
  6091. resolve(result);
  6092. });
  6093. }
  6094. /**
  6095. * Finishing the fight
  6096. *
  6097. * Заканчиваем бой
  6098. */
  6099. function endBattle(battleInfo) {
  6100. if (battleInfo.result.stars >= 3) {
  6101. endBattleCall = {
  6102. calls: [{
  6103. name: "towerEndBattle",
  6104. args: {
  6105. result: battleInfo.result,
  6106. progress: battleInfo.progress,
  6107. },
  6108. ident: "body"
  6109. }]
  6110. }
  6111. send(JSON.stringify(endBattleCall), resultEndBattle);
  6112. } else {
  6113. endTower('towerEndBattle win: false\n', battleInfo);
  6114. }
  6115. }
  6116.  
  6117. /**
  6118. * Getting and processing battle results
  6119. *
  6120. * Получаем и обрабатываем результаты боя
  6121. */
  6122. function resultEndBattle(e) {
  6123. battleResult = e.results[0].result.response;
  6124. if ('error' in battleResult) {
  6125. endTower('errorBattleResult', battleResult);
  6126. return;
  6127. }
  6128. if ('reward' in battleResult) {
  6129. scullCoin += battleResult.reward?.coin[7] ?? 0;
  6130. }
  6131. nextFloor();
  6132. }
  6133.  
  6134. function nextFloor() {
  6135. nextFloorCall = {
  6136. calls: [{
  6137. name: "towerNextFloor",
  6138. args: {},
  6139. ident: "body"
  6140. }]
  6141. }
  6142. send(JSON.stringify(nextFloorCall), checkDataFloor);
  6143. }
  6144.  
  6145. function openChest(floorNumber) {
  6146. floorNumber = floorNumber || 0;
  6147. openChestCall = {
  6148. calls: [{
  6149. name: "towerOpenChest",
  6150. args: {
  6151. num: 2
  6152. },
  6153. ident: "body"
  6154. }]
  6155. }
  6156. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  6157. }
  6158.  
  6159. function lastChest() {
  6160. endTower('openChest 50 floor', floorNumber);
  6161. }
  6162.  
  6163. function skipFloor() {
  6164. skipFloorCall = {
  6165. calls: [{
  6166. name: "towerSkipFloor",
  6167. args: {},
  6168. ident: "body"
  6169. }]
  6170. }
  6171. send(JSON.stringify(skipFloorCall), checkDataFloor);
  6172. }
  6173.  
  6174. function checkBuff(towerInfo) {
  6175. buffArr = towerInfo.floor;
  6176. promises = [];
  6177. for (let buff of buffArr) {
  6178. buffInfo = buffIds[buff.id];
  6179. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  6180. scullCoin -= buffInfo.cost;
  6181. promises.push(buyBuff(buff.id));
  6182. }
  6183. }
  6184. Promise.all(promises).then(nextFloor);
  6185. }
  6186.  
  6187. function buyBuff(buffId) {
  6188. return new Promise(function (resolve, reject) {
  6189. buyBuffCall = {
  6190. calls: [{
  6191. name: "towerBuyBuff",
  6192. args: {
  6193. buffId
  6194. },
  6195. ident: "body"
  6196. }]
  6197. }
  6198. send(JSON.stringify(buyBuffCall), resolve);
  6199. });
  6200. }
  6201.  
  6202. function checkDataFloor(result) {
  6203. towerInfo = result.results[0].result.response;
  6204. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  6205. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  6206. }
  6207. if ('tower' in towerInfo) {
  6208. towerInfo = towerInfo.tower;
  6209. }
  6210. if ('skullReward' in towerInfo) {
  6211. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6212. }
  6213. checkFloor(towerInfo);
  6214. }
  6215. /**
  6216. * Getting tower rewards
  6217. *
  6218. * Получаем награды башни
  6219. */
  6220. function farmTowerRewards(reason) {
  6221. let { pointRewards, points } = lastTowerInfo;
  6222. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  6223. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  6224. if (!farmPoints.length) {
  6225. return;
  6226. }
  6227. let farmTowerRewardsCall = {
  6228. calls: [{
  6229. name: "tower_farmPointRewards",
  6230. args: {
  6231. points: farmPoints
  6232. },
  6233. ident: "tower_farmPointRewards"
  6234. }]
  6235. }
  6236.  
  6237. if (scullCoin > 0) {
  6238. farmTowerRewardsCall.calls.push({
  6239. name: "tower_farmSkullReward",
  6240. args: {},
  6241. ident: "tower_farmSkullReward"
  6242. });
  6243. }
  6244.  
  6245. send(JSON.stringify(farmTowerRewardsCall), () => { });
  6246. }
  6247.  
  6248. function fullSkipTower() {
  6249. /**
  6250. * Next chest
  6251. *
  6252. * Следующий сундук
  6253. */
  6254. function nextChest(n) {
  6255. return {
  6256. name: "towerNextChest",
  6257. args: {},
  6258. ident: "group_" + n + "_body"
  6259. }
  6260. }
  6261. /**
  6262. * Open chest
  6263. *
  6264. * Открыть сундук
  6265. */
  6266. function openChest(n) {
  6267. return {
  6268. name: "towerOpenChest",
  6269. args: {
  6270. "num": 2
  6271. },
  6272. ident: "group_" + n + "_body"
  6273. }
  6274. }
  6275.  
  6276. const fullSkipTowerCall = {
  6277. calls: []
  6278. }
  6279.  
  6280. let n = 0;
  6281. for (let i = 0; i < 15; i++) {
  6282. // 15 сундуков
  6283. fullSkipTowerCall.calls.push(nextChest(++n));
  6284. fullSkipTowerCall.calls.push(openChest(++n));
  6285. // +5 сундуков, 250 изюма // towerOpenChest
  6286. // if (i < 5) {
  6287. // fullSkipTowerCall.calls.push(openChest(++n, 2));
  6288. // }
  6289. }
  6290.  
  6291. fullSkipTowerCall.calls.push({
  6292. name: 'towerGetInfo',
  6293. args: {},
  6294. ident: 'group_' + ++n + '_body',
  6295. });
  6296.  
  6297. send(JSON.stringify(fullSkipTowerCall), data => {
  6298. for (const r of data.results) {
  6299. const towerInfo = r?.result?.response;
  6300. if (towerInfo && 'skullReward' in towerInfo) {
  6301. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6302. }
  6303. }
  6304. data.results[0] = data.results[data.results.length - 1];
  6305. checkDataFloor(data);
  6306. });
  6307. }
  6308.  
  6309. function nextChestOpen(floorNumber) {
  6310. const calls = [{
  6311. name: "towerOpenChest",
  6312. args: {
  6313. num: 2
  6314. },
  6315. ident: "towerOpenChest"
  6316. }];
  6317.  
  6318. Send(JSON.stringify({ calls })).then(e => {
  6319. nextOpenChest(floorNumber);
  6320. });
  6321. }
  6322.  
  6323. function nextOpenChest(floorNumber) {
  6324. if (floorNumber > 49) {
  6325. endTower('openChest 50 floor', floorNumber);
  6326. return;
  6327. }
  6328.  
  6329. let nextOpenChestCall = {
  6330. calls: [{
  6331. name: "towerNextChest",
  6332. args: {},
  6333. ident: "towerNextChest"
  6334. }, {
  6335. name: "towerOpenChest",
  6336. args: {
  6337. num: 2
  6338. },
  6339. ident: "towerOpenChest"
  6340. }]
  6341. }
  6342. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  6343. }
  6344.  
  6345. function endTower(reason, info) {
  6346. console.log(reason, info);
  6347. if (reason != 'noTower') {
  6348. farmTowerRewards(reason);
  6349. }
  6350. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  6351. resolve();
  6352. }
  6353. }
  6354.  
  6355. this.HWHClasses.executeTower = executeTower;
  6356.  
  6357. /**
  6358. * Passage of the arena of the titans
  6359. *
  6360. * Прохождение арены титанов
  6361. */
  6362. function testTitanArena() {
  6363. const { executeTitanArena } = HWHClasses;
  6364. return new Promise((resolve, reject) => {
  6365. titAren = new executeTitanArena(resolve, reject);
  6366. titAren.start();
  6367. });
  6368. }
  6369.  
  6370. /**
  6371. * Passage of the arena of the titans
  6372. *
  6373. * Прохождение арены титанов
  6374. */
  6375. function executeTitanArena(resolve, reject) {
  6376. let titan_arena = [];
  6377. let finishListBattle = [];
  6378. /**
  6379. * ID of the current batch
  6380. *
  6381. * Идетификатор текущей пачки
  6382. */
  6383. let currentRival = 0;
  6384. /**
  6385. * Number of attempts to finish off the pack
  6386. *
  6387. * Количество попыток добития пачки
  6388. */
  6389. let attempts = 0;
  6390. /**
  6391. * Was there an attempt to finish off the current shooting range
  6392. *
  6393. * Была ли попытка добития текущего тира
  6394. */
  6395. let isCheckCurrentTier = false;
  6396. /**
  6397. * Current shooting range
  6398. *
  6399. * Текущий тир
  6400. */
  6401. let currTier = 0;
  6402. /**
  6403. * Number of battles on the current dash
  6404. *
  6405. * Количество битв на текущем тире
  6406. */
  6407. let countRivalsTier = 0;
  6408.  
  6409. let callsStart = {
  6410. calls: [{
  6411. name: "titanArenaGetStatus",
  6412. args: {},
  6413. ident: "titanArenaGetStatus"
  6414. }, {
  6415. name: "teamGetAll",
  6416. args: {},
  6417. ident: "teamGetAll"
  6418. }]
  6419. }
  6420.  
  6421. this.start = function () {
  6422. send(JSON.stringify(callsStart), startTitanArena);
  6423. }
  6424.  
  6425. function startTitanArena(data) {
  6426. let titanArena = data.results[0].result.response;
  6427. if (titanArena.status == 'disabled') {
  6428. endTitanArena('disabled', titanArena);
  6429. return;
  6430. }
  6431.  
  6432. let teamGetAll = data.results[1].result.response;
  6433. titan_arena = teamGetAll.titan_arena;
  6434.  
  6435. checkTier(titanArena)
  6436. }
  6437.  
  6438. function checkTier(titanArena) {
  6439. if (titanArena.status == "peace_time") {
  6440. endTitanArena('Peace_time', titanArena);
  6441. return;
  6442. }
  6443. currTier = titanArena.tier;
  6444. if (currTier) {
  6445. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  6446. }
  6447.  
  6448. if (titanArena.status == "completed_tier") {
  6449. titanArenaCompleteTier();
  6450. return;
  6451. }
  6452. /**
  6453. * Checking for the possibility of a raid
  6454. * Проверка на возможность рейда
  6455. */
  6456. if (titanArena.canRaid) {
  6457. titanArenaStartRaid();
  6458. return;
  6459. }
  6460. /**
  6461. * Check was an attempt to achieve the current shooting range
  6462. * Проверка была ли попытка добития текущего тира
  6463. */
  6464. if (!isCheckCurrentTier) {
  6465. checkRivals(titanArena.rivals);
  6466. return;
  6467. }
  6468.  
  6469. endTitanArena('Done or not canRaid', titanArena);
  6470. }
  6471. /**
  6472. * Submit dash information for verification
  6473. *
  6474. * Отправка информации о тире на проверку
  6475. */
  6476. function checkResultInfo(data) {
  6477. let titanArena = data.results[0].result.response;
  6478. checkTier(titanArena);
  6479. }
  6480. /**
  6481. * Finish the current tier
  6482. *
  6483. * Завершить текущий тир
  6484. */
  6485. function titanArenaCompleteTier() {
  6486. isCheckCurrentTier = false;
  6487. let calls = [{
  6488. name: "titanArenaCompleteTier",
  6489. args: {},
  6490. ident: "body"
  6491. }];
  6492. send(JSON.stringify({calls}), checkResultInfo);
  6493. }
  6494. /**
  6495. * Gathering points to be completed
  6496. *
  6497. * Собираем точки которые нужно добить
  6498. */
  6499. function checkRivals(rivals) {
  6500. finishListBattle = [];
  6501. for (let n in rivals) {
  6502. if (rivals[n].attackScore < 250) {
  6503. finishListBattle.push(n);
  6504. }
  6505. }
  6506. console.log('checkRivals', finishListBattle);
  6507. countRivalsTier = finishListBattle.length;
  6508. roundRivals();
  6509. }
  6510. /**
  6511. * Selecting the next point to finish off
  6512. *
  6513. * Выбор следующей точки для добития
  6514. */
  6515. function roundRivals() {
  6516. let countRivals = finishListBattle.length;
  6517. if (!countRivals) {
  6518. /**
  6519. * Whole range checked
  6520. *
  6521. * Весь тир проверен
  6522. */
  6523. isCheckCurrentTier = true;
  6524. titanArenaGetStatus();
  6525. return;
  6526. }
  6527. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  6528. currentRival = finishListBattle.pop();
  6529. attempts = +currentRival;
  6530. // console.log('roundRivals', currentRival);
  6531. titanArenaStartBattle(currentRival);
  6532. }
  6533. /**
  6534. * The start of a solo battle
  6535. *
  6536. * Начало одиночной битвы
  6537. */
  6538. function titanArenaStartBattle(rivalId) {
  6539. let calls = [{
  6540. name: "titanArenaStartBattle",
  6541. args: {
  6542. rivalId: rivalId,
  6543. titans: titan_arena
  6544. },
  6545. ident: "body"
  6546. }];
  6547. send(JSON.stringify({calls}), calcResult);
  6548. }
  6549. /**
  6550. * Calculation of the results of the battle
  6551. *
  6552. * Расчет результатов боя
  6553. */
  6554. function calcResult(data) {
  6555. let battlesInfo = data.results[0].result.response.battle;
  6556. /**
  6557. * If attempts are equal to the current battle number we make
  6558. * Если попытки равны номеру текущего боя делаем прерасчет
  6559. */
  6560. if (attempts == currentRival) {
  6561. preCalcBattle(battlesInfo);
  6562. return;
  6563. }
  6564. /**
  6565. * If there are still attempts, we calculate a new battle
  6566. * Если попытки еще есть делаем расчет нового боя
  6567. */
  6568. if (attempts > 0) {
  6569. attempts--;
  6570. calcBattleResult(battlesInfo)
  6571. .then(resultCalcBattle);
  6572. return;
  6573. }
  6574. /**
  6575. * Otherwise, go to the next opponent
  6576. * Иначе переходим к следующему сопернику
  6577. */
  6578. roundRivals();
  6579. }
  6580. /**
  6581. * Processing the results of the battle calculation
  6582. *
  6583. * Обработка результатов расчета битвы
  6584. */
  6585. function resultCalcBattle(resultBattle) {
  6586. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  6587. /**
  6588. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  6589. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  6590. */
  6591. if (resultBattle.result.win || !attempts) {
  6592. titanArenaEndBattle({
  6593. progress: resultBattle.progress,
  6594. result: resultBattle.result,
  6595. rivalId: resultBattle.battleData.typeId
  6596. });
  6597. return;
  6598. }
  6599. /**
  6600. * If not victory and there are attempts we start a new battle
  6601. * Если не победа и есть попытки начинаем новый бой
  6602. */
  6603. titanArenaStartBattle(resultBattle.battleData.typeId);
  6604. }
  6605. /**
  6606. * Returns the promise of calculating the results of the battle
  6607. *
  6608. * Возращает промис расчета результатов битвы
  6609. */
  6610. function getBattleInfo(battle, isRandSeed) {
  6611. return new Promise(function (resolve) {
  6612. if (isRandSeed) {
  6613. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  6614. }
  6615. // console.log(battle.seed);
  6616. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  6617. });
  6618. }
  6619. /**
  6620. * Recalculate battles
  6621. *
  6622. * Прерасчтет битвы
  6623. */
  6624. function preCalcBattle(battle) {
  6625. let actions = [getBattleInfo(battle, false)];
  6626. const countTestBattle = getInput('countTestBattle');
  6627. for (let i = 0; i < countTestBattle; i++) {
  6628. actions.push(getBattleInfo(battle, true));
  6629. }
  6630. Promise.all(actions)
  6631. .then(resultPreCalcBattle);
  6632. }
  6633. /**
  6634. * Processing the results of the battle recalculation
  6635. *
  6636. * Обработка результатов прерасчета битвы
  6637. */
  6638. function resultPreCalcBattle(e) {
  6639. let wins = e.map(n => n.result.win);
  6640. let firstBattle = e.shift();
  6641. let countWin = wins.reduce((w, s) => w + s);
  6642. const countTestBattle = getInput('countTestBattle');
  6643. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  6644. if (countWin > 0) {
  6645. attempts = getInput('countAutoBattle');
  6646. } else {
  6647. attempts = 0;
  6648. }
  6649. resultCalcBattle(firstBattle);
  6650. }
  6651.  
  6652. /**
  6653. * Complete an arena battle
  6654. *
  6655. * Завершить битву на арене
  6656. */
  6657. function titanArenaEndBattle(args) {
  6658. let calls = [{
  6659. name: "titanArenaEndBattle",
  6660. args,
  6661. ident: "body"
  6662. }];
  6663. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  6664. }
  6665.  
  6666. function resultTitanArenaEndBattle(e) {
  6667. let attackScore = e.results[0].result.response.attackScore;
  6668. let numReval = countRivalsTier - finishListBattle.length;
  6669. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  6670. /**
  6671. * TODO: Might need to improve the results.
  6672. * TODO: Возможно стоит сделать улучшение результатов
  6673. */
  6674. // console.log('resultTitanArenaEndBattle', e)
  6675. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  6676. roundRivals();
  6677. }
  6678. /**
  6679. * Arena State
  6680. *
  6681. * Состояние арены
  6682. */
  6683. function titanArenaGetStatus() {
  6684. let calls = [{
  6685. name: "titanArenaGetStatus",
  6686. args: {},
  6687. ident: "body"
  6688. }];
  6689. send(JSON.stringify({calls}), checkResultInfo);
  6690. }
  6691. /**
  6692. * Arena Raid Request
  6693. *
  6694. * Запрос рейда арены
  6695. */
  6696. function titanArenaStartRaid() {
  6697. let calls = [{
  6698. name: "titanArenaStartRaid",
  6699. args: {
  6700. titans: titan_arena
  6701. },
  6702. ident: "body"
  6703. }];
  6704. send(JSON.stringify({calls}), calcResults);
  6705. }
  6706.  
  6707. function calcResults(data) {
  6708. let battlesInfo = data.results[0].result.response;
  6709. let {attackers, rivals} = battlesInfo;
  6710.  
  6711. let promises = [];
  6712. for (let n in rivals) {
  6713. rival = rivals[n];
  6714. promises.push(calcBattleResult({
  6715. attackers: attackers,
  6716. defenders: [rival.team],
  6717. seed: rival.seed,
  6718. typeId: n,
  6719. }));
  6720. }
  6721.  
  6722. Promise.all(promises)
  6723. .then(results => {
  6724. const endResults = {};
  6725. for (let info of results) {
  6726. let id = info.battleData.typeId;
  6727. endResults[id] = {
  6728. progress: info.progress,
  6729. result: info.result,
  6730. }
  6731. }
  6732. titanArenaEndRaid(endResults);
  6733. });
  6734. }
  6735.  
  6736. function calcBattleResult(battleData) {
  6737. return new Promise(function (resolve, reject) {
  6738. BattleCalc(battleData, "get_titanClanPvp", resolve);
  6739. });
  6740. }
  6741.  
  6742. /**
  6743. * Sending Raid Results
  6744. *
  6745. * Отправка результатов рейда
  6746. */
  6747. function titanArenaEndRaid(results) {
  6748. titanArenaEndRaidCall = {
  6749. calls: [{
  6750. name: "titanArenaEndRaid",
  6751. args: {
  6752. results
  6753. },
  6754. ident: "body"
  6755. }]
  6756. }
  6757. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  6758. }
  6759.  
  6760. function checkRaidResults(data) {
  6761. results = data.results[0].result.response.results;
  6762. isSucsesRaid = true;
  6763. for (let i in results) {
  6764. isSucsesRaid &&= (results[i].attackScore >= 250);
  6765. }
  6766.  
  6767. if (isSucsesRaid) {
  6768. titanArenaCompleteTier();
  6769. } else {
  6770. titanArenaGetStatus();
  6771. }
  6772. }
  6773.  
  6774. function titanArenaFarmDailyReward() {
  6775. titanArenaFarmDailyRewardCall = {
  6776. calls: [{
  6777. name: "titanArenaFarmDailyReward",
  6778. args: {},
  6779. ident: "body"
  6780. }]
  6781. }
  6782. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  6783. }
  6784.  
  6785. function endTitanArena(reason, info) {
  6786. if (!['Peace_time', 'disabled'].includes(reason)) {
  6787. titanArenaFarmDailyReward();
  6788. }
  6789. console.log(reason, info);
  6790. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  6791. resolve();
  6792. }
  6793. }
  6794.  
  6795. this.HWHClasses.executeTitanArena = executeTitanArena;
  6796.  
  6797. function hackGame() {
  6798. const self = this;
  6799. selfGame = null;
  6800. bindId = 1e9;
  6801. this.libGame = null;
  6802. this.doneLibLoad = () => {};
  6803.  
  6804. /**
  6805. * List of correspondence of used classes to their names
  6806. *
  6807. * Список соответствия используемых классов их названиям
  6808. */
  6809. ObjectsList = [
  6810. { name: 'BattlePresets', prop: 'game.battle.controller.thread.BattlePresets' },
  6811. { name: 'DataStorage', prop: 'game.data.storage.DataStorage' },
  6812. { name: 'BattleConfigStorage', prop: 'game.data.storage.battle.BattleConfigStorage' },
  6813. { name: 'BattleInstantPlay', prop: 'game.battle.controller.instant.BattleInstantPlay' },
  6814. { name: 'MultiBattleInstantReplay', prop: 'game.battle.controller.instant.MultiBattleInstantReplay' },
  6815. { name: 'MultiBattleResult', prop: 'game.battle.controller.MultiBattleResult' },
  6816.  
  6817. { name: 'PlayerMissionData', prop: 'game.model.user.mission.PlayerMissionData' },
  6818. { name: 'PlayerMissionBattle', prop: 'game.model.user.mission.PlayerMissionBattle' },
  6819. { name: 'GameModel', prop: 'game.model.GameModel' },
  6820. { name: 'CommandManager', prop: 'game.command.CommandManager' },
  6821. { name: 'MissionCommandList', prop: 'game.command.rpc.mission.MissionCommandList' },
  6822. { name: 'RPCCommandBase', prop: 'game.command.rpc.RPCCommandBase' },
  6823. { name: 'PlayerTowerData', prop: 'game.model.user.tower.PlayerTowerData' },
  6824. { name: 'TowerCommandList', prop: 'game.command.tower.TowerCommandList' },
  6825. { name: 'PlayerHeroTeamResolver', prop: 'game.model.user.hero.PlayerHeroTeamResolver' },
  6826. { name: 'BattlePausePopup', prop: 'game.view.popup.battle.BattlePausePopup' },
  6827. { name: 'BattlePopup', prop: 'game.view.popup.battle.BattlePopup' },
  6828. { name: 'DisplayObjectContainer', prop: 'starling.display.DisplayObjectContainer' },
  6829. { name: 'GuiClipContainer', prop: 'engine.core.clipgui.GuiClipContainer' },
  6830. { name: 'BattlePausePopupClip', prop: 'game.view.popup.battle.BattlePausePopupClip' },
  6831. { name: 'ClipLabel', prop: 'game.view.gui.components.ClipLabel' },
  6832. { name: 'ClipLabelBase', prop: 'game.view.gui.components.ClipLabelBase' },
  6833. { name: 'Translate', prop: 'com.progrestar.common.lang.Translate' },
  6834. { name: 'ClipButtonLabeledCentered', prop: 'game.view.gui.components.ClipButtonLabeledCentered' },
  6835. { name: 'BattlePausePopupMediator', prop: 'game.mediator.gui.popup.battle.BattlePausePopupMediator' },
  6836. { name: 'SettingToggleButton', prop: 'game.mechanics.settings.popup.view.SettingToggleButton' },
  6837. { name: 'PlayerDungeonData', prop: 'game.mechanics.dungeon.model.PlayerDungeonData' },
  6838. { name: 'NextDayUpdatedManager', prop: 'game.model.user.NextDayUpdatedManager' },
  6839. { name: 'BattleController', prop: 'game.battle.controller.BattleController' },
  6840. { name: 'BattleSettingsModel', prop: 'game.battle.controller.BattleSettingsModel' },
  6841. { name: 'BooleanProperty', prop: 'engine.core.utils.property.BooleanProperty' },
  6842. { name: 'RuleStorage', prop: 'game.data.storage.rule.RuleStorage' },
  6843. { name: 'BattleConfig', prop: 'battle.BattleConfig' },
  6844. { name: 'BattleGuiMediator', prop: 'game.battle.gui.BattleGuiMediator' },
  6845. { name: 'BooleanPropertyWriteable', prop: 'engine.core.utils.property.BooleanPropertyWriteable' },
  6846. { name: 'BattleLogEncoder', prop: 'battle.log.BattleLogEncoder' },
  6847. { name: 'BattleLogReader', prop: 'battle.log.BattleLogReader' },
  6848. { name: 'PlayerSubscriptionInfoValueObject', prop: 'game.model.user.subscription.PlayerSubscriptionInfoValueObject' },
  6849. { name: 'AdventureMapCamera', prop: 'game.mechanics.adventure.popup.map.AdventureMapCamera' },
  6850. ];
  6851.  
  6852. /**
  6853. * Contains the game classes needed to write and override game methods
  6854. *
  6855. * Содержит классы игры необходимые для написания и подмены методов игры
  6856. */
  6857. Game = {
  6858. /**
  6859. * Function 'e'
  6860. * Функция 'e'
  6861. */
  6862. bindFunc: function (a, b) {
  6863. if (null == b) return null;
  6864. null == b.__id__ && (b.__id__ = bindId++);
  6865. var c;
  6866. null == a.hx__closures__ ? (a.hx__closures__ = {}) : (c = a.hx__closures__[b.__id__]);
  6867. null == c && ((c = b.bind(a)), (a.hx__closures__[b.__id__] = c));
  6868. return c;
  6869. },
  6870. };
  6871.  
  6872. /**
  6873. * Connects to game objects via the object creation event
  6874. *
  6875. * Подключается к объектам игры через событие создания объекта
  6876. */
  6877. function connectGame() {
  6878. for (let obj of ObjectsList) {
  6879. /**
  6880. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  6881. */
  6882. Object.defineProperty(Object.prototype, obj.prop, {
  6883. set: function (value) {
  6884. if (!selfGame) {
  6885. selfGame = this;
  6886. }
  6887. if (!Game[obj.name]) {
  6888. Game[obj.name] = value;
  6889. }
  6890. // console.log('set ' + obj.prop, this, value);
  6891. this[obj.prop + '_'] = value;
  6892. },
  6893. get: function () {
  6894. // console.log('get ' + obj.prop, this);
  6895. return this[obj.prop + '_'];
  6896. },
  6897. });
  6898. }
  6899. }
  6900.  
  6901. /**
  6902. * Game.BattlePresets
  6903. * @param {bool} a isReplay
  6904. * @param {bool} b autoToggleable
  6905. * @param {bool} c auto On Start
  6906. * @param {object} d config
  6907. * @param {bool} f showBothTeams
  6908. */
  6909. /**
  6910. * Returns the results of the battle to the callback function
  6911. * Возвращает в функцию callback результаты боя
  6912. * @param {*} battleData battle data данные боя
  6913. * @param {*} battleConfig combat configuration type options:
  6914. *
  6915. * тип конфигурации боя варианты:
  6916. *
  6917. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  6918. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  6919. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  6920. *
  6921. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  6922. *
  6923. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  6924. * @param {*} callback функция в которую вернуться результаты боя
  6925. */
  6926. this.BattleCalc = function (battleData, battleConfig, callback) {
  6927. // battleConfig = battleConfig || getBattleType(battleData.type)
  6928. if (!Game.BattlePresets) throw Error('Use connectGame');
  6929. battlePresets = new Game.BattlePresets(
  6930. battleData.progress,
  6931. !1,
  6932. !0,
  6933. Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](),
  6934. !1
  6935. );
  6936. let battleInstantPlay;
  6937. if (battleData.progress?.length > 1) {
  6938. battleInstantPlay = new Game.MultiBattleInstantReplay(battleData, battlePresets);
  6939. } else {
  6940. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  6941. }
  6942. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 9)].add((battleInstant) => {
  6943. const MBR_2 = getProtoFn(Game.MultiBattleResult, 2);
  6944. const battleResults = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  6945. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  6946. const battleLogs = [];
  6947. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  6948. let battleTime = 0;
  6949. let battleTimer = 0;
  6950. for (const battleResult of battleResults[MBR_2]) {
  6951. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult));
  6952. battleLogs.push(battleLog);
  6953. const maxTime = Math.max(...battleLog.map((e) => (e.time < timeLimit && e.time !== 168.8 ? e.time : 0)));
  6954. battleTimer += getTimer(maxTime);
  6955. battleTime += maxTime;
  6956. }
  6957. callback({
  6958. battleLogs,
  6959. battleTime,
  6960. battleTimer,
  6961. battleData,
  6962. progress: battleResults[getF(Game.MultiBattleResult, 'get_progress')](),
  6963. result: battleResults[getF(Game.MultiBattleResult, 'get_result')](),
  6964. });
  6965. });
  6966. battleInstantPlay.start();
  6967. };
  6968.  
  6969. /**
  6970. * Returns a function with the specified name from the class
  6971. *
  6972. * Возвращает из класса функцию с указанным именем
  6973. * @param {Object} classF Class // класс
  6974. * @param {String} nameF function name // имя функции
  6975. * @param {String} pos name and alias order // порядок имени и псевдонима
  6976. * @returns
  6977. */
  6978. function getF(classF, nameF, pos) {
  6979. pos = pos || false;
  6980. let prop = Object.entries(classF.prototype.__properties__);
  6981. if (!pos) {
  6982. return prop.filter((e) => e[1] == nameF).pop()[0];
  6983. } else {
  6984. return prop.filter((e) => e[0] == nameF).pop()[1];
  6985. }
  6986. }
  6987.  
  6988. /**
  6989. * Returns a function with the specified name from the class
  6990. *
  6991. * Возвращает из класса функцию с указанным именем
  6992. * @param {Object} classF Class // класс
  6993. * @param {String} nameF function name // имя функции
  6994. * @returns
  6995. */
  6996. function getFnP(classF, nameF) {
  6997. let prop = Object.entries(classF.__properties__);
  6998. return prop.filter((e) => e[1] == nameF).pop()[0];
  6999. }
  7000.  
  7001. /**
  7002. * Returns the function name with the specified ordinal from the class
  7003. *
  7004. * Возвращает имя функции с указаным порядковым номером из класса
  7005. * @param {Object} classF Class // класс
  7006. * @param {Number} nF Order number of function // порядковый номер функции
  7007. * @returns
  7008. */
  7009. function getFn(classF, nF) {
  7010. let prop = Object.keys(classF);
  7011. return prop[nF];
  7012. }
  7013.  
  7014. /**
  7015. * Returns the name of the function with the specified serial number from the prototype of the class
  7016. *
  7017. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  7018. * @param {Object} classF Class // класс
  7019. * @param {Number} nF Order number of function // порядковый номер функции
  7020. * @returns
  7021. */
  7022. function getProtoFn(classF, nF) {
  7023. let prop = Object.keys(classF.prototype);
  7024. return prop[nF];
  7025. }
  7026. /**
  7027. * Description of replaced functions
  7028. *
  7029. * Описание подменяемых функций
  7030. */
  7031. replaceFunction = {
  7032. company: function () {
  7033. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  7034. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  7035. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  7036. if (!isChecked('passBattle')) {
  7037. oldSkipMisson.call(this, a, b, c);
  7038. return;
  7039. }
  7040.  
  7041. try {
  7042. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  7043.  
  7044. var a = new Game.BattlePresets(
  7045. !1,
  7046. !1,
  7047. !0,
  7048. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  7049. !1
  7050. );
  7051. a = new Game.BattleInstantPlay(c, a);
  7052. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  7053. a.start();
  7054. } catch (error) {
  7055. console.error('company', error);
  7056. oldSkipMisson.call(this, a, b, c);
  7057. }
  7058. };
  7059.  
  7060. Game.PlayerMissionData.prototype.P$h = function (a) {
  7061. let GM_2 = getFn(Game.GameModel, 2);
  7062. let GM_P2 = getProtoFn(Game.GameModel, 2);
  7063. let CM_20 = getProtoFn(Game.CommandManager, 20);
  7064. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  7065. let MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  7066. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  7067. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  7068. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]));
  7069. };
  7070. },
  7071. /*
  7072. tower: function () {
  7073. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  7074. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  7075. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  7076. if (!isChecked('passBattle')) {
  7077. oldSkipTower.call(this, a);
  7078. return;
  7079. }
  7080. try {
  7081. var p = new Game.BattlePresets(
  7082. !1,
  7083. !1,
  7084. !0,
  7085. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  7086. !1
  7087. );
  7088. a = new Game.BattleInstantPlay(a, p);
  7089. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  7090. a.start();
  7091. } catch (error) {
  7092. console.error('tower', error);
  7093. oldSkipMisson.call(this, a, b, c);
  7094. }
  7095. };
  7096.  
  7097. Game.PlayerTowerData.prototype.P$h = function (a) {
  7098. const GM_2 = getFnP(Game.GameModel, 'get_instance');
  7099. const GM_P2 = getProtoFn(Game.GameModel, 2);
  7100. const CM_29 = getProtoFn(Game.CommandManager, 29);
  7101. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  7102. const MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  7103. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  7104. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  7105. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  7106. };
  7107. },
  7108. */
  7109. // skipSelectHero: function() {
  7110. // if (!HOST) throw Error('Use connectGame');
  7111. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  7112. // },
  7113. passBattle: function () {
  7114. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  7115. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  7116. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  7117. if (!isChecked('passBattle')) {
  7118. oldPassBattle.call(this, a);
  7119. return;
  7120. }
  7121. try {
  7122. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  7123. this[getProtoFn(Game.BattlePausePopup, 3)]();
  7124. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  7125. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](
  7126. Game.Translate.translate('UI_POPUP_BATTLE_PAUSE')
  7127. );
  7128.  
  7129. this.clip[getProtoFn(Game.BattlePausePopupClip, 2)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7130. Game.Translate.translate('UI_POPUP_BATTLE_RETREAT'),
  7131. ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 17)]))
  7132. );
  7133. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7134. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  7135. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]()
  7136. ? ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7137. : ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7138. );
  7139.  
  7140. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][
  7141. getProtoFn(Game.ClipLabelBase, 24)
  7142. ]();
  7143. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](
  7144. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]()
  7145. );
  7146. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](
  7147. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]()
  7148. );
  7149. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](
  7150. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]()
  7151. );
  7152. } catch (error) {
  7153. console.error('passBattle', error);
  7154. oldPassBattle.call(this, a);
  7155. }
  7156. };
  7157.  
  7158. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, 'get_retreatButtonLabel');
  7159. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  7160. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  7161. if (isChecked('passBattle')) {
  7162. return I18N('BTN_PASS');
  7163. } else {
  7164. return oldFunc.call(this);
  7165. }
  7166. };
  7167. },
  7168. endlessCards: function () {
  7169. let PDD_21 = getProtoFn(Game.PlayerDungeonData, 21);
  7170. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_21];
  7171. Game.PlayerDungeonData.prototype[PDD_21] = function () {
  7172. if (countPredictionCard <= 0) {
  7173. return true;
  7174. } else {
  7175. return oldEndlessCards.call(this);
  7176. }
  7177. };
  7178. },
  7179. speedBattle: function () {
  7180. const get_timeScale = getF(Game.BattleController, 'get_timeScale');
  7181. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  7182. Game.BattleController.prototype[get_timeScale] = function () {
  7183. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  7184. if (!speedBattle) {
  7185. return oldSpeedBattle.call(this);
  7186. }
  7187. try {
  7188. const BC_12 = getProtoFn(Game.BattleController, 12);
  7189. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  7190. const BP_get_value = getF(Game.BooleanProperty, 'get_value');
  7191. if (this[BC_12][BSM_12][BP_get_value]()) {
  7192. return 0;
  7193. }
  7194. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  7195. const BC_49 = getProtoFn(Game.BattleController, 49);
  7196. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  7197. const BC_14 = getProtoFn(Game.BattleController, 14);
  7198. const BC_3 = getFn(Game.BattleController, 3);
  7199. if (this[BC_12][BSM_2][BP_get_value]()) {
  7200. var a = speedBattle * this[BC_49]();
  7201. } else {
  7202. a = this[BC_12][BSM_1][BP_get_value]();
  7203. const maxSpeed = Math.max(...this[BC_14]);
  7204. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  7205. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_49]();
  7206. }
  7207. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  7208. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  7209. const DS_23 = getFn(Game.DataStorage, 23);
  7210. const get_battleSpeedMultiplier = getF(Game.RuleStorage, 'get_battleSpeedMultiplier', true);
  7211. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  7212. const R_1 = getFn(selfGame.Reflect, 1);
  7213. const BC_1 = getFn(Game.BattleController, 1);
  7214. const get_config = getF(Game.BattlePresets, 'get_config');
  7215. null != b &&
  7216. (a = selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7217. ? a * selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7218. : a * selfGame.Reflect[R_1](b, 'default'));
  7219. return a;
  7220. } catch (error) {
  7221. console.error('passBatspeedBattletle', error);
  7222. return oldSpeedBattle.call(this);
  7223. }
  7224. };
  7225. },
  7226.  
  7227. /**
  7228. * Acceleration button without Valkyries favor
  7229. *
  7230. * Кнопка ускорения без Покровительства Валькирий
  7231. */
  7232. battleFastKey: function () {
  7233. const BGM_44 = getProtoFn(Game.BattleGuiMediator, 44);
  7234. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_44];
  7235. Game.BattleGuiMediator.prototype[BGM_44] = function () {
  7236. let flag = true;
  7237. //console.log(flag)
  7238. if (!flag) {
  7239. return oldBattleFastKey.call(this);
  7240. }
  7241. try {
  7242. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  7243. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  7244. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  7245. this[BGM_9][BPW_0](true);
  7246. this[BGM_10][BPW_0](true);
  7247. } catch (error) {
  7248. console.error(error);
  7249. return oldBattleFastKey.call(this);
  7250. }
  7251. };
  7252. },
  7253. fastSeason: function () {
  7254. const GameNavigator = selfGame['game.screen.navigator.GameNavigator'];
  7255. const oldFuncName = getProtoFn(GameNavigator, 18);
  7256. const newFuncName = getProtoFn(GameNavigator, 16);
  7257. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  7258. const newFastSeason = GameNavigator.prototype[newFuncName];
  7259. GameNavigator.prototype[oldFuncName] = function (a, b) {
  7260. if (isChecked('fastSeason')) {
  7261. return newFastSeason.apply(this, [a]);
  7262. } else {
  7263. return oldFastSeason.apply(this, [a, b]);
  7264. }
  7265. };
  7266. },
  7267. ShowChestReward: function () {
  7268. const TitanArtifactChest = selfGame['game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator'];
  7269. const getOpenAmountTitan = getF(TitanArtifactChest, 'get_openAmount');
  7270. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  7271. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  7272. if (correctShowOpenArtifact) {
  7273. correctShowOpenArtifact--;
  7274. return 100;
  7275. }
  7276. return oldGetOpenAmountTitan.call(this);
  7277. };
  7278.  
  7279. const ArtifactChest = selfGame['game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator'];
  7280. const getOpenAmount = getF(ArtifactChest, 'get_openAmount');
  7281. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  7282. ArtifactChest.prototype[getOpenAmount] = function () {
  7283. if (correctShowOpenArtifact) {
  7284. correctShowOpenArtifact--;
  7285. return 100;
  7286. }
  7287. return oldGetOpenAmount.call(this);
  7288. };
  7289. },
  7290. fixCompany: function () {
  7291. const GameBattleView = selfGame['game.mediator.gui.popup.battle.GameBattleView'];
  7292. const BattleThread = selfGame['game.battle.controller.thread.BattleThread'];
  7293. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  7294. const getThread = getF(GameBattleView, 'get_thread');
  7295. const oldFunc = GameBattleView.prototype[getThread];
  7296. GameBattleView.prototype[getThread] = function () {
  7297. return (
  7298. oldFunc.call(this) || {
  7299. [getOnViewDisposed]: async () => {},
  7300. }
  7301. );
  7302. };
  7303. },
  7304. BuyTitanArtifact: function () {
  7305. const BIP_4 = getProtoFn(selfGame['game.view.popup.shop.buy.BuyItemPopup'], 4);
  7306. const BuyItemPopup = selfGame['game.view.popup.shop.buy.BuyItemPopup'];
  7307. const oldFunc = BuyItemPopup.prototype[BIP_4];
  7308. BuyItemPopup.prototype[BIP_4] = function () {
  7309. if (isChecked('countControl')) {
  7310. const BuyTitanArtifactItemPopup = selfGame['game.view.popup.shop.buy.BuyTitanArtifactItemPopup'];
  7311. const BTAP_0 = getProtoFn(BuyTitanArtifactItemPopup, 0);
  7312. if (this[BTAP_0]) {
  7313. const BuyTitanArtifactPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyTitanArtifactItemPopupMediator'];
  7314. const BTAM_1 = getProtoFn(BuyTitanArtifactPopupMediator, 1);
  7315. const BuyItemPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyItemPopupMediator'];
  7316. const BIPM_5 = getProtoFn(BuyItemPopupMediator, 5);
  7317. const BIPM_7 = getProtoFn(BuyItemPopupMediator, 7);
  7318. const BIPM_9 = getProtoFn(BuyItemPopupMediator, 9);
  7319.  
  7320. let need = Math.min(this[BTAP_0][BTAM_1](), this[BTAP_0][BIPM_7]);
  7321. need = need ? need : 60;
  7322. this[BTAP_0][BIPM_9] = need;
  7323. this[BTAP_0][BIPM_5] = 10;
  7324. }
  7325. }
  7326. oldFunc.call(this);
  7327. };
  7328. },
  7329. ClanQuestsFastFarm: function () {
  7330. const VipRuleValueObject = selfGame['game.data.storage.rule.VipRuleValueObject'];
  7331. const getClanQuestsFastFarm = getF(VipRuleValueObject, 'get_clanQuestsFastFarm', 1);
  7332. VipRuleValueObject.prototype[getClanQuestsFastFarm] = function () {
  7333. return 0;
  7334. };
  7335. },
  7336. adventureCamera: function () {
  7337. const AMC_40 = getProtoFn(Game.AdventureMapCamera, 40);
  7338. const AMC_5 = getProtoFn(Game.AdventureMapCamera, 5);
  7339. const oldFunc = Game.AdventureMapCamera.prototype[AMC_40];
  7340. Game.AdventureMapCamera.prototype[AMC_40] = function (a) {
  7341. this[AMC_5] = 0.4;
  7342. oldFunc.bind(this)(a);
  7343. };
  7344. },
  7345. unlockMission: function () {
  7346. const WorldMapStoryDrommerHelper = selfGame['game.mediator.gui.worldmap.WorldMapStoryDrommerHelper'];
  7347. const WMSDH_4 = getFn(WorldMapStoryDrommerHelper, 4);
  7348. const WMSDH_7 = getFn(WorldMapStoryDrommerHelper, 7);
  7349. WorldMapStoryDrommerHelper[WMSDH_4] = function () {
  7350. return true;
  7351. };
  7352. WorldMapStoryDrommerHelper[WMSDH_7] = function () {
  7353. return true;
  7354. };
  7355. },
  7356. };
  7357.  
  7358. /**
  7359. * Starts replacing recorded functions
  7360. *
  7361. * Запускает замену записанных функций
  7362. */
  7363. this.activateHacks = function () {
  7364. if (!selfGame) throw Error('Use connectGame');
  7365. for (let func in replaceFunction) {
  7366. try {
  7367. replaceFunction[func]();
  7368. } catch (error) {
  7369. console.error(error);
  7370. }
  7371. }
  7372. };
  7373.  
  7374. /**
  7375. * Returns the game object
  7376. *
  7377. * Возвращает объект игры
  7378. */
  7379. this.getSelfGame = function () {
  7380. return selfGame;
  7381. };
  7382.  
  7383. /**
  7384. * Updates game data
  7385. *
  7386. * Обновляет данные игры
  7387. */
  7388. this.refreshGame = function () {
  7389. new Game.NextDayUpdatedManager()[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  7390. try {
  7391. cheats.refreshInventory();
  7392. } catch (e) {}
  7393. };
  7394.  
  7395. /**
  7396. * Update inventory
  7397. *
  7398. * Обновляет инвентарь
  7399. */
  7400. this.refreshInventory = async function () {
  7401. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7402. const GM_0 = getProtoFn(Game.GameModel, 0);
  7403. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7404. const Player = Game.GameModel[GM_INST]()[GM_0];
  7405. Player[P_24] = new selfGame['game.model.user.inventory.PlayerInventory']();
  7406. Player[P_24].init(await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'body' }] }).then((e) => e.results[0].result.response));
  7407. };
  7408. this.updateInventory = function (reward) {
  7409. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7410. const GM_0 = getProtoFn(Game.GameModel, 0);
  7411. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7412. const Player = Game.GameModel[GM_INST]()[GM_0];
  7413. Player[P_24].init(reward);
  7414. };
  7415.  
  7416. this.updateMap = function (data) {
  7417. const PCDD_21 = getProtoFn(selfGame['game.mechanics.clanDomination.model.PlayerClanDominationData'], 21);
  7418. const P_60 = getProtoFn(selfGame['game.model.user.Player'], 60);
  7419. const GM_0 = getProtoFn(Game.GameModel, 0);
  7420. const getInstance = getFnP(selfGame['Game'], 'get_instance');
  7421. const PlayerClanDominationData = Game.GameModel[getInstance]()[GM_0];
  7422. PlayerClanDominationData[P_60][PCDD_21].update(data);
  7423. };
  7424.  
  7425. /**
  7426. * Change the play screen on windowName
  7427. *
  7428. * Сменить экран игры на windowName
  7429. *
  7430. * Possible options:
  7431. *
  7432. * Возможные варианты:
  7433. *
  7434. * MISSION, ARENA, GRAND, CHEST, SKILLS, SOCIAL_GIFT, CLAN, ENCHANT, TOWER, RATING, CHALLENGE, BOSS, CHAT, CLAN_DUNGEON, CLAN_CHEST, TITAN_GIFT, CLAN_RAID, ASGARD, HERO_ASCENSION, ROLE_ASCENSION, ASCENSION_CHEST, TITAN_MISSION, TITAN_ARENA, TITAN_ARTIFACT, TITAN_ARTIFACT_CHEST, TITAN_VALLEY, TITAN_SPIRITS, TITAN_ARTIFACT_MERCHANT, TITAN_ARENA_HALL_OF_FAME, CLAN_PVP, CLAN_PVP_MERCHANT, CLAN_GLOBAL_PVP, CLAN_GLOBAL_PVP_TITAN, ARTIFACT, ZEPPELIN, ARTIFACT_CHEST, ARTIFACT_MERCHANT, EXPEDITIONS, SUBSCRIPTION, NY2018_GIFTS, NY2018_TREE, NY2018_WELCOME, ADVENTURE, ADVENTURESOLO, SANCTUARY, PET_MERCHANT, PET_LIST, PET_SUMMON, BOSS_RATING_EVENT, BRAWL
  7435. */
  7436. this.goNavigtor = function (windowName) {
  7437. let mechanicStorage = selfGame['game.data.storage.mechanic.MechanicStorage'];
  7438. let window = mechanicStorage[windowName];
  7439. let event = new selfGame['game.mediator.gui.popup.PopupStashEventParams']();
  7440. let Game = selfGame['Game'];
  7441. let navigator = getF(Game, 'get_navigator');
  7442. let navigate = getProtoFn(selfGame['game.screen.navigator.GameNavigator'], 20);
  7443. let instance = getFnP(Game, 'get_instance');
  7444. Game[instance]()[navigator]()[navigate](window, event);
  7445. };
  7446.  
  7447. /**
  7448. * Move to the sanctuary cheats.goSanctuary()
  7449. *
  7450. * Переместиться в святилище cheats.goSanctuary()
  7451. */
  7452. this.goSanctuary = () => {
  7453. this.goNavigtor('SANCTUARY');
  7454. };
  7455.  
  7456. /** Перейти в Долину титанов */
  7457. this.goTitanValley = () => {
  7458. this.goNavigtor('TITAN_VALLEY');
  7459. };
  7460.  
  7461. /**
  7462. * Go to Guild War
  7463. *
  7464. * Перейти к Войне Гильдий
  7465. */
  7466. this.goClanWar = function () {
  7467. let instance = getFnP(Game.GameModel, 'get_instance');
  7468. let player = Game.GameModel[instance]().A;
  7469. let clanWarSelect = selfGame['game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator'];
  7470. new clanWarSelect(player).open();
  7471. };
  7472.  
  7473. /** Перейти к Острову гильдии */
  7474. this.goClanIsland = function () {
  7475. let instance = getFnP(Game.GameModel, 'get_instance');
  7476. let player = Game.GameModel[instance]().A;
  7477. let clanIslandSelect = selfGame['game.view.gui.ClanIslandPopupMediator'];
  7478. new clanIslandSelect(player).open();
  7479. };
  7480.  
  7481. /**
  7482. * Go to BrawlShop
  7483. *
  7484. * Переместиться в BrawlShop
  7485. */
  7486. this.goBrawlShop = () => {
  7487. const instance = getFnP(Game.GameModel, 'get_instance');
  7488. const P_36 = getProtoFn(selfGame['game.model.user.Player'], 36);
  7489. const PSD_0 = getProtoFn(selfGame['game.model.user.shop.PlayerShopData'], 0);
  7490. const IM_0 = getProtoFn(selfGame['haxe.ds.IntMap'], 0);
  7491. const PSDE_4 = getProtoFn(selfGame['game.model.user.shop.PlayerShopDataEntry'], 4);
  7492.  
  7493. const player = Game.GameModel[instance]().A;
  7494. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  7495. const shopPopup = new selfGame['game.mechanics.brawl.mediator.BrawlShopPopupMediator'](player, shop);
  7496. shopPopup.open(new selfGame['game.mediator.gui.popup.PopupStashEventParams']());
  7497. };
  7498.  
  7499. /**
  7500. * Returns all stores from game data
  7501. *
  7502. * Возвращает все магазины из данных игры
  7503. */
  7504. this.getShops = () => {
  7505. const instance = getFnP(Game.GameModel, 'get_instance');
  7506. const P_36 = getProtoFn(selfGame['game.model.user.Player'], 36);
  7507. const PSD_0 = getProtoFn(selfGame['game.model.user.shop.PlayerShopData'], 0);
  7508. const IM_0 = getProtoFn(selfGame['haxe.ds.IntMap'], 0);
  7509.  
  7510. const player = Game.GameModel[instance]().A;
  7511. return player[P_36][PSD_0][IM_0];
  7512. };
  7513.  
  7514. /**
  7515. * Returns the store from the game data by ID
  7516. *
  7517. * Возвращает магазин из данных игры по идетификатору
  7518. */
  7519. this.getShop = (id) => {
  7520. const PSDE_4 = getProtoFn(selfGame['game.model.user.shop.PlayerShopDataEntry'], 4);
  7521. const shops = this.getShops();
  7522. const shop = shops[id]?.[PSDE_4];
  7523. return shop;
  7524. };
  7525.  
  7526. /**
  7527. * Change island map
  7528. *
  7529. * Сменить карту острова
  7530. */
  7531. this.changeIslandMap = (mapId = 2) => {
  7532. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  7533. const GM_0 = getProtoFn(Game.GameModel, 0);
  7534. const P_59 = getProtoFn(selfGame['game.model.user.Player'], 60);
  7535. const PSAD_31 = getProtoFn(selfGame['game.mechanics.season_adventure.model.PlayerSeasonAdventureData'], 31);
  7536. const Player = Game.GameModel[GameInst]()[GM_0];
  7537. Player[P_59][PSAD_31]({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  7538.  
  7539. const GN_15 = getProtoFn(selfGame['game.screen.navigator.GameNavigator'], 17);
  7540. const navigator = getF(selfGame['Game'], 'get_navigator');
  7541. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame['game.mediator.gui.popup.PopupStashEventParams']());
  7542. };
  7543.  
  7544. /**
  7545. * Game library availability tracker
  7546. *
  7547. * Отслеживание доступности игровой библиотеки
  7548. */
  7549. function checkLibLoad() {
  7550. timeout = setTimeout(() => {
  7551. if (Game.GameModel) {
  7552. changeLib();
  7553. } else {
  7554. checkLibLoad();
  7555. }
  7556. }, 100);
  7557. }
  7558.  
  7559. /**
  7560. * Game library data spoofing
  7561. *
  7562. * Подмена данных игровой библиотеки
  7563. */
  7564. function changeLib() {
  7565. console.log('lib connect');
  7566. const originalStartFunc = Game.GameModel.prototype.start;
  7567. Game.GameModel.prototype.start = function (a, b, c) {
  7568. self.libGame = b.raw;
  7569. self.doneLibLoad(self.libGame);
  7570. try {
  7571. const levels = b.raw.seasonAdventure.level;
  7572. for (const id in levels) {
  7573. const level = levels[id];
  7574. level.clientData.graphics.fogged = level.clientData.graphics.visible;
  7575. }
  7576. const adv = b.raw.seasonAdventure.list[1];
  7577. adv.clientData.asset = 'dialog_season_adventure_tiles';
  7578. } catch (e) {
  7579. console.warn(e);
  7580. }
  7581. originalStartFunc.call(this, a, b, c);
  7582. };
  7583. }
  7584.  
  7585. this.LibLoad = function () {
  7586. return new Promise((e) => {
  7587. this.doneLibLoad = e;
  7588. });
  7589. };
  7590.  
  7591. /**
  7592. * Returns the value of a language constant
  7593. *
  7594. * Возвращает значение языковой константы
  7595. * @param {*} langConst language constant // языковая константа
  7596. * @returns
  7597. */
  7598. this.translate = function (langConst) {
  7599. return Game.Translate.translate(langConst);
  7600. };
  7601.  
  7602. connectGame();
  7603. checkLibLoad();
  7604. }
  7605.  
  7606. /**
  7607. * Auto collection of gifts
  7608. *
  7609. * Автосбор подарков
  7610. */
  7611. function getAutoGifts() {
  7612. // c3ltYm9scyB0aGF0IG1lYW4gbm90aGluZw==
  7613. let valName = 'giftSendIds_' + userInfo.id;
  7614.  
  7615. if (!localStorage['clearGift' + userInfo.id]) {
  7616. localStorage[valName] = '';
  7617. localStorage['clearGift' + userInfo.id] = '+';
  7618. }
  7619.  
  7620. if (!localStorage[valName]) {
  7621. localStorage[valName] = '';
  7622. }
  7623.  
  7624. const giftsAPI = new ZingerYWebsiteAPI('getGifts.php', arguments);
  7625. /**
  7626. * Submit a request to receive gift codes
  7627. *
  7628. * Отправка запроса для получения кодов подарков
  7629. */
  7630. giftsAPI.request().then((data) => {
  7631. let freebieCheckCalls = {
  7632. calls: [],
  7633. };
  7634. data.forEach((giftId, n) => {
  7635. if (localStorage[valName].includes(giftId)) return;
  7636. freebieCheckCalls.calls.push({
  7637. name: 'registration',
  7638. args: {
  7639. user: { referrer: {} },
  7640. giftId,
  7641. },
  7642. context: {
  7643. actionTs: Math.floor(performance.now()),
  7644. cookie: window?.NXAppInfo?.session_id || null,
  7645. },
  7646. ident: giftId,
  7647. });
  7648. });
  7649.  
  7650. if (!freebieCheckCalls.calls.length) {
  7651. return;
  7652. }
  7653.  
  7654. send(JSON.stringify(freebieCheckCalls), (e) => {
  7655. let countGetGifts = 0;
  7656. const gifts = [];
  7657. for (check of e.results) {
  7658. gifts.push(check.ident);
  7659. if (check.result.response != null) {
  7660. countGetGifts++;
  7661. }
  7662. }
  7663. const saveGifts = localStorage[valName].split(';');
  7664. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  7665. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  7666. });
  7667. });
  7668. }
  7669.  
  7670. /**
  7671. * To fill the kills in the Forge of Souls
  7672. *
  7673. * Набить килов в горниле душ
  7674. */
  7675. async function bossRatingEvent() {
  7676. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  7677. if (!topGet || !topGet.results[0].result.response[0]) {
  7678. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7679. return;
  7680. }
  7681. const replayId = topGet.results[0].result.response[0].userData.replayId;
  7682. const result = await Send(JSON.stringify({
  7683. calls: [
  7684. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  7685. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  7686. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  7687. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  7688. ]
  7689. }));
  7690. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  7691. if (!bossEventInfo) {
  7692. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7693. return;
  7694. }
  7695. const usedHeroes = bossEventInfo.progress.usedHeroes;
  7696. const party = Object.values(result.results[0].result.response.replay.attackers);
  7697. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  7698. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  7699. const calls = [];
  7700. /**
  7701. * First pack
  7702. *
  7703. * Первая пачка
  7704. */
  7705. const args = {
  7706. heroes: [],
  7707. favor: {}
  7708. }
  7709. for (let hero of party) {
  7710. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  7711. args.pet = hero.id;
  7712. continue;
  7713. }
  7714. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  7715. continue;
  7716. }
  7717. args.heroes.push(hero.id);
  7718. if (hero.favorPetId) {
  7719. args.favor[hero.id] = hero.favorPetId;
  7720. }
  7721. }
  7722. if (args.heroes.length) {
  7723. calls.push({
  7724. name: "bossRatingEvent_startBattle",
  7725. args,
  7726. ident: "body_0"
  7727. });
  7728. }
  7729. /**
  7730. * Other packs
  7731. *
  7732. * Другие пачки
  7733. */
  7734. let heroes = [];
  7735. let count = 1;
  7736. while (heroId = availableHeroes.pop()) {
  7737. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  7738. continue;
  7739. }
  7740. heroes.push(heroId);
  7741. if (heroes.length == 5) {
  7742. calls.push({
  7743. name: "bossRatingEvent_startBattle",
  7744. args: {
  7745. heroes: [...heroes],
  7746. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  7747. },
  7748. ident: "body_" + count
  7749. });
  7750. heroes = [];
  7751. count++;
  7752. }
  7753. }
  7754.  
  7755. if (!calls.length) {
  7756. setProgress(`${I18N('NO_HEROES')}`, true);
  7757. return;
  7758. }
  7759.  
  7760. const resultBattles = await Send(JSON.stringify({ calls }));
  7761. console.log(resultBattles);
  7762. rewardBossRatingEvent();
  7763. }
  7764.  
  7765. /**
  7766. * Collecting Rewards from the Forge of Souls
  7767. *
  7768. * Сбор награды из Горнила Душ
  7769. */
  7770. function rewardBossRatingEvent() {
  7771. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7772. send(rewardBossRatingCall, function (data) {
  7773. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  7774. if (!bossEventInfo) {
  7775. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7776. return;
  7777. }
  7778.  
  7779. let farmedChests = bossEventInfo.progress.farmedChests;
  7780. let score = bossEventInfo.progress.score;
  7781. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  7782. let revard = bossEventInfo.reward;
  7783.  
  7784. let getRewardCall = {
  7785. calls: []
  7786. }
  7787.  
  7788. let count = 0;
  7789. for (let i = 1; i < 10; i++) {
  7790. if (farmedChests.includes(i)) {
  7791. continue;
  7792. }
  7793. if (score < revard[i].score) {
  7794. break;
  7795. }
  7796. getRewardCall.calls.push({
  7797. name: "bossRatingEvent_getReward",
  7798. args: {
  7799. rewardId: i
  7800. },
  7801. ident: "body_" + i
  7802. });
  7803. count++;
  7804. }
  7805. if (!count) {
  7806. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7807. return;
  7808. }
  7809.  
  7810. send(JSON.stringify(getRewardCall), e => {
  7811. console.log(e);
  7812. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7813. });
  7814. });
  7815. }
  7816.  
  7817. /**
  7818. * Collect Easter eggs and event rewards
  7819. *
  7820. * Собрать пасхалки и награды событий
  7821. */
  7822. function offerFarmAllReward() {
  7823. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7824. return Send(offerGetAllCall).then((data) => {
  7825. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  7826. if (!offerGetAll.length) {
  7827. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7828. return;
  7829. }
  7830.  
  7831. const calls = [];
  7832. for (let reward of offerGetAll) {
  7833. calls.push({
  7834. name: "offerFarmReward",
  7835. args: {
  7836. offerId: reward.id
  7837. },
  7838. ident: "offerFarmReward_" + reward.id
  7839. });
  7840. }
  7841.  
  7842. return Send(JSON.stringify({ calls })).then(e => {
  7843. console.log(e);
  7844. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7845. });
  7846. });
  7847. }
  7848.  
  7849. /**
  7850. * Assemble Outland
  7851. *
  7852. * Собрать запределье
  7853. */
  7854. function getOutland() {
  7855. return new Promise(function (resolve, reject) {
  7856. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  7857. let bosses = e.results[0].result.response;
  7858.  
  7859. let bossRaidOpenChestCall = {
  7860. calls: []
  7861. };
  7862.  
  7863. for (let boss of bosses) {
  7864. if (boss.mayRaid) {
  7865. bossRaidOpenChestCall.calls.push({
  7866. name: "bossRaid",
  7867. args: {
  7868. bossId: boss.id
  7869. },
  7870. ident: "bossRaid_" + boss.id
  7871. });
  7872. bossRaidOpenChestCall.calls.push({
  7873. name: "bossOpenChest",
  7874. args: {
  7875. bossId: boss.id,
  7876. amount: 1,
  7877. starmoney: 0
  7878. },
  7879. ident: "bossOpenChest_" + boss.id
  7880. });
  7881. } else if (boss.chestId == 1) {
  7882. bossRaidOpenChestCall.calls.push({
  7883. name: "bossOpenChest",
  7884. args: {
  7885. bossId: boss.id,
  7886. amount: 1,
  7887. starmoney: 0
  7888. },
  7889. ident: "bossOpenChest_" + boss.id
  7890. });
  7891. }
  7892. }
  7893.  
  7894. if (!bossRaidOpenChestCall.calls.length) {
  7895. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  7896. resolve();
  7897. return;
  7898. }
  7899.  
  7900. send(JSON.stringify(bossRaidOpenChestCall), e => {
  7901. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  7902. resolve();
  7903. });
  7904. });
  7905. });
  7906. }
  7907.  
  7908. /**
  7909. * Collect all rewards
  7910. *
  7911. * Собрать все награды
  7912. */
  7913. function questAllFarm() {
  7914. return new Promise(function (resolve, reject) {
  7915. let questGetAllCall = {
  7916. calls: [{
  7917. name: "questGetAll",
  7918. args: {},
  7919. ident: "body"
  7920. }]
  7921. }
  7922. send(JSON.stringify(questGetAllCall), function (data) {
  7923. let questGetAll = data.results[0].result.response;
  7924. const questAllFarmCall = {
  7925. calls: []
  7926. }
  7927. let number = 0;
  7928. for (let quest of questGetAll) {
  7929. if (quest.id < 1e6 && quest.state == 2) {
  7930. questAllFarmCall.calls.push({
  7931. name: "questFarm",
  7932. args: {
  7933. questId: quest.id
  7934. },
  7935. ident: `group_${number}_body`
  7936. });
  7937. number++;
  7938. }
  7939. }
  7940.  
  7941. if (!questAllFarmCall.calls.length) {
  7942. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7943. resolve();
  7944. return;
  7945. }
  7946.  
  7947. send(JSON.stringify(questAllFarmCall), function (res) {
  7948. console.log(res);
  7949. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7950. resolve();
  7951. });
  7952. });
  7953. })
  7954. }
  7955.  
  7956. /**
  7957. * Mission auto repeat
  7958. *
  7959. * Автоповтор миссии
  7960. * isStopSendMission = false;
  7961. * isSendsMission = true;
  7962. **/
  7963. this.sendsMission = async function (param) {
  7964. if (isStopSendMission) {
  7965. isSendsMission = false;
  7966. console.log(I18N('STOPPED'));
  7967. setProgress('');
  7968. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  7969. msg: 'Ok',
  7970. result: true
  7971. }, ])
  7972. return;
  7973. }
  7974. lastMissionBattleStart = Date.now();
  7975. let missionStartCall = {
  7976. "calls": [{
  7977. "name": "missionStart",
  7978. "args": lastMissionStart,
  7979. "ident": "body"
  7980. }]
  7981. }
  7982. /**
  7983. * Mission Request
  7984. *
  7985. * Запрос на выполнение мисии
  7986. */
  7987. SendRequest(JSON.stringify(missionStartCall), async e => {
  7988. if (e['error']) {
  7989. isSendsMission = false;
  7990. console.log(e['error']);
  7991. setProgress('');
  7992. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  7993. await popup.confirm(msg, [
  7994. {msg: 'Ok', result: true},
  7995. ])
  7996. return;
  7997. }
  7998. /**
  7999. * Mission data calculation
  8000. *
  8001. * Расчет данных мисии
  8002. */
  8003. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  8004. /** missionTimer */
  8005. let timer = getTimer(r.battleTime) + 5;
  8006. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  8007. if (period < timer) {
  8008. timer = timer - period;
  8009. await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`);
  8010. }
  8011.  
  8012. let missionEndCall = {
  8013. "calls": [{
  8014. "name": "missionEnd",
  8015. "args": {
  8016. "id": param.id,
  8017. "result": r.result,
  8018. "progress": r.progress
  8019. },
  8020. "ident": "body"
  8021. }]
  8022. }
  8023. /**
  8024. * Mission Completion Request
  8025. *
  8026. * Запрос на завершение миссии
  8027. */
  8028. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  8029. if (e['error']) {
  8030. isSendsMission = false;
  8031. console.log(e['error']);
  8032. setProgress('');
  8033. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  8034. await popup.confirm(msg, [
  8035. {msg: 'Ok', result: true},
  8036. ])
  8037. return;
  8038. }
  8039. r = e.results[0].result.response;
  8040. if (r['error']) {
  8041. isSendsMission = false;
  8042. console.log(r['error']);
  8043. setProgress('');
  8044. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  8045. {msg: 'Ok', result: true},
  8046. ])
  8047. return;
  8048. }
  8049.  
  8050. param.count++;
  8051. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  8052. isStopSendMission = true;
  8053. });
  8054. setTimeout(sendsMission, 1, param);
  8055. });
  8056. })
  8057. });
  8058. }
  8059.  
  8060. /**
  8061. * Opening of russian dolls
  8062. *
  8063. * Открытие матрешек
  8064. */
  8065. async function openRussianDolls(libId, amount) {
  8066. let sum = 0;
  8067. const sumResult = {};
  8068. let count = 0;
  8069.  
  8070. while (amount) {
  8071. sum += amount;
  8072. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  8073. const calls = [
  8074. {
  8075. name: 'consumableUseLootBox',
  8076. args: { libId, amount },
  8077. ident: 'body',
  8078. },
  8079. ];
  8080. const response = await Send(JSON.stringify({ calls })).then((e) => e.results[0].result.response);
  8081. let [countLootBox, result] = Object.entries(response).pop();
  8082. count += +countLootBox;
  8083. let newCount = 0;
  8084.  
  8085. if (result?.consumable && result.consumable[libId]) {
  8086. newCount = result.consumable[libId];
  8087. delete result.consumable[libId];
  8088. }
  8089.  
  8090. mergeItemsObj(sumResult, result);
  8091. amount = newCount;
  8092. }
  8093.  
  8094. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  8095. return [count, sumResult];
  8096. }
  8097.  
  8098. function mergeItemsObj(obj1, obj2) {
  8099. for (const key in obj2) {
  8100. if (obj1[key]) {
  8101. if (typeof obj1[key] == 'object') {
  8102. for (const innerKey in obj2[key]) {
  8103. obj1[key][innerKey] = (obj1[key][innerKey] || 0) + obj2[key][innerKey];
  8104. }
  8105. } else {
  8106. obj1[key] += obj2[key] || 0;
  8107. }
  8108. } else {
  8109. obj1[key] = obj2[key];
  8110. }
  8111. }
  8112.  
  8113. return obj1;
  8114. }
  8115.  
  8116. /**
  8117. * Collect all mail, except letters with energy and charges of the portal
  8118. *
  8119. * Собрать всю почту, кроме писем с энергией и зарядами портала
  8120. */
  8121. function mailGetAll() {
  8122. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  8123.  
  8124. return Send(getMailInfo).then(dataMail => {
  8125. const letters = dataMail.results[0].result.response.letters;
  8126. const letterIds = lettersFilter(letters);
  8127. if (!letterIds.length) {
  8128. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8129. return;
  8130. }
  8131.  
  8132. const calls = [
  8133. { name: "mailFarm", args: { letterIds }, ident: "body" }
  8134. ];
  8135.  
  8136. return Send(JSON.stringify({ calls })).then(res => {
  8137. const lettersIds = res.results[0].result.response;
  8138. if (lettersIds) {
  8139. const countLetters = Object.keys(lettersIds).length;
  8140. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  8141. }
  8142. });
  8143. });
  8144. }
  8145.  
  8146. /**
  8147. * Filters received emails
  8148. *
  8149. * Фильтрует получаемые письма
  8150. */
  8151. function lettersFilter(letters) {
  8152. const lettersIds = [];
  8153. for (let l in letters) {
  8154. letter = letters[l];
  8155. const reward = letter?.reward;
  8156. if (!reward || !Object.keys(reward).length) {
  8157. continue;
  8158. }
  8159. /**
  8160. * Mail Collection Exceptions
  8161. *
  8162. * Исключения на сбор писем
  8163. */
  8164. const isFarmLetter = !(
  8165. /** Portals // сферы портала */
  8166. (reward?.refillable ? reward.refillable[45] : false) ||
  8167. /** Energy // энергия */
  8168. (reward?.stamina ? reward.stamina : false) ||
  8169. /** accelerating energy gain // ускорение набора энергии */
  8170. (reward?.buff ? true : false) ||
  8171. /** VIP Points // вип очки */
  8172. (reward?.vipPoints ? reward.vipPoints : false) ||
  8173. /** souls of heroes // душы героев */
  8174. (reward?.fragmentHero ? true : false) ||
  8175. /** heroes // герои */
  8176. (reward?.bundleHeroReward ? true : false)
  8177. );
  8178. if (isFarmLetter) {
  8179. lettersIds.push(~~letter.id);
  8180. continue;
  8181. }
  8182. /**
  8183. * Если до окончания годности письма менее 24 часов,
  8184. * то оно собирается не смотря на исключения
  8185. */
  8186. const availableUntil = +letter?.availableUntil;
  8187. if (availableUntil) {
  8188. const maxTimeLeft = 24 * 60 * 60 * 1000;
  8189. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  8190. console.log('Time left:', timeLeft)
  8191. if (timeLeft < maxTimeLeft) {
  8192. lettersIds.push(~~letter.id);
  8193. continue;
  8194. }
  8195. }
  8196. }
  8197. return lettersIds;
  8198. }
  8199.  
  8200. /**
  8201. * Displaying information about the areas of the portal and attempts on the VG
  8202. *
  8203. * Отображение информации о сферах портала и попытках на ВГ
  8204. */
  8205. async function justInfo() {
  8206. return new Promise(async (resolve, reject) => {
  8207. const calls = [{
  8208. name: "userGetInfo",
  8209. args: {},
  8210. ident: "userGetInfo"
  8211. },
  8212. {
  8213. name: "clanWarGetInfo",
  8214. args: {},
  8215. ident: "clanWarGetInfo"
  8216. },
  8217. {
  8218. name: "titanArenaGetStatus",
  8219. args: {},
  8220. ident: "titanArenaGetStatus"
  8221. }];
  8222. const result = await Send(JSON.stringify({ calls }));
  8223. const infos = result.results;
  8224. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  8225. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  8226. const arePointsMax = infos[1].result.response?.arePointsMax;
  8227. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  8228. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  8229.  
  8230. const sanctuaryButton = buttons['testAdventure'].button;
  8231. const sanctuaryDot = sanctuaryButton.querySelector('.scriptMenu_dot');
  8232. const clanWarButton = buttons['goToClanWar'].button;
  8233. const clanWarDot = clanWarButton.querySelector('.scriptMenu_dot');
  8234. const titansArenaButton = buttons['testTitanArena'].button;
  8235. const titansArenaDot = clanWarButton.querySelector('.scriptMenu_dot');
  8236.  
  8237. if (portalSphere.amount) {
  8238. sanctuaryButton.classList.add('scriptMenu_attention');
  8239. sanctuaryDot.title = `${portalSphere.amount} ${I18N('PORTALS')}`;
  8240. sanctuaryDot.innerText = portalSphere.amount;
  8241. sanctuaryDot.style.backgroundColor = 'red';
  8242. } else {
  8243. sanctuaryButton.classList.remove('scriptMenu_attention');
  8244. }
  8245. if (clanWarMyTries && !arePointsMax) {
  8246. clanWarButton.classList.add('scriptMenu_attention');
  8247. clanWarDot.title = `${clanWarMyTries}${I18N('ATTEMPTS')}`;
  8248. clanWarDot.innerText = clanWarMyTries;
  8249. clanWarDot.style.backgroundColor = 'red';
  8250. } else {
  8251. clanWarButton.classList.remove('scriptMenu_attention');
  8252. }
  8253.  
  8254. if (titansLevel < 7 && titansStatus == 'battle') { ;
  8255. titansArenaButton.classList.add('scriptMenu_attention');
  8256. titansArenaDot.title = `${titansLevel} ${I18N('LEVEL')}`;
  8257. titansArenaDot.innerText = titansLevel;
  8258. titansArenaDot.style.backgroundColor = 'red';
  8259. } else {
  8260. titansArenaButton.classList.remove('scriptMenu_attention');
  8261. }
  8262.  
  8263. const imgPortal =
  8264. 'data:image/gif;base64,R0lGODlhLwAvAHAAACH5BAEAAP8ALAAAAAAvAC8AhwAAABkQWgjF3krO3ghSjAhSzinF3u+tGWvO3s5rGSmE5gha7+/OWghSrWvmnClShCmUlAiE5u+MGe/W3mvvWmspUmvvGSnOWinOnCnOGWsZjErvnAiUlErvWmsIUkrvGQjOWgjOnAjOGUoZjM6MGe/OIWvv5q1KGSnv5mulGe/vWs7v3ozv3kqEGYxKGWuEWmtSKUrv3mNaCEpKUs7OWiml5ggxWmMpEAgZpRlaCO/35q1rGRkxKWtarSkZrRljKSkZhAjv3msIGRk6CEparQhjWq3v3kql3ozOGe/vnM6tGYytWu9rGWuEGYzO3kqE3gil5s6MWq3vnGvFnM7vWoxrGc5KGYyMWs6tWq2MGYzOnO+tWmvFWkqlWoxrWgAZhEqEWq2tWoytnIyt3krFnGul3mulWmulnEIpUkqlGUqlnK3OnK2MWs7OnClSrSmUte+tnGvFGYytGYzvWs5rWowpGa3O3u/OnErFWoyMnGuE3muEnEqEnIyMGYzOWs7OGe9r3u9rWq3vWq1rWq1r3invWimlWu+t3q0pWq2t3u8pWu8p3q0p3invnCnvGe/vGa2tGa3vGa2tnK0pGe9rnK1rnCmlGe8pGe8pnK0pnGsZrSkp3msp3s7vGYzvnM7vnIzvGc6tnM5r3oxr3gilWs6t3owpWs4pWs4p3owp3s5rnIxrnAilGc4pGc4pnIwpnAgp3kop3s7O3u9KGe+MWoxKWoyM3kIIUgiUte+MnErFGc5KWowIGe9K3u9KWq3OWq1KWq1K3gjvWimEWu+M3q0IWq2M3u8IWu8I3q0I3gjvnAjvGa3OGa2MnK0IGe9KnK1KnCmEGe8IGe8InK0InEoZrSkI3msI3s6MnM5K3oxK3giEWs6M3owIWs4IWs4I3owI3s5KnIxKnAiEGc4IGc4InIwInAgI3koI3kJaCAgQKUIpEGtKUkJSKUIIECla7ylazmtahGta70pa70pahGtazkpazmtrWiExUkprUiljWikQKRkQCAAQCAAACAAAAAj/AP8JHEiwoMGDCBMqXMiwocODJlBIRBHDxMOLBmMEkSjAgICPE2Mw/OUH4z8TGz+agBIBCsuWUAQE0WLwzkAkKZZcnAilhk+fA1bUiEC0ZZABJOD8IyHhwJYDkpakafJQ4kooR5yw0LFihQ4WJhAMKCoARRYSTJgkUOInBZK2DiX2rGHEiI67eFcYATtAAVEoKEiQSFBFDs4UKbg0lGgAigIEeCNzrWvCxIChEcoy3dGiSoITTRQvnCLRrxOveI2McbKahevKJmooiKkFy4Gzg5tMMaMwitwIj/PqGPCugL0CT47ANhEjQg3Atg9IT5CiS4uEUcRIBH4EtREETuB9/xn/BUcBBbBXGGgpoPaBEid23EuXgvdBJhtQGFCwwA7eMgs0gEMDBJD3hR7KbRVbSwP8UcIWJNwjIRLXGZRAAhLVsIACR9y1whMNfNGAHgiUcUSBX8ADWwwKzCYADTSUcMA9ebwQmkFYMMFGhgu80x1XTxSAwxNdGWGCAiG6YQBzly3QkhYxlsDGP1cg4YBBaC0h1zsLPGHXCkfA00AZeu11hALl1VBZXwW0RAaMDGDxTxNdTGEQExJoiUINXCpwmhFOKJCcVmCdOR56MezXJhRvwFlCC2lcWVAUEjBxRobw9HhEXUYekWBlsoVoQEWyFbAAFPRIQQMDJcDQhRhYSv+QZ1kGcAnPYya4BhZYlb1TQ4iI+tVmBPpIQQWrMORxkKwSsEFrDaa+8xgCy1mmgLSHxtDXAhtGMIOxDKjgAkLM7iAAYD4VJ+0RAyAgVl++ikfAESxy62QB365awrjLyprAcxEY4FOmXEp7LbctjlfAAE1yGwEBYBirAgP8GtTUARIMM1QBPrVYQAHF9dgiml/Mexl/3DbAwxnHMqBExQVdLAEMjRXQgHOyydaibPCgqEDH3JrawDosUDExCTATZJuMJ0AAxRNXtLFFPD+P/DB58AC9wH4N4BMxDRPvkPRAbLx3AAlVMLBFCXeQgIaIKJKHQ9X8+forAetMsaoKB7j/MAhCL5j9VFNPJYBGiCGW18CtsvWIs5j7gLEGqyV81gxC6ZBQQgkSMEUCLQckMMLHNhcAD3B+8TdyA0PPACWrB8SH0BItyHAAAwdE4YILTSUww8cELwAyt7D4JSberkd5wA4neIFQE020sMPmJZBwAi0SJMBOA6WTXgAsDYDPOj7r3KNFy5WfkEBCKbTQBQzTM+By5wm4YAPr+LM+IIE27LPOFWswmgqqZ4UEXCEhLUjBGWbgAs3JD2OfWcc68GEDArCOAASwAfnWUYUwtIEKSVCBCiSgPuclpAlImMI9YNDAzeFuMEwQ2w3W4Q530PAGLthBFNqwghCKMAoF3MEB/xNihvr8Ix4sdCCrJja47CVAMFjAwid6eJcQWi8BO4jHQl6AGFjdwwUnOMF75CfCMpoxCTpAoxoZMBgs3qMh7ZODQFYYxgSMsQThCpcK0BiZJNxBCZ7zwhsbYqO3wCoe7AjjCaxAggNUcY94mcDa3qMECWSBHYN0CBfj0IQliEFCMFjkIulAAisUkBZYyB4USxAFCZnkH1xsgltSYCMYyACMpizghS7kOTZIKJMmeYEZzCCH6iCmBS1IRzpkcEsXVMGZMMgHJvfwyoLsYQ9nmMIUuDAFPIAhH8pUZjLbcY89rKKaC9nDFeLxy3vkYwbJTMcL0InOeOSjBVShJz2pqQvPfvrznwANKEMCAgA7';
  8265.  
  8266. setProgress('<img src="' + imgPortal + '" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  8267. resolve();
  8268. });
  8269. }
  8270.  
  8271. async function getDailyBonus() {
  8272. const dailyBonusInfo = await Send(JSON.stringify({
  8273. calls: [{
  8274. name: "dailyBonusGetInfo",
  8275. args: {},
  8276. ident: "body"
  8277. }]
  8278. })).then(e => e.results[0].result.response);
  8279. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  8280.  
  8281. if (!availableToday) {
  8282. console.log('Уже собрано');
  8283. return;
  8284. }
  8285.  
  8286. const currentVipPoints = +userInfo.vipPoints;
  8287. const dailyBonusStat = lib.getData('dailyBonusStatic');
  8288. const vipInfo = lib.getData('level').vip;
  8289. let currentVipLevel = 0;
  8290. for (let i in vipInfo) {
  8291. vipLvl = vipInfo[i];
  8292. if (currentVipPoints >= vipLvl.vipPoints) {
  8293. currentVipLevel = vipLvl.level;
  8294. }
  8295. }
  8296. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  8297.  
  8298. const calls = [{
  8299. name: "dailyBonusFarm",
  8300. args: {
  8301. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  8302. },
  8303. ident: "body"
  8304. }];
  8305.  
  8306. const result = await Send(JSON.stringify({ calls }));
  8307. if (result.error) {
  8308. console.error(result.error);
  8309. return;
  8310. }
  8311.  
  8312. const reward = result.results[0].result.response;
  8313. const type = Object.keys(reward).pop();
  8314. const itemId = Object.keys(reward[type]).pop();
  8315. const count = reward[type][itemId];
  8316. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  8317.  
  8318. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  8319. }
  8320.  
  8321. async function farmStamina(lootBoxId = 148) {
  8322. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  8323. .then(e => e.results[0].result.response.consumable[148]);
  8324.  
  8325. /** Добавить другие ящики */
  8326. /**
  8327. * 144 - медная шкатулка
  8328. * 145 - бронзовая шкатулка
  8329. * 148 - платиновая шкатулка
  8330. */
  8331. if (!lootBox) {
  8332. setProgress(I18N('NO_BOXES'), true);
  8333. return;
  8334. }
  8335.  
  8336. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  8337. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  8338. { result: false, isClose: true },
  8339. { msg: I18N('BTN_YES'), result: true },
  8340. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  8341. ]);
  8342. if (!+result) {
  8343. return;
  8344. }
  8345.  
  8346. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  8347. maxFarmEnergy = +result;
  8348. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  8349. } else {
  8350. maxFarmEnergy = 0;
  8351. }
  8352.  
  8353. let collectEnergy = 0;
  8354. for (let count = lootBox; count > 0; count--) {
  8355. const response = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}').then(
  8356. (e) => e.results[0].result.response
  8357. );
  8358. const result = Object.values(response).pop();
  8359. if ('stamina' in result) {
  8360. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8361. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  8362. if (!maxFarmEnergy) {
  8363. return;
  8364. }
  8365. collectEnergy += +result.stamina;
  8366. if (collectEnergy >= maxFarmEnergy) {
  8367. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  8368. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  8369. return;
  8370. }
  8371. } else {
  8372. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8373. console.log(result);
  8374. }
  8375. }
  8376.  
  8377. setProgress(I18N('BOXES_OVER'), true);
  8378. }
  8379.  
  8380. async function fillActive() {
  8381. const data = await Send(JSON.stringify({
  8382. calls: [{
  8383. name: "questGetAll",
  8384. args: {},
  8385. ident: "questGetAll"
  8386. }, {
  8387. name: "inventoryGet",
  8388. args: {},
  8389. ident: "inventoryGet"
  8390. }, {
  8391. name: "clanGetInfo",
  8392. args: {},
  8393. ident: "clanGetInfo"
  8394. }
  8395. ]
  8396. })).then(e => e.results.map(n => n.result.response));
  8397.  
  8398. const quests = data[0];
  8399. const inv = data[1];
  8400. const stat = data[2].stat;
  8401. const maxActive = 2000 - stat.todayItemsActivity;
  8402. if (maxActive <= 0) {
  8403. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  8404. return;
  8405. }
  8406. let countGetActive = 0;
  8407. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  8408. if (quest) {
  8409. countGetActive = 1750 - quest.progress;
  8410. }
  8411. if (countGetActive <= 0) {
  8412. countGetActive = maxActive;
  8413. }
  8414. console.log(countGetActive);
  8415.  
  8416. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  8417. { result: false, isClose: true },
  8418. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  8419. ]));
  8420.  
  8421. if (!countGetActive) {
  8422. return;
  8423. }
  8424.  
  8425. if (countGetActive > maxActive) {
  8426. countGetActive = maxActive;
  8427. }
  8428.  
  8429. const items = lib.getData('inventoryItem');
  8430.  
  8431. let itemsInfo = [];
  8432. for (let type of ['gear', 'scroll']) {
  8433. for (let i in inv[type]) {
  8434. const v = items[type][i]?.enchantValue || 0;
  8435. itemsInfo.push({
  8436. id: i,
  8437. count: inv[type][i],
  8438. v,
  8439. type
  8440. })
  8441. }
  8442. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  8443. for (let i in inv[invType]) {
  8444. const v = items[type][i]?.fragmentEnchantValue || 0;
  8445. itemsInfo.push({
  8446. id: i,
  8447. count: inv[invType][i],
  8448. v,
  8449. type: invType
  8450. })
  8451. }
  8452. }
  8453. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  8454. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  8455. console.log(itemsInfo);
  8456. const activeItem = itemsInfo.shift();
  8457. console.log(activeItem);
  8458. const countItem = Math.ceil(countGetActive / activeItem.v);
  8459. if (countItem > activeItem.count) {
  8460. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  8461. console.log(activeItem);
  8462. return;
  8463. }
  8464.  
  8465. await Send(JSON.stringify({
  8466. calls: [{
  8467. name: "clanItemsForActivity",
  8468. args: {
  8469. items: {
  8470. [activeItem.type]: {
  8471. [activeItem.id]: countItem
  8472. }
  8473. }
  8474. },
  8475. ident: "body"
  8476. }]
  8477. })).then(e => {
  8478. /** TODO: Вывести потраченые предметы */
  8479. console.log(e);
  8480. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  8481. });
  8482. }
  8483.  
  8484. async function buyHeroFragments() {
  8485. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  8486. .then(e => e.results.map(n => n.result.response));
  8487. const inv = result[0];
  8488. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  8489. const calls = [];
  8490.  
  8491. for (let shop of shops) {
  8492. const slots = Object.values(shop.slots);
  8493. for (const slot of slots) {
  8494. /* Уже куплено */
  8495. if (slot.bought) {
  8496. continue;
  8497. }
  8498. /* Не душа героя */
  8499. if (!('fragmentHero' in slot.reward)) {
  8500. continue;
  8501. }
  8502. const coin = Object.keys(slot.cost).pop();
  8503. const coinId = Object.keys(slot.cost[coin]).pop();
  8504. const stock = inv[coin][coinId] || 0;
  8505. /* Не хватает на покупку */
  8506. if (slot.cost[coin][coinId] > stock) {
  8507. continue;
  8508. }
  8509. inv[coin][coinId] -= slot.cost[coin][coinId];
  8510. calls.push({
  8511. name: "shopBuy",
  8512. args: {
  8513. shopId: shop.id,
  8514. slot: slot.id,
  8515. cost: slot.cost,
  8516. reward: slot.reward,
  8517. },
  8518. ident: `shopBuy_${shop.id}_${slot.id}`,
  8519. })
  8520. }
  8521. }
  8522.  
  8523. if (!calls.length) {
  8524. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  8525. return;
  8526. }
  8527.  
  8528. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8529. if (!bought) {
  8530. console.log('что-то пошло не так')
  8531. return;
  8532. }
  8533.  
  8534. let countHeroSouls = 0;
  8535. for (const buy of bought) {
  8536. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  8537. }
  8538. console.log(countHeroSouls, bought, calls);
  8539. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  8540. }
  8541.  
  8542. /** Открыть платные сундуки в Запределье за 90 */
  8543. async function bossOpenChestPay() {
  8544. const callsNames = ['userGetInfo', 'bossGetAll', 'specialOffer_getAll', 'getTime'];
  8545. const info = await Send({ calls: callsNames.map((name) => ({ name, args: {}, ident: name })) }).then((e) =>
  8546. e.results.map((n) => n.result.response)
  8547. );
  8548.  
  8549. const user = info[0];
  8550. const boses = info[1];
  8551. const offers = info[2];
  8552. const time = info[3];
  8553.  
  8554. const discountOffer = offers.find((e) => e.offerType == 'costReplaceOutlandChest');
  8555.  
  8556. let discount = 1;
  8557. if (discountOffer && discountOffer.endTime > time) {
  8558. discount = 1 - discountOffer.offerData.outlandChest.discountPercent / 100;
  8559. }
  8560.  
  8561. cost9chests = 540 * discount;
  8562. cost18chests = 1740 * discount;
  8563. costFirstChest = 90 * discount;
  8564. costSecondChest = 200 * discount;
  8565.  
  8566. const currentStarMoney = user.starMoney;
  8567. if (currentStarMoney < cost9chests) {
  8568. setProgress('Недостаточно изюма, нужно ' + cost9chests + ' у Вас ' + currentStarMoney, true);
  8569. return;
  8570. }
  8571.  
  8572. const imgEmerald =
  8573. "<img style='position: relative;top: 3px;' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAXCAYAAAD+4+QTAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAY8SURBVEhLpVV5bFVlFv/d7a19W3tfN1pKabGFAm3Rlg4toAWRiH+AioiaqAkaE42NycRR0ZnomJnJYHAJERGNyx/GJYoboo2igKVSMUUKreW1pRvUvr7XvvXe9+7qeW1nGJaJycwvObnny/fl/L7zO+c7l8EV0LAKzA+H83lAFAC/BeDJN2gnc5yd/WaQ8Q0NCCnAANkU+ZfjIpKqJWBOd4EDbHagueBPb1tWuesi9Rqn86zJZDbAMTp4xoSFzMaa4FVe6fra3bbzQbYN6A8Cmrz0qoBx8gzMmaj/QfKHWyxs+4e1DiC78M9v5TTn1RtbVH+kMWlJCCad100VOmQiUWFnNLg4HW42QeYEl3KnIiP5Bzu/dr27o0UistD48k2d8rF9Sib9GZKaejAnOmrs2/6e3VR3q7idF41GWVA41uQQ1RMY00ZJrChcrAYvx8HHaSjil8LLilCY98BORylBKlWQHhjzfvfFnuTfPn1O+xFolzM7s5nMI80rSl7qib8ykRNcWyaUosBWgnN6BL3pHuRwucjmnBTUCjfHwElkNiaNPHYr0mYCKnMeE/r3OC2NQiZZheHsfQ9Vu1uAM+eBIX2W5Nqsh/ewtxlrhl75NtUviDpwq+s+NOXWwWFhKKCd6iCQVByV2qSb0wEo5PvhY9YikGrH3uAdiBtBDIdVVAvlyfjBOffuesTcDxySqD3mUxaOPLZ6aktAOS/kqHaYigN7gnsxMGnDAuEuiPw6ymIt3MwaZFFQB7MeTmYjPLSWjTTCioQ5XCOMJIPeoInD/SNOviy6heLmALkckRTyf3xLbtQ8k6sdOodcxoocMoXU9JoFdF8VESMMiWRJmykyedqXTInaQJnOTtYDcJtZ+DXkRSrOou1cCoHx4LptL0nLgYU8kWhwlFgrNV2wFnEmVAr+w9gUzkwQic2DoNmLYe0QgkYXIuYg4uYYosYQJs1fMGkEpqWzUVucDh9E37gCIWFgvY9FcbniEipii6hbwZVilP0kXB/jysrrPLqU3yDG0JzXhA3OjWgsXo8UG6XbR6AxScqJjJHo/gmY0+9FIOn80I0UkukQFohJNFZmwV/uhosX2j59KPuF8JgS5CI3wHB90RUdKL12pMs7Z3VvfH6WyOajPt+Deb7FRDCBmNmNpNmPhHEWCW0IMXUQaTVEtVPhseYTZRCBeB86h8+hY0yDodsHfny+4NETB7JOLN74TXqmu1Yu4ixHuj3ii0/eaatx7RgY/NYKtR2tm+6B7lbwTGg3bDQ06MLTcsoJettR4DqaC8+u/gfe6HwZOzuGQU8JDR5f1B2+6uHWp8RPSjfsj5/dDyMzfIAj3bqSK8bGW579ECPWXRViHTijDK2BPojcPCxkbXCZflh1H5ISkCCSWJxI8jcjmErhnaHh6fdzdbZTd0aKd7Q+5T/gqj6VyBBkwmfG0QySkkHDJq19dDrgvP3GQq/Pt6h/8mesLqqFz+6DRq0qWkR4uGzEYhrGJBktNdvQGfoJH490YwmNuwKt+LWvWubtAk6GlPHhfw/LCyQz0BXEZOaoLcDf1lAt2z1z5nIhlIsL0Csfo90sWDkHXDYXaq2VWFZShffOfoQc0qOIzT9wbGvpXxOYGgG6SdwLuJSE6mPT1ZNdUdM9fyi8YlnTEiHLc423GBPaFBSVQcrQqcMYrJrbjElVRUf8FIq57K4z/8x7rL9f7ymsb0vHz83GmsXlJJSlsXKhxn3w+YSyrC48vKB0zVbLYqHCUYEe5SekaRYznBuLvU1olwbBmvr4r/v4RzteN4761x+Wxg9dGPH/wkzhL8WRHkMvKo7j/sc/Swfir7ZT/WTYSapc6LwFhc4qSKwLEYHXoz/bnzv8dOw7+4ojyYkvLyfI4MokhNToSKZwYf+6u3e39P3y8XH6AeY5yxHiBcx11OA8rZO9qTdaNx9/n9KPyUdnOulKuFyui6GHAAkHpEDBptqauaKtcMySRBW3HH2Do1+9WbP9GXocVGj5okJfit8jATY06Dh+MBIyiwZrrylb4XXneO1BV9df7n/tMb0/0J17O9LJU7Nn/x+UrKvOyOq58dXtNz0Q2Luz+cUnrqe1q+qmyv8q9/+EypuXZrK2kdEwgW3R5pW/r8I0gN8AVk6uP7Y929oAAAAASUVORK5CYII='>";
  8574.  
  8575. if (currentStarMoney < cost9chests) {
  8576. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney, imgEmerald }), true);
  8577. return;
  8578. }
  8579.  
  8580. const buttons = [{ result: false, isClose: true }];
  8581.  
  8582. if (currentStarMoney >= cost9chests) {
  8583. buttons.push({
  8584. msg: I18N('BUY_OUTLAND_BTN', { count: 9, countEmerald: cost9chests, imgEmerald }),
  8585. result: [costFirstChest, costFirstChest, 0],
  8586. });
  8587. }
  8588.  
  8589. if (currentStarMoney >= cost18chests) {
  8590. buttons.push({
  8591. msg: I18N('BUY_OUTLAND_BTN', { count: 18, countEmerald: cost18chests, imgEmerald }),
  8592. result: [costFirstChest, costFirstChest, 0, costSecondChest, costSecondChest, 0],
  8593. });
  8594. }
  8595.  
  8596. const answer = await popup.confirm(`<div style="margin-bottom: 15px;">${I18N('BUY_OUTLAND')}</div>`, buttons);
  8597.  
  8598. if (!answer) {
  8599. return;
  8600. }
  8601.  
  8602. const callBoss = [];
  8603. let n = 0;
  8604. for (let boss of boses) {
  8605. const bossId = boss.id;
  8606. if (boss.chestNum != 2) {
  8607. continue;
  8608. }
  8609. const calls = [];
  8610. for (const starmoney of answer) {
  8611. calls.push({
  8612. name: 'bossOpenChest',
  8613. args: {
  8614. amount: 1,
  8615. bossId,
  8616. starmoney,
  8617. },
  8618. ident: 'bossOpenChest_' + ++n,
  8619. });
  8620. }
  8621. callBoss.push(calls);
  8622. }
  8623.  
  8624. if (!callBoss.length) {
  8625. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  8626. return;
  8627. }
  8628.  
  8629. let count = 0;
  8630. let errors = 0;
  8631. for (const calls of callBoss) {
  8632. const result = await Send({ calls });
  8633. console.log(result);
  8634. if (result?.results) {
  8635. count += result.results.length;
  8636. } else {
  8637. errors++;
  8638. }
  8639. }
  8640.  
  8641. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ${count}`, true);
  8642. }
  8643.  
  8644. async function autoRaidAdventure() {
  8645. const calls = [
  8646. {
  8647. name: "userGetInfo",
  8648. args: {},
  8649. ident: "userGetInfo"
  8650. },
  8651. {
  8652. name: "adventure_raidGetInfo",
  8653. args: {},
  8654. ident: "adventure_raidGetInfo"
  8655. }
  8656. ];
  8657. const result = await Send(JSON.stringify({ calls }))
  8658. .then(e => e.results.map(n => n.result.response));
  8659.  
  8660. const portalSphere = result[0].refillable.find(n => n.id == 45);
  8661. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  8662. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  8663.  
  8664. if (!portalSphere.amount || !adventureId) {
  8665. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  8666. return;
  8667. }
  8668.  
  8669. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  8670. { result: false, isClose: true },
  8671. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  8672. ]));
  8673.  
  8674. if (!countRaid) {
  8675. return;
  8676. }
  8677.  
  8678. if (countRaid > portalSphere.amount) {
  8679. countRaid = portalSphere.amount;
  8680. }
  8681.  
  8682. const resultRaid = await Send(JSON.stringify({
  8683. calls: [...Array(countRaid)].map((e, i) => ({
  8684. name: "adventure_raid",
  8685. args: {
  8686. adventureId
  8687. },
  8688. ident: `body_${i}`
  8689. }))
  8690. })).then(e => e.results.map(n => n.result.response));
  8691.  
  8692. if (!resultRaid.length) {
  8693. console.log(resultRaid);
  8694. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  8695. return;
  8696. }
  8697.  
  8698. console.log(resultRaid, adventureId, portalSphere.amount);
  8699. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  8700. }
  8701.  
  8702. /** Вывести всю клановую статистику в консоль браузера */
  8703. async function clanStatistic() {
  8704. const copy = function (text) {
  8705. const copyTextarea = document.createElement("textarea");
  8706. copyTextarea.style.opacity = "0";
  8707. copyTextarea.textContent = text;
  8708. document.body.appendChild(copyTextarea);
  8709. copyTextarea.select();
  8710. document.execCommand("copy");
  8711. document.body.removeChild(copyTextarea);
  8712. delete copyTextarea;
  8713. }
  8714. const calls = [
  8715. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  8716. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  8717. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  8718. ];
  8719.  
  8720. const result = await Send(JSON.stringify({ calls }));
  8721.  
  8722. const dataClanInfo = result.results[0].result.response;
  8723. const dataClanStat = result.results[1].result.response;
  8724. const dataClanLog = result.results[2].result.response;
  8725.  
  8726. const membersStat = {};
  8727. for (let i = 0; i < dataClanStat.stat.length; i++) {
  8728. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  8729. }
  8730.  
  8731. const joinStat = {};
  8732. historyLog = dataClanLog.history;
  8733. for (let j in historyLog) {
  8734. his = historyLog[j];
  8735. if (his.event == 'join') {
  8736. joinStat[his.userId] = his.ctime;
  8737. }
  8738. }
  8739.  
  8740. const infoArr = [];
  8741. const members = dataClanInfo.clan.members;
  8742. for (let n in members) {
  8743. var member = [
  8744. n,
  8745. members[n].name,
  8746. members[n].level,
  8747. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  8748. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  8749. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  8750. membersStat[n].activity.reverse().join('\t'),
  8751. membersStat[n].adventureStat.reverse().join('\t'),
  8752. membersStat[n].clanGifts.reverse().join('\t'),
  8753. membersStat[n].clanWarStat.reverse().join('\t'),
  8754. membersStat[n].dungeonActivity.reverse().join('\t'),
  8755. ];
  8756. infoArr.push(member);
  8757. }
  8758. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  8759. console.log(info);
  8760. copy(info);
  8761. setProgress(I18N('CLAN_STAT_COPY'), true);
  8762. }
  8763.  
  8764. async function buyInStoreForGold() {
  8765. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  8766. const shops = result[0];
  8767. const user = result[1];
  8768. let gold = user.gold;
  8769. const calls = [];
  8770. if (shops[17]) {
  8771. const slots = shops[17].slots;
  8772. for (let i = 1; i <= 2; i++) {
  8773. if (!slots[i].bought) {
  8774. const costGold = slots[i].cost.gold;
  8775. if ((gold - costGold) < 0) {
  8776. continue;
  8777. }
  8778. gold -= costGold;
  8779. calls.push({
  8780. name: "shopBuy",
  8781. args: {
  8782. shopId: 17,
  8783. slot: i,
  8784. cost: slots[i].cost,
  8785. reward: slots[i].reward,
  8786. },
  8787. ident: 'body_' + i,
  8788. })
  8789. }
  8790. }
  8791. }
  8792. const slots = shops[1].slots;
  8793. for (let i = 4; i <= 6; i++) {
  8794. if (!slots[i].bought && slots[i]?.cost?.gold) {
  8795. const costGold = slots[i].cost.gold;
  8796. if ((gold - costGold) < 0) {
  8797. continue;
  8798. }
  8799. gold -= costGold;
  8800. calls.push({
  8801. name: "shopBuy",
  8802. args: {
  8803. shopId: 1,
  8804. slot: i,
  8805. cost: slots[i].cost,
  8806. reward: slots[i].reward,
  8807. },
  8808. ident: 'body_' + i,
  8809. })
  8810. }
  8811. }
  8812.  
  8813. if (!calls.length) {
  8814. setProgress(I18N('NOTHING_BUY'), true);
  8815. return;
  8816. }
  8817.  
  8818. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8819. console.log(resultBuy);
  8820. const countBuy = resultBuy.length;
  8821. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  8822. }
  8823.  
  8824. function rewardsAndMailFarm() {
  8825. return new Promise(function (resolve, reject) {
  8826. let questGetAllCall = {
  8827. calls: [{
  8828. name: "questGetAll",
  8829. args: {},
  8830. ident: "questGetAll"
  8831. }, {
  8832. name: "mailGetAll",
  8833. args: {},
  8834. ident: "mailGetAll"
  8835. }]
  8836. }
  8837. send(JSON.stringify(questGetAllCall), function (data) {
  8838. if (!data) return;
  8839. const questGetAll = data.results[0].result.response.filter((e) => e.state == 2);
  8840. const questBattlePass = lib.getData('quest').battlePass;
  8841. const questChainBPass = lib.getData('battlePass').questChain;
  8842. const listBattlePass = lib.getData('battlePass').list;
  8843.  
  8844. const questAllFarmCall = {
  8845. calls: [],
  8846. };
  8847. const questIds = [];
  8848. for (let quest of questGetAll) {
  8849. if (quest.id >= 2001e4) {
  8850. continue;
  8851. }
  8852. if (quest.id > 1e6 && quest.id < 2e7) {
  8853. const questInfo = questBattlePass[quest.id];
  8854. const chain = questChainBPass[questInfo.chain];
  8855. if (chain.requirement?.battlePassTicket) {
  8856. continue;
  8857. }
  8858. const battlePass = listBattlePass[chain.battlePass];
  8859. const startTime = battlePass.startCondition.time.value * 1e3
  8860. const endTime = new Date(startTime + battlePass.duration * 1e3);
  8861. if (startTime > Date.now() || endTime < Date.now()) {
  8862. continue;
  8863. }
  8864. }
  8865. if (quest.id >= 2e7) {
  8866. questIds.push(quest.id);
  8867. continue;
  8868. }
  8869. questAllFarmCall.calls.push({
  8870. name: 'questFarm',
  8871. args: {
  8872. questId: quest.id,
  8873. },
  8874. ident: `questFarm_${quest.id}`,
  8875. });
  8876. }
  8877.  
  8878. if (questIds.length) {
  8879. questAllFarmCall.calls.push({
  8880. name: 'quest_questsFarm',
  8881. args: { questIds },
  8882. ident: 'quest_questsFarm',
  8883. });
  8884. }
  8885.  
  8886. let letters = data?.results[1]?.result?.response?.letters;
  8887. letterIds = lettersFilter(letters);
  8888.  
  8889. if (letterIds.length) {
  8890. questAllFarmCall.calls.push({
  8891. name: 'mailFarm',
  8892. args: { letterIds },
  8893. ident: 'mailFarm',
  8894. });
  8895. }
  8896.  
  8897. if (!questAllFarmCall.calls.length) {
  8898. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8899. resolve();
  8900. return;
  8901. }
  8902.  
  8903. send(JSON.stringify(questAllFarmCall), async function (res) {
  8904. let countQuests = 0;
  8905. let countMail = 0;
  8906. let questsIds = [];
  8907. for (let call of res.results) {
  8908. if (call.ident.includes('questFarm')) {
  8909. countQuests++;
  8910. } else if (call.ident.includes('questsFarm')) {
  8911. countQuests += Object.keys(call.result.response).length;
  8912. } else if (call.ident.includes('mailFarm')) {
  8913. countMail = Object.keys(call.result.response).length;
  8914. }
  8915.  
  8916. const newQuests = call.result.newQuests;
  8917. if (newQuests) {
  8918. for (let quest of newQuests) {
  8919. if ((quest.id < 1e6 || (quest.id >= 2e7 && quest.id < 2001e4)) && quest.state == 2) {
  8920. questsIds.push(quest.id);
  8921. }
  8922. }
  8923. }
  8924. }
  8925.  
  8926. while (questsIds.length) {
  8927. const questIds = [];
  8928. const calls = [];
  8929. for (let questId of questsIds) {
  8930. if (questId < 1e6) {
  8931. calls.push({
  8932. name: 'questFarm',
  8933. args: {
  8934. questId,
  8935. },
  8936. ident: `questFarm_${questId}`,
  8937. });
  8938. countQuests++;
  8939. } else if (questId >= 2e7 && questId < 2001e4) {
  8940. questIds.push(questId);
  8941. countQuests++;
  8942. }
  8943. }
  8944. calls.push({
  8945. name: 'quest_questsFarm',
  8946. args: { questIds },
  8947. ident: 'body',
  8948. });
  8949. const results = await Send({ calls }).then((e) => e.results.map((e) => e.result));
  8950. questsIds = [];
  8951. for (const result of results) {
  8952. const newQuests = result.newQuests;
  8953. if (newQuests) {
  8954. for (let quest of newQuests) {
  8955. if (quest.state == 2) {
  8956. questsIds.push(quest.id);
  8957. }
  8958. }
  8959. }
  8960. }
  8961. }
  8962.  
  8963. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  8964. resolve();
  8965. });
  8966. });
  8967. })
  8968. }
  8969.  
  8970. class epicBrawl {
  8971. timeout = null;
  8972. time = null;
  8973.  
  8974. constructor() {
  8975. if (epicBrawl.inst) {
  8976. return epicBrawl.inst;
  8977. }
  8978. epicBrawl.inst = this;
  8979. return this;
  8980. }
  8981.  
  8982. runTimeout(func, timeDiff) {
  8983. const worker = new Worker(URL.createObjectURL(new Blob([`
  8984. self.onmessage = function(e) {
  8985. const timeDiff = e.data;
  8986.  
  8987. if (timeDiff > 0) {
  8988. setTimeout(() => {
  8989. self.postMessage(1);
  8990. self.close();
  8991. }, timeDiff);
  8992. }
  8993. };
  8994. `])));
  8995. worker.postMessage(timeDiff);
  8996. worker.onmessage = () => {
  8997. func();
  8998. };
  8999. return true;
  9000. }
  9001.  
  9002. timeDiff(date1, date2) {
  9003. const date1Obj = new Date(date1);
  9004. const date2Obj = new Date(date2);
  9005.  
  9006. const timeDiff = Math.abs(date2Obj - date1Obj);
  9007.  
  9008. const totalSeconds = timeDiff / 1000;
  9009. const minutes = Math.floor(totalSeconds / 60);
  9010. const seconds = Math.floor(totalSeconds % 60);
  9011.  
  9012. const formattedMinutes = String(minutes).padStart(2, '0');
  9013. const formattedSeconds = String(seconds).padStart(2, '0');
  9014.  
  9015. return `${formattedMinutes}:${formattedSeconds}`;
  9016. }
  9017.  
  9018. check() {
  9019. console.log(new Date(this.time))
  9020. if (Date.now() > this.time) {
  9021. this.timeout = null;
  9022. this.start()
  9023. return;
  9024. }
  9025. this.timeout = this.runTimeout(() => this.check(), 6e4);
  9026. return this.timeDiff(this.time, Date.now())
  9027. }
  9028.  
  9029. async start() {
  9030. if (this.timeout) {
  9031. const time = this.timeDiff(this.time, Date.now());
  9032. console.log(new Date(this.time))
  9033. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  9034. return;
  9035. }
  9036. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  9037. const teamInfo = await Send('{"calls":[{"name":"teamGetAll","args":{},"ident":"teamGetAll"},{"name":"teamGetFavor","args":{},"ident":"teamGetFavor"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  9038. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  9039. this.time = (refill.lastRefill + 3600) * 1000
  9040. const attempts = refill.amount;
  9041. if (!attempts) {
  9042. console.log(new Date(this.time));
  9043. const time = this.check();
  9044. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  9045. return;
  9046. }
  9047.  
  9048. if (!teamInfo[0].epic_brawl) {
  9049. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  9050. return;
  9051. }
  9052.  
  9053. const args = {
  9054. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  9055. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  9056. favor: teamInfo[1].epic_brawl,
  9057. }
  9058.  
  9059. let wins = 0;
  9060. let coins = 0;
  9061. let streak = { progress: 0, nextStage: 0 };
  9062. for (let i = attempts; i > 0; i--) {
  9063. const info = await Send(JSON.stringify({
  9064. calls: [
  9065. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  9066. ]
  9067. })).then(e => e.results.map(n => n.result.response));
  9068.  
  9069. const { progress, result } = await Calc(info[1].battle);
  9070. const endResult = await Send(JSON.stringify({ calls: [{ name: "epicBrawl_endBattle", args: { progress, result }, ident: "epicBrawl_endBattle" }, { name: "epicBrawl_getWinStreak", args: {}, ident: "epicBrawl_getWinStreak" }] })).then(e => e.results.map(n => n.result.response));
  9071.  
  9072. const resultInfo = endResult[0].result;
  9073. streak = endResult[1];
  9074.  
  9075. wins += resultInfo.win;
  9076. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  9077.  
  9078. console.log(endResult[0].result)
  9079. if (endResult[1].progress == endResult[1].nextStage) {
  9080. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  9081. coins += farm.coin[39];
  9082. }
  9083.  
  9084. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9085. i, wins, attempts, coins,
  9086. progress: streak.progress,
  9087. nextStage: streak.nextStage,
  9088. end: '',
  9089. }), false, hideProgress);
  9090. }
  9091.  
  9092. console.log(new Date(this.time));
  9093. const time = this.check();
  9094. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9095. wins, attempts, coins,
  9096. i: '',
  9097. progress: streak.progress,
  9098. nextStage: streak.nextStage,
  9099. end: I18N('ATTEMPT_ENDED', { time }),
  9100. }), false, hideProgress);
  9101. }
  9102. }
  9103.  
  9104. function countdownTimer(seconds, message) {
  9105. message = message || I18N('TIMER');
  9106. const stopTimer = Date.now() + seconds * 1e3
  9107. return new Promise(resolve => {
  9108. const interval = setInterval(async () => {
  9109. const now = Date.now();
  9110. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  9111. if (now > stopTimer) {
  9112. clearInterval(interval);
  9113. setProgress('', 1);
  9114. resolve();
  9115. }
  9116. }, 100);
  9117. });
  9118. }
  9119.  
  9120. this.HWHFuncs.countdownTimer = countdownTimer;
  9121.  
  9122. /** Набить килов в горниле душк */
  9123. async function bossRatingEventSouls() {
  9124. const data = await Send({
  9125. calls: [
  9126. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  9127. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  9128. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  9129. ]
  9130. });
  9131. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  9132. if (!bossEventInfo) {
  9133. setProgress('Эвент завершен', true);
  9134. return;
  9135. }
  9136.  
  9137. if (bossEventInfo.progress.score > 250) {
  9138. setProgress('Уже убито больше 250 врагов');
  9139. rewardBossRatingEventSouls();
  9140. return;
  9141. }
  9142. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  9143. const heroGetAllList = data.results[0].result.response;
  9144. const usedHeroes = bossEventInfo.progress.usedHeroes;
  9145. const heroList = [];
  9146.  
  9147. for (let heroId in heroGetAllList) {
  9148. let hero = heroGetAllList[heroId];
  9149. if (usedHeroes.includes(hero.id)) {
  9150. continue;
  9151. }
  9152. heroList.push(hero.id);
  9153. }
  9154.  
  9155. if (!heroList.length) {
  9156. setProgress('Нет героев', true);
  9157. return;
  9158. }
  9159.  
  9160. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  9161. const petLib = lib.getData('pet');
  9162. let count = 1;
  9163.  
  9164. for (const heroId of heroList) {
  9165. const args = {
  9166. heroes: [heroId],
  9167. pet
  9168. }
  9169. /** Поиск питомца для героя */
  9170. for (const petId of availablePets) {
  9171. if (petLib[petId].favorHeroes.includes(heroId)) {
  9172. args.favor = {
  9173. [heroId]: petId
  9174. }
  9175. break;
  9176. }
  9177. }
  9178.  
  9179. const calls = [{
  9180. name: "bossRatingEvent_startBattle",
  9181. args,
  9182. ident: "body"
  9183. }, {
  9184. name: "offerGetAll",
  9185. args: {},
  9186. ident: "offerGetAll"
  9187. }];
  9188.  
  9189. const res = await Send({ calls });
  9190. count++;
  9191.  
  9192. if ('error' in res) {
  9193. console.error(res.error);
  9194. setProgress('Перезагрузите игру и попробуйте позже', true);
  9195. return;
  9196. }
  9197.  
  9198. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  9199. if (eventInfo.progress.score > 250) {
  9200. break;
  9201. }
  9202. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  9203. }
  9204.  
  9205. rewardBossRatingEventSouls();
  9206. }
  9207. /** Сбор награды из Горнила Душ */
  9208. async function rewardBossRatingEventSouls() {
  9209. const data = await Send({
  9210. calls: [
  9211. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  9212. ]
  9213. });
  9214.  
  9215. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  9216. if (!bossEventInfo) {
  9217. setProgress('Эвент завершен', true);
  9218. return;
  9219. }
  9220.  
  9221. const farmedChests = bossEventInfo.progress.farmedChests;
  9222. const score = bossEventInfo.progress.score;
  9223. // setProgress('Количество убитых врагов: ' + score);
  9224. const revard = bossEventInfo.reward;
  9225. const calls = [];
  9226.  
  9227. let count = 0;
  9228. for (let i = 1; i < 10; i++) {
  9229. if (farmedChests.includes(i)) {
  9230. continue;
  9231. }
  9232. if (score < revard[i].score) {
  9233. break;
  9234. }
  9235. calls.push({
  9236. name: "bossRatingEvent_getReward",
  9237. args: {
  9238. rewardId: i
  9239. },
  9240. ident: "body_" + i
  9241. });
  9242. count++;
  9243. }
  9244. if (!count) {
  9245. setProgress('Нечего собирать', true);
  9246. return;
  9247. }
  9248.  
  9249. Send({ calls }).then(e => {
  9250. console.log(e);
  9251. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  9252. })
  9253. }
  9254. /**
  9255. * Spin the Seer
  9256. *
  9257. * Покрутить провидца
  9258. */
  9259. async function rollAscension() {
  9260. const refillable = await Send({calls:[
  9261. {
  9262. name:"userGetInfo",
  9263. args:{},
  9264. ident:"userGetInfo"
  9265. }
  9266. ]}).then(e => e.results[0].result.response.refillable);
  9267. const i47 = refillable.find(i => i.id == 47);
  9268. if (i47?.amount) {
  9269. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  9270. setProgress(I18N('DONE'), true);
  9271. } else {
  9272. setProgress(I18N('NOT_ENOUGH_AP'), true);
  9273. }
  9274. }
  9275.  
  9276. /**
  9277. * Collect gifts for the New Year
  9278. *
  9279. * Собрать подарки на новый год
  9280. */
  9281. function getGiftNewYear() {
  9282. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  9283. const gifts = e.results[0].result.response.gifts;
  9284. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  9285. name: "newYearGiftOpen",
  9286. args: {
  9287. giftId: e.id
  9288. },
  9289. ident: `body_${e.id}`
  9290. }));
  9291. if (!calls.length) {
  9292. setProgress(I18N('NY_NO_GIFTS'), 5000);
  9293. return;
  9294. }
  9295. Send({ calls }).then(e => {
  9296. console.log(e.results)
  9297. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  9298. console.log(msg);
  9299. setProgress(msg, 5000);
  9300. });
  9301. })
  9302. }
  9303.  
  9304. async function updateArtifacts() {
  9305. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9306. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9307. { result: false, isClose: true }
  9308. ]);
  9309. if (!count) {
  9310. return;
  9311. }
  9312. const quest = new questRun;
  9313. await quest.autoInit();
  9314. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9315. const inventory = quest.questInfo['inventoryGet'];
  9316. const calls = [];
  9317. for (let i = count; i > 0; i--) {
  9318. const upArtifact = quest.getUpgradeArtifact();
  9319. if (!upArtifact.heroId) {
  9320. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9321. { msg: I18N('YES'), result: true },
  9322. { result: false, isClose: true }
  9323. ])) {
  9324. break;
  9325. } else {
  9326. return;
  9327. }
  9328. }
  9329. const hero = heroes.find(e => e.id == upArtifact.heroId);
  9330. hero.artifacts[upArtifact.slotId].level++;
  9331. inventory[upArtifact.costCurrency][upArtifact.costId] -= upArtifact.costValue;
  9332. calls.push({
  9333. name: "heroArtifactLevelUp",
  9334. args: {
  9335. heroId: upArtifact.heroId,
  9336. slotId: upArtifact.slotId
  9337. },
  9338. ident: `heroArtifactLevelUp_${i}`
  9339. });
  9340. }
  9341.  
  9342. if (!calls.length) {
  9343. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9344. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9345. return;
  9346. }
  9347.  
  9348. await Send(JSON.stringify({ calls })).then(e => {
  9349. if ('error' in e) {
  9350. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9351. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9352. } else {
  9353. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9354. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9355. }
  9356. });
  9357. }
  9358.  
  9359. window.sign = a => {
  9360. const i = this['\x78\x79\x7a'];
  9361. return md5([i['\x6e\x61\x6d\x65'], i['\x76\x65\x72\x73\x69\x6f\x6e'], i['\x61\x75\x74\x68\x6f\x72'], ~(a % 1e3)]['\x6a\x6f\x69\x6e']('\x5f'))
  9362. }
  9363.  
  9364. async function updateSkins() {
  9365. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9366. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9367. { result: false, isClose: true }
  9368. ]);
  9369. if (!count) {
  9370. return;
  9371. }
  9372.  
  9373. const quest = new questRun;
  9374. await quest.autoInit();
  9375. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9376. const inventory = quest.questInfo['inventoryGet'];
  9377. const calls = [];
  9378. for (let i = count; i > 0; i--) {
  9379. const upSkin = quest.getUpgradeSkin();
  9380. if (!upSkin.heroId) {
  9381. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9382. { msg: I18N('YES'), result: true },
  9383. { result: false, isClose: true }
  9384. ])) {
  9385. break;
  9386. } else {
  9387. return;
  9388. }
  9389. }
  9390. const hero = heroes.find(e => e.id == upSkin.heroId);
  9391. hero.skins[upSkin.skinId]++;
  9392. inventory[upSkin.costCurrency][upSkin.costCurrencyId] -= upSkin.cost;
  9393. calls.push({
  9394. name: "heroSkinUpgrade",
  9395. args: {
  9396. heroId: upSkin.heroId,
  9397. skinId: upSkin.skinId
  9398. },
  9399. ident: `heroSkinUpgrade_${i}`
  9400. })
  9401. }
  9402.  
  9403. if (!calls.length) {
  9404. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9405. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9406. return;
  9407. }
  9408.  
  9409. await Send(JSON.stringify({ calls })).then(e => {
  9410. if ('error' in e) {
  9411. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9412. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9413. } else {
  9414. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9415. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9416. }
  9417. });
  9418. }
  9419.  
  9420. function getQuestionInfo(img, nameOnly = false) {
  9421. const libHeroes = Object.values(lib.data.hero);
  9422. const parts = img.split(':');
  9423. const id = parts[1];
  9424. switch (parts[0]) {
  9425. case 'titanArtifact_id':
  9426. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  9427. case 'titan':
  9428. return cheats.translate("LIB_HERO_NAME_" + id);
  9429. case 'skill':
  9430. return cheats.translate("LIB_SKILL_" + id);
  9431. case 'inventoryItem_gear':
  9432. return cheats.translate("LIB_GEAR_NAME_" + id);
  9433. case 'inventoryItem_coin':
  9434. return cheats.translate("LIB_COIN_NAME_" + id);
  9435. case 'artifact':
  9436. if (nameOnly) {
  9437. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  9438. }
  9439. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  9440. return {
  9441. /** Как называется этот артефакт? */
  9442. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  9443. /** Какому герою принадлежит этот артефакт? */
  9444. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  9445. };
  9446. case 'hero':
  9447. if (nameOnly) {
  9448. return cheats.translate("LIB_HERO_NAME_" + id);
  9449. }
  9450. artifacts = lib.data.hero[id].artifacts;
  9451. return {
  9452. /** Как зовут этого героя? */
  9453. name: cheats.translate("LIB_HERO_NAME_" + id),
  9454. /** Какой артефакт принадлежит этому герою? */
  9455. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  9456. };
  9457. }
  9458. }
  9459.  
  9460. function hintQuest(quest) {
  9461. const result = {};
  9462. if (quest?.questionIcon) {
  9463. const info = getQuestionInfo(quest.questionIcon);
  9464. if (info?.heroes) {
  9465. /** Какому герою принадлежит этот артефакт? */
  9466. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  9467. }
  9468. if (info?.artifact) {
  9469. /** Какой артефакт принадлежит этому герою? */
  9470. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  9471. }
  9472. if (typeof info == 'string') {
  9473. result.info = { name: info };
  9474. } else {
  9475. result.info = info;
  9476. }
  9477. }
  9478.  
  9479. if (quest.answers[0]?.answerIcon) {
  9480. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  9481. }
  9482.  
  9483. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  9484. return false;
  9485. }
  9486.  
  9487. let resultText = '';
  9488. if (result?.info) {
  9489. resultText += I18N('PICTURE') + result.info.name;
  9490. }
  9491. console.log(result);
  9492. if (result?.answer && result.answer.length) {
  9493. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  9494. }
  9495.  
  9496. return resultText;
  9497. }
  9498.  
  9499. async function farmBattlePass() {
  9500. const isFarmReward = (reward) => {
  9501. return !(reward?.buff || reward?.fragmentHero || reward?.bundleHeroReward);
  9502. };
  9503.  
  9504. const battlePassProcess = (pass) => {
  9505. if (!pass.id) {return []}
  9506. const levels = Object.values(lib.data.battlePass.level).filter(x => x.battlePass == pass.id)
  9507. const last_level = levels[levels.length - 1];
  9508. let actual = Math.max(...levels.filter(p => pass.exp >= p.experience).map(p => p.level))
  9509.  
  9510. if (pass.exp > last_level.experience) {
  9511. actual = last_level.level + (pass.exp - last_level.experience) / last_level.experienceByLevel;
  9512. }
  9513. const calls = [];
  9514. for(let i = 1; i <= actual; i++) {
  9515. const level = i >= last_level.level ? last_level : levels.find(l => l.level === i);
  9516. const reward = {free: level?.freeReward, paid:level?.paidReward};
  9517.  
  9518. if (!pass.rewards[i]?.free && isFarmReward(reward.free)) {
  9519. const args = {level: i, free:true};
  9520. if (!pass.gold) { args.id = pass.id }
  9521. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_free_${args.id}_${i}` });
  9522. }
  9523. if (pass.ticket && !pass.rewards[i]?.paid && isFarmReward(reward.paid)) {
  9524. const args = {level: i, free:false};
  9525. if (!pass.gold) { args.id = pass.id}
  9526. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_paid_${args.id}_${i}` });
  9527. }
  9528. }
  9529. return calls;
  9530. }
  9531.  
  9532. const passes = await Send({
  9533. calls: [
  9534. { name: 'battlePass_getInfo', args: {}, ident: 'getInfo' },
  9535. { name: 'battlePass_getSpecial', args: {}, ident: 'getSpecial' },
  9536. ],
  9537. }).then((e) => [{...e.results[0].result.response?.battlePass, gold: true}, ...Object.values(e.results[1].result.response)]);
  9538.  
  9539. const calls = passes.map(p => battlePassProcess(p)).flat()
  9540.  
  9541. if (!calls.length) {
  9542. setProgress(I18N('NOTHING_TO_COLLECT'));
  9543. return;
  9544. }
  9545.  
  9546. let results = await Send({calls});
  9547. if (results.error) {
  9548. console.log(results.error);
  9549. setProgress(I18N('SOMETHING_WENT_WRONG'));
  9550. } else {
  9551. setProgress(I18N('SEASON_REWARD_COLLECTED', {count: results.results.length}), true);
  9552. }
  9553. }
  9554.  
  9555. async function sellHeroSoulsForGold() {
  9556. let { fragmentHero, heroes } = await Send({
  9557. calls: [
  9558. { name: 'inventoryGet', args: {}, ident: 'inventoryGet' },
  9559. { name: 'heroGetAll', args: {}, ident: 'heroGetAll' },
  9560. ],
  9561. })
  9562. .then((e) => e.results.map((r) => r.result.response))
  9563. .then((e) => ({ fragmentHero: e[0].fragmentHero, heroes: e[1] }));
  9564.  
  9565. const calls = [];
  9566. for (let i in fragmentHero) {
  9567. if (heroes[i] && heroes[i].star == 6) {
  9568. calls.push({
  9569. name: 'inventorySell',
  9570. args: {
  9571. type: 'hero',
  9572. libId: i,
  9573. amount: fragmentHero[i],
  9574. fragment: true,
  9575. },
  9576. ident: 'inventorySell_' + i,
  9577. });
  9578. }
  9579. }
  9580. if (!calls.length) {
  9581. console.log(0);
  9582. return 0;
  9583. }
  9584. const rewards = await Send({ calls }).then((e) => e.results.map((r) => r.result?.response?.gold || 0));
  9585. const gold = rewards.reduce((e, a) => e + a, 0);
  9586. setProgress(I18N('GOLD_RECEIVED', { gold }), true);
  9587. }
  9588.  
  9589. /**
  9590. * Attack of the minions of Asgard
  9591. *
  9592. * Атака прислужников Асгарда
  9593. */
  9594. function testRaidNodes() {
  9595. const { executeRaidNodes } = HWHClasses;
  9596. return new Promise((resolve, reject) => {
  9597. const tower = new executeRaidNodes(resolve, reject);
  9598. tower.start();
  9599. });
  9600. }
  9601.  
  9602. /**
  9603. * Attack of the minions of Asgard
  9604. *
  9605. * Атака прислужников Асгарда
  9606. */
  9607. function executeRaidNodes(resolve, reject) {
  9608. let raidData = {
  9609. teams: [],
  9610. favor: {},
  9611. nodes: [],
  9612. attempts: 0,
  9613. countExecuteBattles: 0,
  9614. cancelBattle: 0,
  9615. }
  9616.  
  9617. callsExecuteRaidNodes = {
  9618. calls: [{
  9619. name: "clanRaid_getInfo",
  9620. args: {},
  9621. ident: "clanRaid_getInfo"
  9622. }, {
  9623. name: "teamGetAll",
  9624. args: {},
  9625. ident: "teamGetAll"
  9626. }, {
  9627. name: "teamGetFavor",
  9628. args: {},
  9629. ident: "teamGetFavor"
  9630. }]
  9631. }
  9632.  
  9633. this.start = function () {
  9634. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  9635. }
  9636.  
  9637. async function startRaidNodes(data) {
  9638. res = data.results;
  9639. clanRaidInfo = res[0].result.response;
  9640. teamGetAll = res[1].result.response;
  9641. teamGetFavor = res[2].result.response;
  9642.  
  9643. let index = 0;
  9644. let isNotFullPack = false;
  9645. for (let team of teamGetAll.clanRaid_nodes) {
  9646. if (team.length < 6) {
  9647. isNotFullPack = true;
  9648. }
  9649. raidData.teams.push({
  9650. data: {},
  9651. heroes: team.filter(id => id < 6000),
  9652. pet: team.filter(id => id >= 6000).pop(),
  9653. battleIndex: index++
  9654. });
  9655. }
  9656. raidData.favor = teamGetFavor.clanRaid_nodes;
  9657.  
  9658. if (isNotFullPack) {
  9659. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  9660. { msg: I18N('BTN_NO'), result: true },
  9661. { msg: I18N('BTN_YES'), result: false },
  9662. ])) {
  9663. endRaidNodes('isNotFullPack');
  9664. return;
  9665. }
  9666. }
  9667.  
  9668. raidData.nodes = clanRaidInfo.nodes;
  9669. raidData.attempts = clanRaidInfo.attempts;
  9670. setIsCancalBattle(false);
  9671.  
  9672. checkNodes();
  9673. }
  9674.  
  9675. function getAttackNode() {
  9676. for (let nodeId in raidData.nodes) {
  9677. let node = raidData.nodes[nodeId];
  9678. let points = 0
  9679. for (team of node.teams) {
  9680. points += team.points;
  9681. }
  9682. let now = Date.now() / 1000;
  9683. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  9684. let countTeam = node.teams.length;
  9685. delete raidData.nodes[nodeId];
  9686. return {
  9687. nodeId,
  9688. countTeam
  9689. };
  9690. }
  9691. }
  9692. return null;
  9693. }
  9694.  
  9695. function checkNodes() {
  9696. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  9697. let nodeInfo = getAttackNode();
  9698. if (nodeInfo && raidData.attempts) {
  9699. startNodeBattles(nodeInfo);
  9700. return;
  9701. }
  9702.  
  9703. endRaidNodes('EndRaidNodes');
  9704. }
  9705.  
  9706. function startNodeBattles(nodeInfo) {
  9707. let {nodeId, countTeam} = nodeInfo;
  9708. let teams = raidData.teams.slice(0, countTeam);
  9709. let heroes = raidData.teams.map(e => e.heroes).flat();
  9710. let favor = {...raidData.favor};
  9711. for (let heroId in favor) {
  9712. if (!heroes.includes(+heroId)) {
  9713. delete favor[heroId];
  9714. }
  9715. }
  9716.  
  9717. let calls = [{
  9718. name: "clanRaid_startNodeBattles",
  9719. args: {
  9720. nodeId,
  9721. teams,
  9722. favor
  9723. },
  9724. ident: "body"
  9725. }];
  9726.  
  9727. send(JSON.stringify({calls}), resultNodeBattles);
  9728. }
  9729.  
  9730. function resultNodeBattles(e) {
  9731. if (e['error']) {
  9732. endRaidNodes('nodeBattlesError', e['error']);
  9733. return;
  9734. }
  9735.  
  9736. console.log(e);
  9737. let battles = e.results[0].result.response.battles;
  9738. let promises = [];
  9739. let battleIndex = 0;
  9740. for (let battle of battles) {
  9741. battle.battleIndex = battleIndex++;
  9742. promises.push(calcBattleResult(battle));
  9743. }
  9744.  
  9745. Promise.all(promises)
  9746. .then(results => {
  9747. const endResults = {};
  9748. let isAllWin = true;
  9749. for (let r of results) {
  9750. isAllWin &&= r.result.win;
  9751. }
  9752. if (!isAllWin) {
  9753. cancelEndNodeBattle(results[0]);
  9754. return;
  9755. }
  9756. raidData.countExecuteBattles = results.length;
  9757. let timeout = 500;
  9758. for (let r of results) {
  9759. setTimeout(endNodeBattle, timeout, r);
  9760. timeout += 500;
  9761. }
  9762. });
  9763. }
  9764. /**
  9765. * Returns the battle calculation promise
  9766. *
  9767. * Возвращает промис расчета боя
  9768. */
  9769. function calcBattleResult(battleData) {
  9770. return new Promise(function (resolve, reject) {
  9771. BattleCalc(battleData, "get_clanPvp", resolve);
  9772. });
  9773. }
  9774. /**
  9775. * Cancels the fight
  9776. *
  9777. * Отменяет бой
  9778. */
  9779. function cancelEndNodeBattle(r) {
  9780. const fixBattle = function (heroes) {
  9781. for (const ids in heroes) {
  9782. hero = heroes[ids];
  9783. hero.energy = random(1, 999);
  9784. if (hero.hp > 0) {
  9785. hero.hp = random(1, hero.hp);
  9786. }
  9787. }
  9788. }
  9789. fixBattle(r.progress[0].attackers.heroes);
  9790. fixBattle(r.progress[0].defenders.heroes);
  9791. endNodeBattle(r);
  9792. }
  9793. /**
  9794. * Ends the fight
  9795. *
  9796. * Завершает бой
  9797. */
  9798. function endNodeBattle(r) {
  9799. let nodeId = r.battleData.result.nodeId;
  9800. let battleIndex = r.battleData.battleIndex;
  9801. let calls = [{
  9802. name: "clanRaid_endNodeBattle",
  9803. args: {
  9804. nodeId,
  9805. battleIndex,
  9806. result: r.result,
  9807. progress: r.progress
  9808. },
  9809. ident: "body"
  9810. }]
  9811.  
  9812. SendRequest(JSON.stringify({calls}), battleResult);
  9813. }
  9814. /**
  9815. * Processing the results of the battle
  9816. *
  9817. * Обработка результатов боя
  9818. */
  9819. function battleResult(e) {
  9820. if (e['error']) {
  9821. endRaidNodes('missionEndError', e['error']);
  9822. return;
  9823. }
  9824. r = e.results[0].result.response;
  9825. if (r['error']) {
  9826. if (r.reason == "invalidBattle") {
  9827. raidData.cancelBattle++;
  9828. checkNodes();
  9829. } else {
  9830. endRaidNodes('missionEndError', e['error']);
  9831. }
  9832. return;
  9833. }
  9834.  
  9835. if (!(--raidData.countExecuteBattles)) {
  9836. raidData.attempts--;
  9837. checkNodes();
  9838. }
  9839. }
  9840. /**
  9841. * Completing a task
  9842. *
  9843. * Завершение задачи
  9844. */
  9845. function endRaidNodes(reason, info) {
  9846. setIsCancalBattle(true);
  9847. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  9848. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  9849. console.log(reason, info);
  9850. resolve();
  9851. }
  9852. }
  9853.  
  9854. this.HWHClasses.executeRaidNodes = executeRaidNodes;
  9855.  
  9856. /**
  9857. * Asgard Boss Attack Replay
  9858. *
  9859. * Повтор атаки босса Асгарда
  9860. */
  9861. function testBossBattle() {
  9862. const { executeBossBattle } = HWHClasses;
  9863. return new Promise((resolve, reject) => {
  9864. const bossBattle = new executeBossBattle(resolve, reject);
  9865. bossBattle.start(lastBossBattle);
  9866. });
  9867. }
  9868.  
  9869. /**
  9870. * Asgard Boss Attack Replay
  9871. *
  9872. * Повтор атаки босса Асгарда
  9873. */
  9874. function executeBossBattle(resolve, reject) {
  9875.  
  9876. this.start = function (battleInfo) {
  9877. preCalcBattle(battleInfo);
  9878. }
  9879.  
  9880. function getBattleInfo(battle) {
  9881. return new Promise(function (resolve) {
  9882. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9883. BattleCalc(battle, getBattleType(battle.type), e => {
  9884. let extra = e.progress[0].defenders.heroes[1].extra;
  9885. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  9886. });
  9887. });
  9888. }
  9889.  
  9890. function preCalcBattle(battle) {
  9891. let actions = [];
  9892. const countTestBattle = getInput('countTestBattle');
  9893. for (let i = 0; i < countTestBattle; i++) {
  9894. actions.push(getBattleInfo(battle, true));
  9895. }
  9896. Promise.all(actions)
  9897. .then(resultPreCalcBattle);
  9898. }
  9899.  
  9900. async function resultPreCalcBattle(damages) {
  9901. let maxDamage = 0;
  9902. let minDamage = 1e10;
  9903. let avgDamage = 0;
  9904. for (let damage of damages) {
  9905. avgDamage += damage
  9906. if (damage > maxDamage) {
  9907. maxDamage = damage;
  9908. }
  9909. if (damage < minDamage) {
  9910. minDamage = damage;
  9911. }
  9912. }
  9913. avgDamage /= damages.length;
  9914. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  9915.  
  9916. await popup.confirm(
  9917. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  9918. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  9919. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  9920. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  9921. , [
  9922. { msg: I18N('BTN_OK'), result: 0},
  9923. ])
  9924. endBossBattle(I18N('BTN_CANCEL'));
  9925. }
  9926.  
  9927. /**
  9928. * Completing a task
  9929. *
  9930. * Завершение задачи
  9931. */
  9932. function endBossBattle(reason, info) {
  9933. console.log(reason, info);
  9934. resolve();
  9935. }
  9936. }
  9937.  
  9938. this.HWHClasses.executeBossBattle = executeBossBattle;
  9939.  
  9940. class FixBattle {
  9941. minTimer = 1.3;
  9942. maxTimer = 15.3;
  9943.  
  9944. constructor(battle, isTimeout = true) {
  9945. this.battle = structuredClone(battle);
  9946. this.isTimeout = isTimeout;
  9947. }
  9948.  
  9949. timeout(callback, timeout) {
  9950. if (this.isTimeout) {
  9951. this.worker.postMessage(timeout);
  9952. this.worker.onmessage = callback;
  9953. } else {
  9954. callback();
  9955. }
  9956. }
  9957.  
  9958. randTimer() {
  9959. return Math.random() * (this.maxTimer - this.minTimer + 1) + this.minTimer;
  9960. }
  9961.  
  9962. setAvgTime(startTime) {
  9963. this.fixTime += Date.now() - startTime;
  9964. this.avgTime = this.fixTime / this.count;
  9965. }
  9966.  
  9967. init() {
  9968. this.fixTime = 0;
  9969. this.lastTimer = 0;
  9970. this.index = 0;
  9971. this.lastBossDamage = 0;
  9972. this.bestResult = {
  9973. count: 0,
  9974. timer: 0,
  9975. value: 0,
  9976. result: null,
  9977. progress: null,
  9978. };
  9979. this.lastBattleResult = {
  9980. win: false,
  9981. };
  9982. this.worker = new Worker(
  9983. URL.createObjectURL(
  9984. new Blob([
  9985. `self.onmessage = function(e) {
  9986. const timeout = e.data;
  9987. setTimeout(() => {
  9988. self.postMessage(1);
  9989. }, timeout);
  9990. };`,
  9991. ])
  9992. )
  9993. );
  9994. }
  9995.  
  9996. async start(endTime = Date.now() + 6e4, maxCount = 100) {
  9997. this.endTime = endTime;
  9998. this.maxCount = maxCount;
  9999. this.init();
  10000. return await new Promise((resolve) => {
  10001. this.resolve = resolve;
  10002. this.count = 0;
  10003. this.loop();
  10004. });
  10005. }
  10006.  
  10007. endFix() {
  10008. this.bestResult.maxCount = this.count;
  10009. this.worker.terminate();
  10010. this.resolve(this.bestResult);
  10011. }
  10012.  
  10013. async loop() {
  10014. const start = Date.now();
  10015. if (this.isEndLoop()) {
  10016. this.endFix();
  10017. return;
  10018. }
  10019. this.count++;
  10020. try {
  10021. this.lastResult = await Calc(this.battle);
  10022. } catch (e) {
  10023. this.updateProgressTimer(this.index++);
  10024. this.timeout(this.loop.bind(this), 0);
  10025. return;
  10026. }
  10027. const { progress, result } = this.lastResult;
  10028. this.lastBattleResult = result;
  10029. this.lastBattleProgress = progress;
  10030. this.setAvgTime(start);
  10031. this.checkResult();
  10032. this.showResult();
  10033. this.updateProgressTimer();
  10034. this.timeout(this.loop.bind(this), 0);
  10035. }
  10036.  
  10037. isEndLoop() {
  10038. return this.count >= this.maxCount || this.endTime < Date.now();
  10039. }
  10040.  
  10041. updateProgressTimer(index = 0) {
  10042. this.lastTimer = this.randTimer();
  10043. this.battle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', index, this.lastTimer] } }];
  10044. }
  10045.  
  10046. showResult() {
  10047. console.log(
  10048. this.count,
  10049. this.avgTime.toFixed(2),
  10050. (this.endTime - Date.now()) / 1000,
  10051. this.lastTimer.toFixed(2),
  10052. this.lastBossDamage.toLocaleString(),
  10053. this.bestResult.value.toLocaleString()
  10054. );
  10055. }
  10056.  
  10057. checkResult() {
  10058. const { damageTaken, damageTakenNextLevel } = this.lastBattleProgress[0].defenders.heroes[1].extra;
  10059. this.lastBossDamage = damageTaken + damageTakenNextLevel;
  10060. if (this.lastBossDamage > this.bestResult.value) {
  10061. this.bestResult = {
  10062. count: this.count,
  10063. timer: this.lastTimer,
  10064. value: this.lastBossDamage,
  10065. result: structuredClone(this.lastBattleResult),
  10066. progress: structuredClone(this.lastBattleProgress),
  10067. };
  10068. }
  10069. }
  10070.  
  10071. stopFix() {
  10072. this.endTime = 0;
  10073. }
  10074. }
  10075.  
  10076. this.HWHClasses.FixBattle = FixBattle;
  10077.  
  10078. class WinFixBattle extends FixBattle {
  10079. checkResult() {
  10080. if (this.lastBattleResult.win) {
  10081. this.bestResult = {
  10082. count: this.count,
  10083. timer: this.lastTimer,
  10084. value: this.lastBattleResult.stars,
  10085. result: structuredClone(this.lastBattleResult),
  10086. progress: structuredClone(this.lastBattleProgress),
  10087. battleTimer: this.lastResult.battleTimer,
  10088. };
  10089. }
  10090. }
  10091.  
  10092. setWinTimer(value) {
  10093. this.winTimer = value;
  10094. }
  10095.  
  10096. setMaxTimer(value) {
  10097. this.maxTimer = value;
  10098. }
  10099.  
  10100. randTimer() {
  10101. if (this.winTimer) {
  10102. return this.winTimer;
  10103. }
  10104. return super.randTimer();
  10105. }
  10106.  
  10107. isEndLoop() {
  10108. return super.isEndLoop() || this.bestResult.result?.win;
  10109. }
  10110.  
  10111. showResult() {
  10112. console.log(
  10113. this.count,
  10114. this.avgTime.toFixed(2),
  10115. (this.endTime - Date.now()) / 1000,
  10116. this.lastResult.battleTime,
  10117. this.lastTimer,
  10118. this.bestResult.value
  10119. );
  10120. const endTime = ((this.endTime - Date.now()) / 1000).toFixed(2);
  10121. const avgTime = this.avgTime.toFixed(2);
  10122. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${endTime}s<br/>${avgTime}ms`;
  10123. setProgress(msg, false, this.stopFix.bind(this));
  10124. }
  10125. }
  10126.  
  10127. this.HWHClasses.WinFixBattle = WinFixBattle;
  10128.  
  10129. class BestOrWinFixBattle extends WinFixBattle {
  10130. isNoMakeWin = false;
  10131.  
  10132. getState(result) {
  10133. let beforeSumFactor = 0;
  10134. const beforeHeroes = result.battleData.defenders[0];
  10135. for (let heroId in beforeHeroes) {
  10136. const hero = beforeHeroes[heroId];
  10137. const state = hero.state;
  10138. let factor = 1;
  10139. if (state) {
  10140. const hp = state.hp / (hero?.hp || 1);
  10141. const energy = state.energy / 1e3;
  10142. factor = hp + energy / 20;
  10143. }
  10144. beforeSumFactor += factor;
  10145. }
  10146.  
  10147. let afterSumFactor = 0;
  10148. const afterHeroes = result.progress[0].defenders.heroes;
  10149. for (let heroId in afterHeroes) {
  10150. const hero = afterHeroes[heroId];
  10151. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10152. const energy = hero.energy / 1e3;
  10153. const factor = hp + energy / 20;
  10154. afterSumFactor += factor;
  10155. }
  10156. return 100 - Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10157. }
  10158.  
  10159. setNoMakeWin(value) {
  10160. this.isNoMakeWin = value;
  10161. }
  10162.  
  10163. checkResult() {
  10164. const state = this.getState(this.lastResult);
  10165. console.log(state);
  10166.  
  10167. if (state > this.bestResult.value) {
  10168. if (!(this.isNoMakeWin && this.lastBattleResult.win)) {
  10169. this.bestResult = {
  10170. count: this.count,
  10171. timer: this.lastTimer,
  10172. value: state,
  10173. result: structuredClone(this.lastBattleResult),
  10174. progress: structuredClone(this.lastBattleProgress),
  10175. battleTimer: this.lastResult.battleTimer,
  10176. };
  10177. }
  10178. }
  10179. }
  10180. }
  10181.  
  10182. this.HWHClasses.BestOrWinFixBattle = BestOrWinFixBattle;
  10183.  
  10184. class BossFixBattle extends FixBattle {
  10185. showResult() {
  10186. super.showResult();
  10187. //setTimeout(() => {
  10188. const best = this.bestResult;
  10189. const maxDmg = best.value.toLocaleString();
  10190. const avgTime = this.avgTime.toLocaleString();
  10191. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${maxDmg}<br/>${avgTime}ms`;
  10192. setProgress(msg, false, this.stopFix.bind(this));
  10193. //}, 0);
  10194. }
  10195. }
  10196.  
  10197. this.HWHClasses.BossFixBattle = BossFixBattle;
  10198.  
  10199. class DungeonFixBattle extends FixBattle {
  10200. init() {
  10201. super.init();
  10202. this.isTimeout = false;
  10203. }
  10204.  
  10205. setState() {
  10206. const result = this.lastResult;
  10207. let beforeSumFactor = 0;
  10208. const beforeHeroes = result.battleData.attackers;
  10209. for (let heroId in beforeHeroes) {
  10210. const hero = beforeHeroes[heroId];
  10211. const state = hero.state;
  10212. let factor = 1;
  10213. if (state) {
  10214. const hp = state.hp / (hero?.hp || 1);
  10215. const energy = state.energy / 1e3;
  10216. factor = hp + energy / 20;
  10217. }
  10218. beforeSumFactor += factor;
  10219. }
  10220.  
  10221. let afterSumFactor = 0;
  10222. const afterHeroes = result.progress[0].attackers.heroes;
  10223. for (let heroId in afterHeroes) {
  10224. const hero = afterHeroes[heroId];
  10225. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10226. const energy = hero.energy / 1e3;
  10227. const factor = hp + energy / 20;
  10228. afterSumFactor += factor;
  10229. }
  10230. this.lastState = Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10231. }
  10232.  
  10233. checkResult() {
  10234. this.setState();
  10235. if (this.lastResult.result.win && this.lastState > this.bestResult.value) {
  10236. this.bestResult = {
  10237. count: this.count,
  10238. timer: this.lastTimer,
  10239. value: this.lastState,
  10240. result: this.lastResult.result,
  10241. progress: this.lastResult.progress,
  10242. };
  10243. }
  10244. }
  10245.  
  10246. showResult() {
  10247. console.log(
  10248. this.count,
  10249. this.avgTime.toFixed(2),
  10250. (this.endTime - Date.now()) / 1000,
  10251. this.lastTimer.toFixed(2),
  10252. this.lastState.toLocaleString(),
  10253. this.bestResult.value.toLocaleString()
  10254. );
  10255. }
  10256. }
  10257.  
  10258. this.HWHClasses.DungeonFixBattle = DungeonFixBattle;
  10259.  
  10260. const masterWsMixin = {
  10261. wsStart() {
  10262. const socket = new WebSocket(this.url);
  10263.  
  10264. socket.onopen = () => {
  10265. console.log('Connected to server');
  10266.  
  10267. // Пример создания новой задачи
  10268. const newTask = {
  10269. type: 'newTask',
  10270. battle: this.battle,
  10271. endTime: this.endTime - 1e4,
  10272. maxCount: this.maxCount,
  10273. };
  10274. socket.send(JSON.stringify(newTask));
  10275. };
  10276.  
  10277. socket.onmessage = this.onmessage.bind(this);
  10278.  
  10279. socket.onclose = () => {
  10280. console.log('Disconnected from server');
  10281. };
  10282.  
  10283. this.ws = socket;
  10284. },
  10285.  
  10286. onmessage(event) {
  10287. const data = JSON.parse(event.data);
  10288. switch (data.type) {
  10289. case 'newTask': {
  10290. console.log('newTask:', data);
  10291. this.id = data.id;
  10292. this.countExecutor = data.count;
  10293. break;
  10294. }
  10295. case 'getSolTask': {
  10296. console.log('getSolTask:', data);
  10297. this.endFix(data.solutions);
  10298. break;
  10299. }
  10300. case 'resolveTask': {
  10301. console.log('resolveTask:', data);
  10302. if (data.id === this.id && data.solutions.length === this.countExecutor) {
  10303. this.worker.terminate();
  10304. this.endFix(data.solutions);
  10305. }
  10306. break;
  10307. }
  10308. default:
  10309. console.log('Unknown message type:', data.type);
  10310. }
  10311. },
  10312.  
  10313. getTask() {
  10314. this.ws.send(
  10315. JSON.stringify({
  10316. type: 'getSolTask',
  10317. id: this.id,
  10318. })
  10319. );
  10320. },
  10321. };
  10322.  
  10323. /*
  10324. mFix = new action.masterFixBattle(battle)
  10325. await mFix.start(Date.now() + 6e4, 1);
  10326. */
  10327. class masterFixBattle extends FixBattle {
  10328. constructor(battle, url = 'wss://localho.st:3000') {
  10329. super(battle, true);
  10330. this.url = url;
  10331. }
  10332.  
  10333. async start(endTime, maxCount) {
  10334. this.endTime = endTime;
  10335. this.maxCount = maxCount;
  10336. this.init();
  10337. this.wsStart();
  10338. return await new Promise((resolve) => {
  10339. this.resolve = resolve;
  10340. const timeout = this.endTime - Date.now();
  10341. this.timeout(this.getTask.bind(this), timeout);
  10342. });
  10343. }
  10344.  
  10345. async endFix(solutions) {
  10346. this.ws.close();
  10347. let maxCount = 0;
  10348. for (const solution of solutions) {
  10349. maxCount += solution.maxCount;
  10350. if (solution.value > this.bestResult.value) {
  10351. this.bestResult = solution;
  10352. }
  10353. }
  10354. this.count = maxCount;
  10355. super.endFix();
  10356. }
  10357. }
  10358.  
  10359. Object.assign(masterFixBattle.prototype, masterWsMixin);
  10360.  
  10361. this.HWHClasses.masterFixBattle = masterFixBattle;
  10362.  
  10363. class masterWinFixBattle extends WinFixBattle {
  10364. constructor(battle, url = 'wss://localho.st:3000') {
  10365. super(battle, true);
  10366. this.url = url;
  10367. }
  10368.  
  10369. async start(endTime, maxCount) {
  10370. this.endTime = endTime;
  10371. this.maxCount = maxCount;
  10372. this.init();
  10373. this.wsStart();
  10374. return await new Promise((resolve) => {
  10375. this.resolve = resolve;
  10376. const timeout = this.endTime - Date.now();
  10377. this.timeout(this.getTask.bind(this), timeout);
  10378. });
  10379. }
  10380.  
  10381. async endFix(solutions) {
  10382. this.ws.close();
  10383. let maxCount = 0;
  10384. for (const solution of solutions) {
  10385. maxCount += solution.maxCount;
  10386. if (solution.value > this.bestResult.value) {
  10387. this.bestResult = solution;
  10388. }
  10389. }
  10390. this.count = maxCount;
  10391. super.endFix();
  10392. }
  10393. }
  10394.  
  10395. Object.assign(masterWinFixBattle.prototype, masterWsMixin);
  10396.  
  10397. this.HWHClasses.masterWinFixBattle = masterWinFixBattle;
  10398.  
  10399. const slaveWsMixin = {
  10400. wsStop() {
  10401. this.ws.close();
  10402. },
  10403.  
  10404. wsStart() {
  10405. const socket = new WebSocket(this.url);
  10406.  
  10407. socket.onopen = () => {
  10408. console.log('Connected to server');
  10409. };
  10410. socket.onmessage = this.onmessage.bind(this);
  10411. socket.onclose = () => {
  10412. console.log('Disconnected from server');
  10413. };
  10414.  
  10415. this.ws = socket;
  10416. },
  10417.  
  10418. async onmessage(event) {
  10419. const data = JSON.parse(event.data);
  10420. switch (data.type) {
  10421. case 'newTask': {
  10422. console.log('newTask:', data.task);
  10423. const { battle, endTime, maxCount } = data.task;
  10424. this.battle = battle;
  10425. const id = data.task.id;
  10426. const solution = await this.start(endTime, maxCount);
  10427. this.ws.send(
  10428. JSON.stringify({
  10429. type: 'resolveTask',
  10430. id,
  10431. solution,
  10432. })
  10433. );
  10434. break;
  10435. }
  10436. default:
  10437. console.log('Unknown message type:', data.type);
  10438. }
  10439. },
  10440. };
  10441. /*
  10442. sFix = new action.slaveFixBattle();
  10443. sFix.wsStart()
  10444. */
  10445. class slaveFixBattle extends FixBattle {
  10446. constructor(url = 'wss://localho.st:3000') {
  10447. super(null, false);
  10448. this.isTimeout = false;
  10449. this.url = url;
  10450. }
  10451. }
  10452.  
  10453. Object.assign(slaveFixBattle.prototype, slaveWsMixin);
  10454.  
  10455. this.HWHClasses.slaveFixBattle = slaveFixBattle;
  10456.  
  10457. class slaveWinFixBattle extends WinFixBattle {
  10458. constructor(url = 'wss://localho.st:3000') {
  10459. super(null, false);
  10460. this.isTimeout = false;
  10461. this.url = url;
  10462. }
  10463. }
  10464.  
  10465. Object.assign(slaveWinFixBattle.prototype, slaveWsMixin);
  10466.  
  10467. this.HWHClasses.slaveWinFixBattle = slaveWinFixBattle;
  10468. /**
  10469. * Auto-repeat attack
  10470. *
  10471. * Автоповтор атаки
  10472. */
  10473. function testAutoBattle() {
  10474. const { executeAutoBattle } = HWHClasses;
  10475. return new Promise((resolve, reject) => {
  10476. const bossBattle = new executeAutoBattle(resolve, reject);
  10477. bossBattle.start(lastBattleArg, lastBattleInfo);
  10478. });
  10479. }
  10480.  
  10481. /**
  10482. * Auto-repeat attack
  10483. *
  10484. * Автоповтор атаки
  10485. */
  10486. function executeAutoBattle(resolve, reject) {
  10487. let battleArg = {};
  10488. let countBattle = 0;
  10489. let countError = 0;
  10490. let findCoeff = 0;
  10491. let dataNotEeceived = 0;
  10492. let stopAutoBattle = false;
  10493.  
  10494. let isSetWinTimer = false;
  10495. const svgJustice = '<svg width="20" height="20" viewBox="0 0 124 125" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m54 0h-1c-7.25 6.05-17.17 6.97-25.78 10.22-8.6 3.25-23.68 1.07-23.22 12.78s-0.47 24.08 1 35 2.36 18.36 7 28c4.43-8.31-3.26-18.88-3-30 0.26-11.11-2.26-25.29-1-37 11.88-4.16 26.27-0.42 36.77-9.23s20.53 6.05 29.23-0.77c-6.65-2.98-14.08-4.96-20-9z"/></g><g><path d="m108 5c-11.05 2.96-27.82 2.2-35.08 11.92s-14.91 14.71-22.67 23.33c-7.77 8.62-14.61 15.22-22.25 23.75 7.05 11.93 14.33 2.58 20.75-4.25 6.42-6.82 12.98-13.03 19.5-19.5s12.34-13.58 19.75-18.25c2.92 7.29-8.32 12.65-13.25 18.75-4.93 6.11-12.19 11.48-17.5 17.5s-12.31 11.38-17.25 17.75c10.34 14.49 17.06-3.04 26.77-10.23s15.98-16.89 26.48-24.52c10.5-7.64 12.09-24.46 14.75-36.25z"/></g><g><path d="m60 25c-11.52-6.74-24.53 8.28-38 6 0.84 9.61-1.96 20.2 2 29 5.53-4.04-4.15-23.2 4.33-26.67 8.48-3.48 18.14-1.1 24.67-8.33 2.73 0.3 4.81 2.98 7 0z"/></g><g><path d="m100 75c3.84-11.28 5.62-25.85 3-38-4.2 5.12-3.5 13.58-4 20s-3.52 13.18 1 18z"/></g><g><path d="m55 94c15.66-5.61 33.71-20.85 29-39-3.07 8.05-4.3 16.83-10.75 23.25s-14.76 8.35-18.25 15.75z"/></g><g><path d="m0 94v7c6.05 3.66 9.48 13.3 18 11-3.54-11.78 8.07-17.05 14-25 6.66 1.52 13.43 16.26 19 5-11.12-9.62-20.84-21.33-32-31-9.35 6.63 4.76 11.99 6 19-7.88 5.84-13.24 17.59-25 14z"/></g><g><path d="m82 125h26v-19h16v-1c-11.21-8.32-18.38-21.74-30-29-8.59 10.26-19.05 19.27-27 30h15v19z"/></g><g><path d="m68 110c-7.68-1.45-15.22 4.83-21.92-1.08s-11.94-5.72-18.08-11.92c-3.03 8.84 10.66 9.88 16.92 16.08s17.09 3.47 23.08-3.08z"/></g></svg>';
  10496. const svgBoss = '<svg width="20" height="20" viewBox="0 0 40 41" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m21 12c-2.19-3.23 5.54-10.95-0.97-10.97-6.52-0.02 1.07 7.75-1.03 10.97-2.81 0.28-5.49-0.2-8-1-0.68 3.53 0.55 6.06 4 4 0.65 7.03 1.11 10.95 1.67 18.33 0.57 7.38 6.13 7.2 6.55-0.11 0.42-7.3 1.35-11.22 1.78-18.22 3.53 1.9 4.73-0.42 4-4-2.61 0.73-5.14 1.35-8 1m-1 17c-1.59-3.6-1.71-10.47 0-14 1.59 3.6 1.71 10.47 0 14z"/></g><g><path d="m6 19c-1.24-4.15 2.69-8.87 1-12-3.67 4.93-6.52 10.57-6 17 5.64-0.15 8.82 4.98 13 8 1.3-6.54-0.67-12.84-8-13z"/></g><g><path d="m33 7c0.38 5.57 2.86 14.79-7 15v10c4.13-2.88 7.55-7.97 13-8 0.48-6.46-2.29-12.06-6-17z"/></g></svg>';
  10497. const svgAttempt = '<svg width="20" height="20" viewBox="0 0 645 645" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m442 26c-8.8 5.43-6.6 21.6-12.01 30.99-2.5 11.49-5.75 22.74-8.99 34.01-40.61-17.87-92.26-15.55-133.32-0.32-72.48 27.31-121.88 100.19-142.68 171.32 10.95-4.49 19.28-14.97 29.3-21.7 50.76-37.03 121.21-79.04 183.47-44.07 16.68 5.8 2.57 21.22-0.84 31.7-4.14 12.19-11.44 23.41-13.93 36.07 56.01-17.98 110.53-41.23 166-61-20.49-59.54-46.13-117.58-67-177z"/></g><g><path d="m563 547c23.89-16.34 36.1-45.65 47.68-71.32 23.57-62.18 7.55-133.48-28.38-186.98-15.1-22.67-31.75-47.63-54.3-63.7 1.15 14.03 6.71 26.8 8.22 40.78 12.08 61.99 15.82 148.76-48.15 183.29-10.46-0.54-15.99-16.1-24.32-22.82-8.2-7.58-14.24-19.47-23.75-24.25-4.88 59.04-11.18 117.71-15 177 62.9 5.42 126.11 9.6 189 15-4.84-9.83-17.31-15.4-24.77-24.23-9.02-7.06-17.8-15.13-26.23-22.77z"/></g><g><path d="m276 412c-10.69-15.84-30.13-25.9-43.77-40.23-15.39-12.46-30.17-25.94-45.48-38.52-15.82-11.86-29.44-28.88-46.75-37.25-19.07 24.63-39.96 48.68-60.25 72.75-18.71 24.89-42.41 47.33-58.75 73.25 22.4-2.87 44.99-13.6 66.67-13.67 0.06 22.8 10.69 42.82 20.41 62.59 49.09 93.66 166.6 114.55 261.92 96.08-6.07-9.2-22.11-9.75-31.92-16.08-59.45-26.79-138.88-75.54-127.08-151.92 21.66-2.39 43.42-4.37 65-7z"/></g></svg>';
  10498.  
  10499. this.start = function (battleArgs, battleInfo) {
  10500. battleArg = battleArgs;
  10501. if (nameFuncStartBattle == 'invasion_bossStart') {
  10502. startBattle();
  10503. return;
  10504. }
  10505. preCalcBattle(battleInfo);
  10506. }
  10507. /**
  10508. * Returns a promise for combat recalculation
  10509. *
  10510. * Возвращает промис для прерасчета боя
  10511. */
  10512. function getBattleInfo(battle) {
  10513. return new Promise(function (resolve) {
  10514. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10515. Calc(battle).then(e => {
  10516. e.coeff = calcCoeff(e, 'defenders');
  10517. resolve(e);
  10518. });
  10519. });
  10520. }
  10521. /**
  10522. * Battle recalculation
  10523. *
  10524. * Прерасчет боя
  10525. */
  10526. function preCalcBattle(battle) {
  10527. let actions = [];
  10528. const countTestBattle = getInput('countTestBattle');
  10529. for (let i = 0; i < countTestBattle; i++) {
  10530. actions.push(getBattleInfo(battle));
  10531. }
  10532. Promise.all(actions)
  10533. .then(resultPreCalcBattle);
  10534. }
  10535. /**
  10536. * Processing the results of the battle recalculation
  10537. *
  10538. * Обработка результатов прерасчета боя
  10539. */
  10540. async function resultPreCalcBattle(results) {
  10541. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  10542. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  10543. if (countWin > 0) {
  10544. setIsCancalBattle(false);
  10545. startBattle();
  10546. return;
  10547. }
  10548.  
  10549. let minCoeff = 100;
  10550. let maxCoeff = -100;
  10551. let avgCoeff = 0;
  10552. results.forEach(e => {
  10553. if (e.coeff < minCoeff) minCoeff = e.coeff;
  10554. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  10555. avgCoeff += e.coeff;
  10556. });
  10557. avgCoeff /= results.length;
  10558.  
  10559. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10560. nameFuncStartBattle == 'bossAttack') {
  10561. const result = await popup.confirm(
  10562. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  10563. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  10564. { msg: I18N('BTN_DO_IT'), result: true },
  10565. ])
  10566. if (result) {
  10567. setIsCancalBattle(false);
  10568. startBattle();
  10569. return;
  10570. }
  10571. setProgress(I18N('NOT_THIS_TIME'), true);
  10572. endAutoBattle('invasion_bossStart');
  10573. return;
  10574. }
  10575.  
  10576. const result = await popup.confirm(
  10577. I18N('VICTORY_IMPOSSIBLE') +
  10578. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  10579. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  10580. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  10581. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  10582. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  10583. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  10584. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  10585. ])
  10586. if (result) {
  10587. findCoeff = result;
  10588. setIsCancalBattle(false);
  10589. startBattle();
  10590. return;
  10591. }
  10592. setProgress(I18N('NOT_THIS_TIME'), true);
  10593. endAutoBattle(I18N('NOT_THIS_TIME'));
  10594. }
  10595.  
  10596. /**
  10597. * Calculation of the combat result coefficient
  10598. *
  10599. * Расчет коэфициента результата боя
  10600. */
  10601. function calcCoeff(result, packType) {
  10602. let beforeSumFactor = 0;
  10603. const beforePack = result.battleData[packType][0];
  10604. for (let heroId in beforePack) {
  10605. const hero = beforePack[heroId];
  10606. const state = hero.state;
  10607. let factor = 1;
  10608. if (state) {
  10609. const hp = state.hp / state.maxHp;
  10610. const energy = state.energy / 1e3;
  10611. factor = hp + energy / 20;
  10612. }
  10613. beforeSumFactor += factor;
  10614. }
  10615.  
  10616. let afterSumFactor = 0;
  10617. const afterPack = result.progress[0][packType].heroes;
  10618. for (let heroId in afterPack) {
  10619. const hero = afterPack[heroId];
  10620. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  10621. const hp = hero.hp / stateHp;
  10622. const energy = hero.energy / 1e3;
  10623. const factor = hp + energy / 20;
  10624. afterSumFactor += factor;
  10625. }
  10626. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  10627. return Math.round(resultCoeff * 1000) / 1000;
  10628. }
  10629. /**
  10630. * Start battle
  10631. *
  10632. * Начало боя
  10633. */
  10634. function startBattle() {
  10635. countBattle++;
  10636. const countMaxBattle = getInput('countAutoBattle');
  10637. // setProgress(countBattle + '/' + countMaxBattle);
  10638. if (countBattle > countMaxBattle) {
  10639. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  10640. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  10641. return;
  10642. }
  10643. if (stopAutoBattle) {
  10644. setProgress(I18N('STOPPED'), true);
  10645. endAutoBattle('STOPPED');
  10646. return;
  10647. }
  10648. send({calls: [{
  10649. name: nameFuncStartBattle,
  10650. args: battleArg,
  10651. ident: "body"
  10652. }]}, calcResultBattle);
  10653. }
  10654. /**
  10655. * Battle calculation
  10656. *
  10657. * Расчет боя
  10658. */
  10659. async function calcResultBattle(e) {
  10660. if (!e) {
  10661. console.log('данные не были получены');
  10662. if (dataNotEeceived < 10) {
  10663. dataNotEeceived++;
  10664. startBattle();
  10665. return;
  10666. }
  10667. endAutoBattle('Error', 'данные не были получены ' + dataNotEeceived + ' раз');
  10668. return;
  10669. }
  10670. if ('error' in e) {
  10671. if (e.error.description === 'too many tries') {
  10672. invasionTimer += 100;
  10673. countBattle--;
  10674. countError++;
  10675. console.log(`Errors: ${countError}`, e.error);
  10676. startBattle();
  10677. return;
  10678. }
  10679. const result = await popup.confirm(I18N('ERROR_DURING_THE_BATTLE') + '<br>' + e.error.description, [
  10680. { msg: I18N('BTN_OK'), result: false },
  10681. { msg: I18N('RELOAD_GAME'), result: true },
  10682. ]);
  10683. endAutoBattle('Error', e.error);
  10684. if (result) {
  10685. location.reload();
  10686. }
  10687. return;
  10688. }
  10689. let battle = e.results[0].result.response.battle
  10690. if (nameFuncStartBattle == 'towerStartBattle' ||
  10691. nameFuncStartBattle == 'bossAttack' ||
  10692. nameFuncStartBattle == 'invasion_bossStart') {
  10693. battle = e.results[0].result.response;
  10694. }
  10695. lastBattleInfo = battle;
  10696. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  10697. }
  10698. /**
  10699. * Processing the results of the battle
  10700. *
  10701. * Обработка результатов боя
  10702. */
  10703. async function resultBattle(e) {
  10704. const isWin = e.result.win;
  10705. if (isWin) {
  10706. endBattle(e, false);
  10707. return;
  10708. } else if (isChecked('tryFixIt_v2')) {
  10709. const { WinFixBattle } = HWHClasses;
  10710. const cloneBattle = structuredClone(e.battleData);
  10711. const bFix = new WinFixBattle(cloneBattle);
  10712. let attempts = Infinity;
  10713. if (nameFuncStartBattle == 'invasion_bossStart' && !isSetWinTimer) {
  10714. let winTimer = await popup.confirm(`Secret number:`, [
  10715. { result: false, isClose: true },
  10716. { msg: 'Go', isInput: true, default: '0' },
  10717. ]);
  10718. winTimer = Number.parseFloat(winTimer);
  10719. if (winTimer) {
  10720. attempts = 5;
  10721. bFix.setWinTimer(winTimer);
  10722. }
  10723. isSetWinTimer = true;
  10724. }
  10725. let endTime = Date.now() + 6e4;
  10726. if (nameFuncStartBattle == 'invasion_bossStart') {
  10727. endTime = Date.now() + 6e4 * 4;
  10728. bFix.setMaxTimer(120.3);
  10729. }
  10730. const result = await bFix.start(endTime, attempts);
  10731. console.log(result);
  10732. if (result.value) {
  10733. endBattle(result, false);
  10734. return;
  10735. }
  10736. }
  10737. const countMaxBattle = getInput('countAutoBattle');
  10738. if (findCoeff) {
  10739. const coeff = calcCoeff(e, 'defenders');
  10740. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  10741. if (coeff > findCoeff) {
  10742. endBattle(e, false);
  10743. return;
  10744. }
  10745. } else {
  10746. if (nameFuncStartBattle == 'invasion_bossStart') {
  10747. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10748. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10749. setProgress(`${svgBoss} ${bossLvl} ${svgJustice} ${justice} <br>${svgAttempt} ${countBattle}/${countMaxBattle}`, false, () => {
  10750. stopAutoBattle = true;
  10751. });
  10752. await new Promise((resolve) => setTimeout(resolve, 5000));
  10753. } else {
  10754. setProgress(`${countBattle}/${countMaxBattle}`);
  10755. }
  10756. }
  10757. if (nameFuncStartBattle == 'towerStartBattle' ||
  10758. nameFuncStartBattle == 'bossAttack' ||
  10759. nameFuncStartBattle == 'invasion_bossStart') {
  10760. startBattle();
  10761. return;
  10762. }
  10763. cancelEndBattle(e);
  10764. }
  10765. /**
  10766. * Cancel fight
  10767. *
  10768. * Отмена боя
  10769. */
  10770. function cancelEndBattle(r) {
  10771. const fixBattle = function (heroes) {
  10772. for (const ids in heroes) {
  10773. hero = heroes[ids];
  10774. hero.energy = random(1, 999);
  10775. if (hero.hp > 0) {
  10776. hero.hp = random(1, hero.hp);
  10777. }
  10778. }
  10779. }
  10780. fixBattle(r.progress[0].attackers.heroes);
  10781. fixBattle(r.progress[0].defenders.heroes);
  10782. endBattle(r, true);
  10783. }
  10784. /**
  10785. * End of the fight
  10786. *
  10787. * Завершение боя */
  10788. function endBattle(battleResult, isCancal) {
  10789. let calls = [{
  10790. name: nameFuncEndBattle,
  10791. args: {
  10792. result: battleResult.result,
  10793. progress: battleResult.progress
  10794. },
  10795. ident: "body"
  10796. }];
  10797.  
  10798. if (nameFuncStartBattle == 'invasion_bossStart') {
  10799. calls[0].args.id = lastBattleArg.id;
  10800. }
  10801.  
  10802. send(JSON.stringify({
  10803. calls
  10804. }), async e => {
  10805. console.log(e);
  10806. if (isCancal) {
  10807. startBattle();
  10808. return;
  10809. }
  10810.  
  10811. setProgress(`${I18N('SUCCESS')}!`, 5000)
  10812. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10813. nameFuncStartBattle == 'bossAttack') {
  10814. const countMaxBattle = getInput('countAutoBattle');
  10815. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10816. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10817. let winTimer = '';
  10818. if (nameFuncStartBattle == 'invasion_bossStart') {
  10819. winTimer = '<br>Secret number: ' + battleResult.progress[0].attackers.input[5];
  10820. }
  10821. const result = await popup.confirm(
  10822. I18N('BOSS_HAS_BEEN_DEF_TEXT', {
  10823. bossLvl: `${svgBoss} ${bossLvl} ${svgJustice} ${justice}`,
  10824. countBattle: svgAttempt + ' ' + countBattle,
  10825. countMaxBattle,
  10826. winTimer,
  10827. }),
  10828. [
  10829. { msg: I18N('BTN_OK'), result: 0 },
  10830. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  10831. { msg: I18N('RELOAD_GAME'), result: 2 },
  10832. ]
  10833. );
  10834. if (result) {
  10835. if (result == 1) {
  10836. cheats.refreshGame();
  10837. }
  10838. if (result == 2) {
  10839. location.reload();
  10840. }
  10841. }
  10842.  
  10843. }
  10844. endAutoBattle(`${I18N('SUCCESS')}!`)
  10845. });
  10846. }
  10847. /**
  10848. * Completing a task
  10849. *
  10850. * Завершение задачи
  10851. */
  10852. function endAutoBattle(reason, info) {
  10853. setIsCancalBattle(true);
  10854. console.log(reason, info);
  10855. resolve();
  10856. }
  10857. }
  10858.  
  10859. this.HWHClasses.executeAutoBattle = executeAutoBattle;
  10860.  
  10861. function testDailyQuests() {
  10862. const { dailyQuests } = HWHClasses;
  10863. return new Promise((resolve, reject) => {
  10864. const quests = new dailyQuests(resolve, reject);
  10865. quests.init(questsInfo);
  10866. quests.start();
  10867. });
  10868. }
  10869.  
  10870. /**
  10871. * Automatic completion of daily quests
  10872. *
  10873. * Автоматическое выполнение ежедневных квестов
  10874. */
  10875. class dailyQuests {
  10876. /**
  10877. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  10878. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10879. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10880. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  10881. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10882. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10883. */
  10884. callsList = ['userGetInfo', 'heroGetAll', 'titanGetAll', 'inventoryGet', 'questGetAll', 'bossGetAll', 'missionGetAll'];
  10885.  
  10886. dataQuests = {
  10887. 10001: {
  10888. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  10889. doItCall: () => {
  10890. const upgradeSkills = this.getUpgradeSkills();
  10891. return upgradeSkills.map(({ heroId, skill }, index) => ({
  10892. name: 'heroUpgradeSkill',
  10893. args: { heroId, skill },
  10894. ident: `heroUpgradeSkill_${index}`,
  10895. }));
  10896. },
  10897. isWeCanDo: () => {
  10898. const upgradeSkills = this.getUpgradeSkills();
  10899. let sumGold = 0;
  10900. for (const skill of upgradeSkills) {
  10901. sumGold += this.skillCost(skill.value);
  10902. if (!skill.heroId) {
  10903. return false;
  10904. }
  10905. }
  10906. return this.questInfo['userGetInfo'].gold > sumGold;
  10907. },
  10908. },
  10909. 10002: {
  10910. description: 'Пройди 10 миссий', // --------------
  10911. isWeCanDo: () => false,
  10912. },
  10913. 10003: {
  10914. description: 'Пройди 3 героические миссии', // ++++++++++++++++
  10915. isWeCanDo: () => {
  10916. const vipPoints = +this.questInfo.userGetInfo.vipPoints;
  10917. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10918. return (vipPoints > 100 || goldTicket) && this.getHeroicMissionId();
  10919. },
  10920. doItCall: () => {
  10921. const selectedMissionId = this.getHeroicMissionId();
  10922. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10923. const vipLevel = Math.max(...lib.data.level.vip.filter(l => l.vipPoints <= +this.questInfo.userGetInfo.vipPoints).map(l => l.level));
  10924. // Возвращаем массив команд для рейда
  10925. if (vipLevel >= 5 || goldTicket) {
  10926. return [{ name: 'missionRaid', args: { id: selectedMissionId, times: 3 }, ident: 'missionRaid_1' }];
  10927. } else {
  10928. return [
  10929. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_1' },
  10930. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_2' },
  10931. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_3' },
  10932. ];
  10933. }
  10934. },
  10935. },
  10936. 10004: {
  10937. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  10938. isWeCanDo: () => false,
  10939. },
  10940. 10006: {
  10941. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  10942. doItCall: () => [
  10943. {
  10944. name: 'refillableAlchemyUse',
  10945. args: { multi: false },
  10946. ident: 'refillableAlchemyUse',
  10947. },
  10948. ],
  10949. isWeCanDo: () => {
  10950. const starMoney = this.questInfo['userGetInfo'].starMoney;
  10951. return starMoney >= 20;
  10952. },
  10953. },
  10954. 10007: {
  10955. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  10956. doItCall: () => [{ name: 'gacha_open', args: { ident: 'heroGacha', free: true, pack: false }, ident: 'gacha_open' }],
  10957. isWeCanDo: () => {
  10958. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  10959. return soulCrystal > 0;
  10960. },
  10961. },
  10962. 10016: {
  10963. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  10964. doItCall: () => [{ name: 'clanSendDailyGifts', args: {}, ident: 'clanSendDailyGifts' }],
  10965. isWeCanDo: () => true,
  10966. },
  10967. 10018: {
  10968. description: 'Используй зелье опыта', // ++++++++++++++++
  10969. doItCall: () => {
  10970. const expHero = this.getExpHero();
  10971. return [
  10972. {
  10973. name: 'consumableUseHeroXp',
  10974. args: {
  10975. heroId: expHero.heroId,
  10976. libId: expHero.libId,
  10977. amount: 1,
  10978. },
  10979. ident: 'consumableUseHeroXp',
  10980. },
  10981. ];
  10982. },
  10983. isWeCanDo: () => {
  10984. const expHero = this.getExpHero();
  10985. return expHero.heroId && expHero.libId;
  10986. },
  10987. },
  10988. 10019: {
  10989. description: 'Открой 1 сундук в Башне',
  10990. doItFunc: testTower,
  10991. isWeCanDo: () => false,
  10992. },
  10993. 10020: {
  10994. description: 'Открой 3 сундука в Запределье', // Готово
  10995. doItCall: () => {
  10996. return this.getOutlandChest();
  10997. },
  10998. isWeCanDo: () => {
  10999. const outlandChest = this.getOutlandChest();
  11000. return outlandChest.length > 0;
  11001. },
  11002. },
  11003. 10021: {
  11004. description: 'Собери 75 Титанита в Подземелье Гильдии',
  11005. isWeCanDo: () => false,
  11006. },
  11007. 10022: {
  11008. description: 'Собери 150 Титанита в Подземелье Гильдии',
  11009. doItFunc: testDungeon,
  11010. isWeCanDo: () => false,
  11011. },
  11012. 10023: {
  11013. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  11014. doItCall: () => {
  11015. const heroId = this.getHeroIdTitanGift();
  11016. return [
  11017. { name: 'heroTitanGiftLevelUp', args: { heroId }, ident: 'heroTitanGiftLevelUp' },
  11018. { name: 'heroTitanGiftDrop', args: { heroId }, ident: 'heroTitanGiftDrop' },
  11019. ];
  11020. },
  11021. isWeCanDo: () => {
  11022. const heroId = this.getHeroIdTitanGift();
  11023. return heroId;
  11024. },
  11025. },
  11026. 10024: {
  11027. description: 'Повысь уровень любого артефакта один раз', // Готово
  11028. doItCall: () => {
  11029. const upArtifact = this.getUpgradeArtifact();
  11030. return [
  11031. {
  11032. name: 'heroArtifactLevelUp',
  11033. args: {
  11034. heroId: upArtifact.heroId,
  11035. slotId: upArtifact.slotId,
  11036. },
  11037. ident: `heroArtifactLevelUp`,
  11038. },
  11039. ];
  11040. },
  11041. isWeCanDo: () => {
  11042. const upgradeArtifact = this.getUpgradeArtifact();
  11043. return upgradeArtifact.heroId;
  11044. },
  11045. },
  11046. 10025: {
  11047. description: 'Начни 1 Экспедицию',
  11048. doItFunc: checkExpedition,
  11049. isWeCanDo: () => false,
  11050. },
  11051. 10026: {
  11052. description: 'Начни 4 Экспедиции', // --------------
  11053. doItFunc: checkExpedition,
  11054. isWeCanDo: () => false,
  11055. },
  11056. 10027: {
  11057. description: 'Победи в 1 бою Турнира Стихий',
  11058. doItFunc: testTitanArena,
  11059. isWeCanDo: () => false,
  11060. },
  11061. 10028: {
  11062. description: 'Повысь уровень любого артефакта титанов', // Готово
  11063. doItCall: () => {
  11064. const upTitanArtifact = this.getUpgradeTitanArtifact();
  11065. return [
  11066. {
  11067. name: 'titanArtifactLevelUp',
  11068. args: {
  11069. titanId: upTitanArtifact.titanId,
  11070. slotId: upTitanArtifact.slotId,
  11071. },
  11072. ident: `titanArtifactLevelUp`,
  11073. },
  11074. ];
  11075. },
  11076. isWeCanDo: () => {
  11077. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  11078. return upgradeTitanArtifact.titanId;
  11079. },
  11080. },
  11081. 10029: {
  11082. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  11083. doItCall: () => [{ name: 'titanArtifactChestOpen', args: { amount: 1, free: true }, ident: 'titanArtifactChestOpen' }],
  11084. isWeCanDo: () => {
  11085. return this.questInfo['inventoryGet']?.consumable[55] > 0;
  11086. },
  11087. },
  11088. 10030: {
  11089. description: 'Улучши облик любого героя 1 раз', // Готово
  11090. doItCall: () => {
  11091. const upSkin = this.getUpgradeSkin();
  11092. return [
  11093. {
  11094. name: 'heroSkinUpgrade',
  11095. args: {
  11096. heroId: upSkin.heroId,
  11097. skinId: upSkin.skinId,
  11098. },
  11099. ident: `heroSkinUpgrade`,
  11100. },
  11101. ];
  11102. },
  11103. isWeCanDo: () => {
  11104. const upgradeSkin = this.getUpgradeSkin();
  11105. return upgradeSkin.heroId;
  11106. },
  11107. },
  11108. 10031: {
  11109. description: 'Победи в 6 боях Турнира Стихий', // --------------
  11110. doItFunc: testTitanArena,
  11111. isWeCanDo: () => false,
  11112. },
  11113. 10043: {
  11114. description: 'Начни или присоеденись к Приключению', // --------------
  11115. isWeCanDo: () => false,
  11116. },
  11117. 10044: {
  11118. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  11119. doItCall: () => [{ name: 'pet_chestOpen', args: { amount: 1, paid: false }, ident: 'pet_chestOpen' }],
  11120. isWeCanDo: () => {
  11121. return this.questInfo['inventoryGet']?.consumable[90] > 0;
  11122. },
  11123. },
  11124. 10046: {
  11125. /**
  11126. * TODO: Watch Adventure
  11127. * TODO: Смотреть приключение
  11128. */
  11129. description: 'Открой 3 сундука в Приключениях',
  11130. isWeCanDo: () => false,
  11131. },
  11132. 10047: {
  11133. description: 'Набери 150 очков активности в Гильдии', // Готово
  11134. doItCall: () => {
  11135. const enchantRune = this.getEnchantRune();
  11136. return [
  11137. {
  11138. name: 'heroEnchantRune',
  11139. args: {
  11140. heroId: enchantRune.heroId,
  11141. tier: enchantRune.tier,
  11142. items: {
  11143. consumable: { [enchantRune.itemId]: 1 },
  11144. },
  11145. },
  11146. ident: `heroEnchantRune`,
  11147. },
  11148. ];
  11149. },
  11150. isWeCanDo: () => {
  11151. const userInfo = this.questInfo['userGetInfo'];
  11152. const enchantRune = this.getEnchantRune();
  11153. return enchantRune.heroId && userInfo.gold > 1e3;
  11154. },
  11155. },
  11156. };
  11157.  
  11158. constructor(resolve, reject, questInfo) {
  11159. this.resolve = resolve;
  11160. this.reject = reject;
  11161. }
  11162.  
  11163. init(questInfo) {
  11164. this.questInfo = questInfo;
  11165. this.isAuto = false;
  11166. }
  11167.  
  11168. async autoInit(isAuto) {
  11169. this.isAuto = isAuto || false;
  11170. const quests = {};
  11171. const calls = this.callsList.map((name) => ({
  11172. name,
  11173. args: {},
  11174. ident: name,
  11175. }));
  11176. const result = await Send(JSON.stringify({ calls })).then((e) => e.results);
  11177. for (const call of result) {
  11178. quests[call.ident] = call.result.response;
  11179. }
  11180. this.questInfo = quests;
  11181. }
  11182.  
  11183. async start() {
  11184. const weCanDo = [];
  11185. const selectedActions = getSaveVal('selectedActions', {});
  11186. for (let quest of this.questInfo['questGetAll']) {
  11187. if (quest.id in this.dataQuests && quest.state == 1) {
  11188. if (!selectedActions[quest.id]) {
  11189. selectedActions[quest.id] = {
  11190. checked: false,
  11191. };
  11192. }
  11193.  
  11194. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  11195. if (!isWeCanDo.call(this)) {
  11196. continue;
  11197. }
  11198.  
  11199. weCanDo.push({
  11200. name: quest.id,
  11201. label: I18N(`QUEST_${quest.id}`),
  11202. checked: selectedActions[quest.id].checked,
  11203. });
  11204. }
  11205. }
  11206.  
  11207. if (!weCanDo.length) {
  11208. this.end(I18N('NOTHING_TO_DO'));
  11209. return;
  11210. }
  11211.  
  11212. console.log(weCanDo);
  11213. let taskList = [];
  11214. if (this.isAuto) {
  11215. taskList = weCanDo;
  11216. } else {
  11217. const answer = await popup.confirm(
  11218. `${I18N('YOU_CAN_COMPLETE')}:`,
  11219. [
  11220. { msg: I18N('BTN_DO_IT'), result: true },
  11221. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11222. ],
  11223. weCanDo
  11224. );
  11225. if (!answer) {
  11226. this.end('');
  11227. return;
  11228. }
  11229. taskList = popup.getCheckBoxes();
  11230. taskList.forEach((e) => {
  11231. selectedActions[e.name].checked = e.checked;
  11232. });
  11233. setSaveVal('selectedActions', selectedActions);
  11234. }
  11235.  
  11236. const calls = [];
  11237. let countChecked = 0;
  11238. for (const task of taskList) {
  11239. if (task.checked) {
  11240. countChecked++;
  11241. const quest = this.dataQuests[task.name];
  11242. console.log(quest.description);
  11243.  
  11244. if (quest.doItCall) {
  11245. const doItCall = quest.doItCall.call(this);
  11246. calls.push(...doItCall);
  11247. }
  11248. }
  11249. }
  11250.  
  11251. if (!countChecked) {
  11252. this.end(I18N('NOT_QUEST_COMPLETED'));
  11253. return;
  11254. }
  11255.  
  11256. const result = await Send(JSON.stringify({ calls }));
  11257. if (result.error) {
  11258. console.error(result.error, result.error.call);
  11259. }
  11260. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  11261. }
  11262.  
  11263. errorHandling(error) {
  11264. //console.error(error);
  11265. let errorInfo = error.toString() + '\n';
  11266. try {
  11267. const errorStack = error.stack.split('\n');
  11268. const endStack = errorStack.map((e) => e.split('@')[0]).indexOf('testDoYourBest');
  11269. errorInfo += errorStack.slice(0, endStack).join('\n');
  11270. } catch (e) {
  11271. errorInfo += error.stack;
  11272. }
  11273. copyText(errorInfo);
  11274. }
  11275.  
  11276. skillCost(lvl) {
  11277. return 573 * lvl ** 0.9 + lvl ** 2.379;
  11278. }
  11279.  
  11280. getUpgradeSkills() {
  11281. const heroes = Object.values(this.questInfo['heroGetAll']);
  11282. const upgradeSkills = [
  11283. { heroId: 0, slotId: 0, value: 130 },
  11284. { heroId: 0, slotId: 0, value: 130 },
  11285. { heroId: 0, slotId: 0, value: 130 },
  11286. ];
  11287. const skillLib = lib.getData('skill');
  11288. /**
  11289. * color - 1 (белый) открывает 1 навык
  11290. * color - 2 (зеленый) открывает 2 навык
  11291. * color - 4 (синий) открывает 3 навык
  11292. * color - 7 (фиолетовый) открывает 4 навык
  11293. */
  11294. const colors = [1, 2, 4, 7];
  11295. for (const hero of heroes) {
  11296. const level = hero.level;
  11297. const color = hero.color;
  11298. for (let skillId in hero.skills) {
  11299. const tier = skillLib[skillId].tier;
  11300. const sVal = hero.skills[skillId];
  11301. if (color < colors[tier] || tier < 1 || tier > 4) {
  11302. continue;
  11303. }
  11304. for (let upSkill of upgradeSkills) {
  11305. if (sVal < upSkill.value && sVal < level) {
  11306. upSkill.value = sVal;
  11307. upSkill.heroId = hero.id;
  11308. upSkill.skill = tier;
  11309. break;
  11310. }
  11311. }
  11312. }
  11313. }
  11314. return upgradeSkills;
  11315. }
  11316.  
  11317. getUpgradeArtifact() {
  11318. const heroes = Object.values(this.questInfo['heroGetAll']);
  11319. const inventory = this.questInfo['inventoryGet'];
  11320. const upArt = { heroId: 0, slotId: 0, level: 100 };
  11321.  
  11322. const heroLib = lib.getData('hero');
  11323. const artifactLib = lib.getData('artifact');
  11324.  
  11325. for (const hero of heroes) {
  11326. const heroInfo = heroLib[hero.id];
  11327. const level = hero.level;
  11328. if (level < 20) {
  11329. continue;
  11330. }
  11331.  
  11332. for (let slotId in hero.artifacts) {
  11333. const art = hero.artifacts[slotId];
  11334. /* Текущая звезданость арта */
  11335. const star = art.star;
  11336. if (!star) {
  11337. continue;
  11338. }
  11339. /* Текущий уровень арта */
  11340. const level = art.level;
  11341. if (level >= 100) {
  11342. continue;
  11343. }
  11344. /* Идентификатор арта в библиотеке */
  11345. const artifactId = heroInfo.artifacts[slotId];
  11346. const artInfo = artifactLib.id[artifactId];
  11347. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  11348.  
  11349. const costCurrency = Object.keys(costNextLevel).pop();
  11350. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11351. const costId = costValues[0];
  11352. const costValue = +costValues[1];
  11353.  
  11354. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11355. if (level < upArt.level && inventory[costCurrency][costId] >= costValue) {
  11356. upArt.level = level;
  11357. upArt.heroId = hero.id;
  11358. upArt.slotId = slotId;
  11359. upArt.costCurrency = costCurrency;
  11360. upArt.costId = costId;
  11361. upArt.costValue = costValue;
  11362. }
  11363. }
  11364. }
  11365. return upArt;
  11366. }
  11367.  
  11368. getUpgradeSkin() {
  11369. const heroes = Object.values(this.questInfo['heroGetAll']);
  11370. const inventory = this.questInfo['inventoryGet'];
  11371. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  11372.  
  11373. const skinLib = lib.getData('skin');
  11374.  
  11375. for (const hero of heroes) {
  11376. const level = hero.level;
  11377. if (level < 20) {
  11378. continue;
  11379. }
  11380.  
  11381. for (let skinId in hero.skins) {
  11382. /* Текущий уровень скина */
  11383. const level = hero.skins[skinId];
  11384. if (level >= 60) {
  11385. continue;
  11386. }
  11387. /* Идентификатор скина в библиотеке */
  11388. const skinInfo = skinLib[skinId];
  11389. if (!skinInfo.statData.levels?.[level + 1]) {
  11390. continue;
  11391. }
  11392. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  11393.  
  11394. const costCurrency = Object.keys(costNextLevel).pop();
  11395. const costCurrencyId = Object.keys(costNextLevel[costCurrency]).pop();
  11396. const costValue = +costNextLevel[costCurrency][costCurrencyId];
  11397.  
  11398. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11399. if (level < upSkin.level && costValue < upSkin.cost && inventory[costCurrency][costCurrencyId] >= costValue) {
  11400. upSkin.cost = costValue;
  11401. upSkin.level = level;
  11402. upSkin.heroId = hero.id;
  11403. upSkin.skinId = skinId;
  11404. upSkin.costCurrency = costCurrency;
  11405. upSkin.costCurrencyId = costCurrencyId;
  11406. }
  11407. }
  11408. }
  11409. return upSkin;
  11410. }
  11411.  
  11412. getUpgradeTitanArtifact() {
  11413. const titans = Object.values(this.questInfo['titanGetAll']);
  11414. const inventory = this.questInfo['inventoryGet'];
  11415. const userInfo = this.questInfo['userGetInfo'];
  11416. const upArt = { titanId: 0, slotId: 0, level: 120 };
  11417.  
  11418. const titanLib = lib.getData('titan');
  11419. const artTitanLib = lib.getData('titanArtifact');
  11420.  
  11421. for (const titan of titans) {
  11422. const titanInfo = titanLib[titan.id];
  11423. // const level = titan.level
  11424. // if (level < 20) {
  11425. // continue;
  11426. // }
  11427.  
  11428. for (let slotId in titan.artifacts) {
  11429. const art = titan.artifacts[slotId];
  11430. /* Текущая звезданость арта */
  11431. const star = art.star;
  11432. if (!star) {
  11433. continue;
  11434. }
  11435. /* Текущий уровень арта */
  11436. const level = art.level;
  11437. if (level >= 120) {
  11438. continue;
  11439. }
  11440. /* Идентификатор арта в библиотеке */
  11441. const artifactId = titanInfo.artifacts[slotId];
  11442. const artInfo = artTitanLib.id[artifactId];
  11443. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  11444.  
  11445. const costCurrency = Object.keys(costNextLevel).pop();
  11446. let costValue = 0;
  11447. let currentValue = 0;
  11448. if (costCurrency == 'gold') {
  11449. costValue = costNextLevel[costCurrency];
  11450. currentValue = userInfo.gold;
  11451. } else {
  11452. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11453. const costId = costValues[0];
  11454. costValue = +costValues[1];
  11455. currentValue = inventory[costCurrency][costId];
  11456. }
  11457.  
  11458. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11459. if (level < upArt.level && currentValue >= costValue) {
  11460. upArt.level = level;
  11461. upArt.titanId = titan.id;
  11462. upArt.slotId = slotId;
  11463. break;
  11464. }
  11465. }
  11466. }
  11467. return upArt;
  11468. }
  11469.  
  11470. getEnchantRune() {
  11471. const heroes = Object.values(this.questInfo['heroGetAll']);
  11472. const inventory = this.questInfo['inventoryGet'];
  11473. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  11474. for (let i = 1; i <= 4; i++) {
  11475. if (inventory.consumable[i] > 0) {
  11476. enchRune.itemId = i;
  11477. break;
  11478. }
  11479. return enchRune;
  11480. }
  11481.  
  11482. const runeLib = lib.getData('rune');
  11483. const runeLvls = Object.values(runeLib.level);
  11484. /**
  11485. * color - 4 (синий) открывает 1 и 2 символ
  11486. * color - 7 (фиолетовый) открывает 3 символ
  11487. * color - 8 (фиолетовый +1) открывает 4 символ
  11488. * color - 9 (фиолетовый +2) открывает 5 символ
  11489. */
  11490. // TODO: кажется надо учесть уровень команды
  11491. const colors = [4, 4, 7, 8, 9];
  11492. for (const hero of heroes) {
  11493. const color = hero.color;
  11494.  
  11495. for (let runeTier in hero.runes) {
  11496. /* Проверка на доступность руны */
  11497. if (color < colors[runeTier]) {
  11498. continue;
  11499. }
  11500. /* Текущий опыт руны */
  11501. const exp = hero.runes[runeTier];
  11502. if (exp >= 43750) {
  11503. continue;
  11504. }
  11505.  
  11506. let level = 0;
  11507. if (exp) {
  11508. for (let lvl of runeLvls) {
  11509. if (exp >= lvl.enchantValue) {
  11510. level = lvl.level;
  11511. } else {
  11512. break;
  11513. }
  11514. }
  11515. }
  11516. /** Уровень героя необходимый для уровня руны */
  11517. const heroLevel = runeLib.level[level].heroLevel;
  11518. if (hero.level < heroLevel) {
  11519. continue;
  11520. }
  11521.  
  11522. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11523. if (exp < enchRune.exp) {
  11524. enchRune.exp = exp;
  11525. enchRune.heroId = hero.id;
  11526. enchRune.tier = runeTier;
  11527. break;
  11528. }
  11529. }
  11530. }
  11531. return enchRune;
  11532. }
  11533.  
  11534. getOutlandChest() {
  11535. const bosses = this.questInfo['bossGetAll'];
  11536.  
  11537. const calls = [];
  11538.  
  11539. for (let boss of bosses) {
  11540. if (boss.mayRaid) {
  11541. calls.push({
  11542. name: 'bossRaid',
  11543. args: {
  11544. bossId: boss.id,
  11545. },
  11546. ident: 'bossRaid_' + boss.id,
  11547. });
  11548. calls.push({
  11549. name: 'bossOpenChest',
  11550. args: {
  11551. bossId: boss.id,
  11552. amount: 1,
  11553. starmoney: 0,
  11554. },
  11555. ident: 'bossOpenChest_' + boss.id,
  11556. });
  11557. } else if (boss.chestId == 1) {
  11558. calls.push({
  11559. name: 'bossOpenChest',
  11560. args: {
  11561. bossId: boss.id,
  11562. amount: 1,
  11563. starmoney: 0,
  11564. },
  11565. ident: 'bossOpenChest_' + boss.id,
  11566. });
  11567. }
  11568. }
  11569.  
  11570. return calls;
  11571. }
  11572.  
  11573. getExpHero() {
  11574. const heroes = Object.values(this.questInfo['heroGetAll']);
  11575. const inventory = this.questInfo['inventoryGet'];
  11576. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  11577. /** зелья опыта (consumable 9, 10, 11, 12) */
  11578. for (let i = 9; i <= 12; i++) {
  11579. if (inventory.consumable[i]) {
  11580. expHero.libId = i;
  11581. break;
  11582. }
  11583. }
  11584.  
  11585. for (const hero of heroes) {
  11586. const exp = hero.xp;
  11587. if (exp < expHero.exp) {
  11588. expHero.heroId = hero.id;
  11589. }
  11590. }
  11591. return expHero;
  11592. }
  11593.  
  11594. getHeroIdTitanGift() {
  11595. const heroes = Object.values(this.questInfo['heroGetAll']);
  11596. const inventory = this.questInfo['inventoryGet'];
  11597. const user = this.questInfo['userGetInfo'];
  11598. const titanGiftLib = lib.getData('titanGift');
  11599. /** Искры */
  11600. const titanGift = inventory.consumable[24];
  11601. let heroId = 0;
  11602. let minLevel = 30;
  11603.  
  11604. if (titanGift < 250 || user.gold < 7000) {
  11605. return 0;
  11606. }
  11607.  
  11608. for (const hero of heroes) {
  11609. if (hero.titanGiftLevel >= 30) {
  11610. continue;
  11611. }
  11612.  
  11613. if (!hero.titanGiftLevel) {
  11614. return hero.id;
  11615. }
  11616.  
  11617. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  11618. if (minLevel > hero.titanGiftLevel && titanGift >= cost.consumable[24] && user.gold >= cost.gold) {
  11619. minLevel = hero.titanGiftLevel;
  11620. heroId = hero.id;
  11621. }
  11622. }
  11623.  
  11624. return heroId;
  11625. }
  11626.  
  11627. getHeroicMissionId() {
  11628. // Получаем доступные миссии с 3 звездами
  11629. const availableMissionsToRaid = Object.values(this.questInfo.missionGetAll)
  11630. .filter((mission) => mission.stars === 3)
  11631. .map((mission) => mission.id);
  11632.  
  11633. // Получаем героев для улучшения, у которых меньше 6 звезд
  11634. const heroesToUpgrade = Object.values(this.questInfo.heroGetAll)
  11635. .filter((hero) => hero.star < 6)
  11636. .sort((a, b) => b.power - a.power)
  11637. .map((hero) => hero.id);
  11638.  
  11639. // Получаем героические миссии, которые доступны для рейдов
  11640. const heroicMissions = Object.values(lib.data.mission).filter((mission) => mission.isHeroic && availableMissionsToRaid.includes(mission.id));
  11641.  
  11642. // Собираем дропы из героических миссий
  11643. const drops = heroicMissions.map((mission) => {
  11644. const lastWave = mission.normalMode.waves[mission.normalMode.waves.length - 1];
  11645. const allRewards = lastWave.enemies[lastWave.enemies.length - 1]
  11646. .drop.map((drop) => drop.reward);
  11647.  
  11648. const heroId = +Object.keys(allRewards.find((reward) => reward.fragmentHero).fragmentHero).pop();
  11649.  
  11650. return { id: mission.id, heroId };
  11651. });
  11652.  
  11653. // Определяем, какие дропы подходят для героев, которых нужно улучшить
  11654. const heroDrops = heroesToUpgrade.map((heroId) => drops.find((drop) => drop.heroId == heroId)).filter((drop) => drop);
  11655. const firstMission = heroDrops[0];
  11656. // Выбираем миссию для рейда
  11657. const selectedMissionId = firstMission ? firstMission.id : 1;
  11658.  
  11659. const stamina = this.questInfo.userGetInfo.refillable.find((x) => x.id == 1).amount;
  11660. const costMissions = 3 * lib.data.mission[selectedMissionId].normalMode.teamExp;
  11661. if (stamina < costMissions) {
  11662. console.log('Энергии не достаточно');
  11663. return 0;
  11664. }
  11665. return selectedMissionId;
  11666. }
  11667.  
  11668. end(status) {
  11669. setProgress(status, true);
  11670. this.resolve();
  11671. }
  11672. }
  11673.  
  11674. this.questRun = dailyQuests;
  11675. this.HWHClasses.dailyQuests = dailyQuests;
  11676.  
  11677. function testDoYourBest() {
  11678. const { doYourBest } = HWHClasses;
  11679. return new Promise((resolve, reject) => {
  11680. const doIt = new doYourBest(resolve, reject);
  11681. doIt.start();
  11682. });
  11683. }
  11684.  
  11685. /**
  11686. * Do everything button
  11687. *
  11688. * Кнопка сделать все
  11689. */
  11690. class doYourBest {
  11691.  
  11692. funcList = [
  11693. {
  11694. name: 'getOutland',
  11695. label: I18N('ASSEMBLE_OUTLAND'),
  11696. checked: false
  11697. },
  11698. {
  11699. name: 'testTower',
  11700. label: I18N('PASS_THE_TOWER'),
  11701. checked: false
  11702. },
  11703. {
  11704. name: 'checkExpedition',
  11705. label: I18N('CHECK_EXPEDITIONS'),
  11706. checked: false
  11707. },
  11708. {
  11709. name: 'testTitanArena',
  11710. label: I18N('COMPLETE_TOE'),
  11711. checked: false
  11712. },
  11713. {
  11714. name: 'mailGetAll',
  11715. label: I18N('COLLECT_MAIL'),
  11716. checked: false
  11717. },
  11718. {
  11719. name: 'collectAllStuff',
  11720. label: I18N('COLLECT_MISC'),
  11721. title: I18N('COLLECT_MISC_TITLE'),
  11722. checked: false
  11723. },
  11724. {
  11725. name: 'getDailyBonus',
  11726. label: I18N('DAILY_BONUS'),
  11727. checked: false
  11728. },
  11729. {
  11730. name: 'dailyQuests',
  11731. label: I18N('DO_DAILY_QUESTS'),
  11732. checked: false
  11733. },
  11734. {
  11735. name: 'rollAscension',
  11736. label: I18N('SEER_TITLE'),
  11737. checked: false
  11738. },
  11739. {
  11740. name: 'questAllFarm',
  11741. label: I18N('COLLECT_QUEST_REWARDS'),
  11742. checked: false
  11743. },
  11744. {
  11745. name: 'testDungeon',
  11746. label: I18N('COMPLETE_DUNGEON'),
  11747. checked: false
  11748. },
  11749. {
  11750. name: 'synchronization',
  11751. label: I18N('MAKE_A_SYNC'),
  11752. checked: false
  11753. },
  11754. {
  11755. name: 'reloadGame',
  11756. label: I18N('RELOAD_GAME'),
  11757. checked: false
  11758. },
  11759. ];
  11760.  
  11761. functions = {
  11762. getOutland,
  11763. testTower,
  11764. checkExpedition,
  11765. testTitanArena,
  11766. mailGetAll,
  11767. collectAllStuff: async () => {
  11768. await offerFarmAllReward();
  11769. await Send('{"calls":[{"name":"subscriptionFarm","args":{},"ident":"body"},{"name":"zeppelinGiftFarm","args":{},"ident":"zeppelinGiftFarm"},{"name":"grandFarmCoins","args":{},"ident":"grandFarmCoins"},{"name":"gacha_refill","args":{"ident":"heroGacha"},"ident":"gacha_refill"}]}');
  11770. },
  11771. dailyQuests: async function () {
  11772. const quests = new dailyQuests(() => { }, () => { });
  11773. await quests.autoInit(true);
  11774. await quests.start();
  11775. },
  11776. rollAscension,
  11777. getDailyBonus,
  11778. questAllFarm,
  11779. testDungeon,
  11780. synchronization: async () => {
  11781. cheats.refreshGame();
  11782. },
  11783. reloadGame: async () => {
  11784. location.reload();
  11785. },
  11786. }
  11787.  
  11788. constructor(resolve, reject, questInfo) {
  11789. this.resolve = resolve;
  11790. this.reject = reject;
  11791. this.questInfo = questInfo
  11792. }
  11793.  
  11794. async start() {
  11795. const selectedDoIt = getSaveVal('selectedDoIt', {});
  11796.  
  11797. this.funcList.forEach(task => {
  11798. if (!selectedDoIt[task.name]) {
  11799. selectedDoIt[task.name] = {
  11800. checked: task.checked
  11801. }
  11802. } else {
  11803. task.checked = selectedDoIt[task.name].checked
  11804. }
  11805. });
  11806.  
  11807. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  11808. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11809. { msg: I18N('BTN_GO'), result: true },
  11810. ], this.funcList);
  11811.  
  11812. if (!answer) {
  11813. this.end('');
  11814. return;
  11815. }
  11816.  
  11817. const taskList = popup.getCheckBoxes();
  11818. taskList.forEach(task => {
  11819. selectedDoIt[task.name].checked = task.checked;
  11820. });
  11821. setSaveVal('selectedDoIt', selectedDoIt);
  11822. for (const task of popup.getCheckBoxes()) {
  11823. if (task.checked) {
  11824. try {
  11825. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  11826. await this.functions[task.name]();
  11827. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  11828. } catch (error) {
  11829. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  11830. { msg: I18N('BTN_NO'), result: false },
  11831. { msg: I18N('BTN_YES'), result: true },
  11832. ])) {
  11833. this.errorHandling(error);
  11834. }
  11835. }
  11836. }
  11837. }
  11838. setTimeout((msg) => {
  11839. this.end(msg);
  11840. }, 2000, I18N('ALL_TASK_COMPLETED'));
  11841. return;
  11842. }
  11843.  
  11844. errorHandling(error) {
  11845. //console.error(error);
  11846. let errorInfo = error.toString() + '\n';
  11847. try {
  11848. const errorStack = error.stack.split('\n');
  11849. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  11850. errorInfo += errorStack.slice(0, endStack).join('\n');
  11851. } catch (e) {
  11852. errorInfo += error.stack;
  11853. }
  11854. copyText(errorInfo);
  11855. }
  11856.  
  11857. end(status) {
  11858. setProgress(status, true);
  11859. this.resolve();
  11860. }
  11861. }
  11862.  
  11863. this.HWHClasses.doYourBest = doYourBest;
  11864.  
  11865. /**
  11866. * Passing the adventure along the specified route
  11867. *
  11868. * Прохождение приключения по указанному маршруту
  11869. */
  11870. function testAdventure(type) {
  11871. const { executeAdventure } = HWHClasses;
  11872. return new Promise((resolve, reject) => {
  11873. const bossBattle = new executeAdventure(resolve, reject);
  11874. bossBattle.start(type);
  11875. });
  11876. }
  11877.  
  11878. /**
  11879. * Passing the adventure along the specified route
  11880. *
  11881. * Прохождение приключения по указанному маршруту
  11882. */
  11883. class executeAdventure {
  11884.  
  11885. type = 'default';
  11886.  
  11887. actions = {
  11888. default: {
  11889. getInfo: "adventure_getInfo",
  11890. startBattle: 'adventure_turnStartBattle',
  11891. endBattle: 'adventure_endBattle',
  11892. collectBuff: 'adventure_turnCollectBuff'
  11893. },
  11894. solo: {
  11895. getInfo: "adventureSolo_getInfo",
  11896. startBattle: 'adventureSolo_turnStartBattle',
  11897. endBattle: 'adventureSolo_endBattle',
  11898. collectBuff: 'adventureSolo_turnCollectBuff'
  11899. }
  11900. }
  11901.  
  11902. terminatеReason = I18N('UNKNOWN');
  11903. callAdventureInfo = {
  11904. name: "adventure_getInfo",
  11905. args: {},
  11906. ident: "adventure_getInfo"
  11907. }
  11908. callTeamGetAll = {
  11909. name: "teamGetAll",
  11910. args: {},
  11911. ident: "teamGetAll"
  11912. }
  11913. callTeamGetFavor = {
  11914. name: "teamGetFavor",
  11915. args: {},
  11916. ident: "teamGetFavor"
  11917. }
  11918. callStartBattle = {
  11919. name: "adventure_turnStartBattle",
  11920. args: {},
  11921. ident: "body"
  11922. }
  11923. callEndBattle = {
  11924. name: "adventure_endBattle",
  11925. args: {
  11926. result: {},
  11927. progress: {},
  11928. },
  11929. ident: "body"
  11930. }
  11931. callCollectBuff = {
  11932. name: "adventure_turnCollectBuff",
  11933. args: {},
  11934. ident: "body"
  11935. }
  11936.  
  11937. constructor(resolve, reject) {
  11938. this.resolve = resolve;
  11939. this.reject = reject;
  11940. }
  11941.  
  11942. async start(type) {
  11943. this.type = type || this.type;
  11944. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  11945. const data = await Send(JSON.stringify({
  11946. calls: [
  11947. this.callAdventureInfo,
  11948. this.callTeamGetAll,
  11949. this.callTeamGetFavor
  11950. ]
  11951. }));
  11952. return this.checkAdventureInfo(data.results);
  11953. }
  11954.  
  11955. async getPath() {
  11956. const oldVal = getSaveVal('adventurePath', '');
  11957. const keyPath = `adventurePath:${this.mapIdent}`;
  11958. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  11959. {
  11960. msg: I18N('START_ADVENTURE'),
  11961. placeholder: '1,2,3,4,5,6',
  11962. isInput: true,
  11963. default: getSaveVal(keyPath, oldVal)
  11964. },
  11965. {
  11966. msg: I18N('BTN_CANCEL'),
  11967. result: false,
  11968. isCancel: true
  11969. },
  11970. ]);
  11971. if (!answer) {
  11972. this.terminatеReason = I18N('BTN_CANCELED');
  11973. return false;
  11974. }
  11975.  
  11976. let path = answer.split(',');
  11977. if (path.length < 2) {
  11978. path = answer.split('-');
  11979. }
  11980. if (path.length < 2) {
  11981. this.terminatеReason = I18N('MUST_TWO_POINTS');
  11982. return false;
  11983. }
  11984.  
  11985. for (let p in path) {
  11986. path[p] = +path[p].trim()
  11987. if (Number.isNaN(path[p])) {
  11988. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  11989. return false;
  11990. }
  11991. }
  11992.  
  11993. if (!this.checkPath(path)) {
  11994. return false;
  11995. }
  11996. setSaveVal(keyPath, answer);
  11997. return path;
  11998. }
  11999.  
  12000. checkPath(path) {
  12001. for (let i = 0; i < path.length - 1; i++) {
  12002. const currentPoint = path[i];
  12003. const nextPoint = path[i + 1];
  12004.  
  12005. const isValidPath = this.paths.some(p =>
  12006. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  12007. (p.from_id === nextPoint && p.to_id === currentPoint)
  12008. );
  12009.  
  12010. if (!isValidPath) {
  12011. this.terminatеReason = I18N('INCORRECT_WAY', {
  12012. from: currentPoint,
  12013. to: nextPoint,
  12014. });
  12015. return false;
  12016. }
  12017. }
  12018.  
  12019. return true;
  12020. }
  12021.  
  12022. async checkAdventureInfo(data) {
  12023. this.advInfo = data[0].result.response;
  12024. if (!this.advInfo) {
  12025. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  12026. return this.end();
  12027. }
  12028. const heroesTeam = data[1].result.response.adventure_hero;
  12029. const favor = data[2]?.result.response.adventure_hero;
  12030. const heroes = heroesTeam.slice(0, 5);
  12031. const pet = heroesTeam[5];
  12032. this.args = {
  12033. pet,
  12034. heroes,
  12035. favor,
  12036. path: [],
  12037. broadcast: false
  12038. }
  12039. const advUserInfo = this.advInfo.users[userInfo.id];
  12040. this.turnsLeft = advUserInfo.turnsLeft;
  12041. this.currentNode = advUserInfo.currentNode;
  12042. this.nodes = this.advInfo.nodes;
  12043. this.paths = this.advInfo.paths;
  12044. this.mapIdent = this.advInfo.mapIdent;
  12045.  
  12046. this.path = await this.getPath();
  12047. if (!this.path) {
  12048. return this.end();
  12049. }
  12050.  
  12051. if (this.currentNode == 1 && this.path[0] != 1) {
  12052. this.path.unshift(1);
  12053. }
  12054.  
  12055. return this.loop();
  12056. }
  12057.  
  12058. async loop() {
  12059. const position = this.path.indexOf(+this.currentNode);
  12060. if (!(~position)) {
  12061. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  12062. return this.end();
  12063. }
  12064. this.path = this.path.slice(position);
  12065. if ((this.path.length - 1) > this.turnsLeft &&
  12066. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  12067. { msg: I18N('YES_CONTINUE'), result: false },
  12068. { msg: I18N('BTN_NO'), result: true },
  12069. ])) {
  12070. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  12071. return this.end();
  12072. }
  12073. const toPath = [];
  12074. for (const nodeId of this.path) {
  12075. if (!this.turnsLeft) {
  12076. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  12077. return this.end();
  12078. }
  12079. toPath.push(nodeId);
  12080. console.log(toPath);
  12081. if (toPath.length > 1) {
  12082. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  12083. }
  12084. if (nodeId == this.currentNode) {
  12085. continue;
  12086. }
  12087.  
  12088. const nodeInfo = this.getNodeInfo(nodeId);
  12089. if (nodeInfo.type == 'TYPE_COMBAT') {
  12090. if (nodeInfo.state == 'empty') {
  12091. this.turnsLeft--;
  12092. continue;
  12093. }
  12094.  
  12095. /**
  12096. * Disable regular battle cancellation
  12097. *
  12098. * Отключаем штатную отменую боя
  12099. */
  12100. setIsCancalBattle(false);
  12101. if (await this.battle(toPath)) {
  12102. this.turnsLeft--;
  12103. toPath.splice(0, toPath.indexOf(nodeId));
  12104. nodeInfo.state = 'empty';
  12105. setIsCancalBattle(true);
  12106. continue;
  12107. }
  12108. setIsCancalBattle(true);
  12109. return this.end()
  12110. }
  12111.  
  12112. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  12113. const buff = this.checkBuff(nodeInfo);
  12114. if (buff == null) {
  12115. continue;
  12116. }
  12117.  
  12118. if (await this.collectBuff(buff, toPath)) {
  12119. this.turnsLeft--;
  12120. toPath.splice(0, toPath.indexOf(nodeId));
  12121. continue;
  12122. }
  12123. this.terminatеReason = I18N('BUFF_GET_ERROR');
  12124. return this.end();
  12125. }
  12126. }
  12127. this.terminatеReason = I18N('SUCCESS');
  12128. return this.end();
  12129. }
  12130.  
  12131. /**
  12132. * Carrying out a fight
  12133. *
  12134. * Проведение боя
  12135. */
  12136. async battle(path, preCalc = true) {
  12137. const data = await this.startBattle(path);
  12138. try {
  12139. const battle = data.results[0].result.response.battle;
  12140. const result = await Calc(battle);
  12141. if (result.result.win) {
  12142. const info = await this.endBattle(result);
  12143. if (info.results[0].result.response?.error) {
  12144. this.terminatеReason = I18N('BATTLE_END_ERROR');
  12145. return false;
  12146. }
  12147. } else {
  12148. await this.cancelBattle(result);
  12149.  
  12150. if (preCalc && await this.preCalcBattle(battle)) {
  12151. path = path.slice(-2);
  12152. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  12153. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  12154. const result = await this.battle(path, false);
  12155. if (result) {
  12156. setProgress(I18N('VICTORY'));
  12157. return true;
  12158. }
  12159. }
  12160. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  12161. return false;
  12162. }
  12163. return false;
  12164. }
  12165. } catch (error) {
  12166. console.error(error);
  12167. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  12168. { msg: I18N('BTN_NO'), result: false },
  12169. { msg: I18N('BTN_YES'), result: true },
  12170. ])) {
  12171. this.errorHandling(error, data);
  12172. }
  12173. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  12174. return false;
  12175. }
  12176. return true;
  12177. }
  12178.  
  12179. /**
  12180. * Recalculate battles
  12181. *
  12182. * Прерасчтет битвы
  12183. */
  12184. async preCalcBattle(battle) {
  12185. const countTestBattle = getInput('countTestBattle');
  12186. for (let i = 0; i < countTestBattle; i++) {
  12187. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  12188. const result = await Calc(battle);
  12189. if (result.result.win) {
  12190. console.log(i, countTestBattle);
  12191. return true;
  12192. }
  12193. }
  12194. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  12195. return false;
  12196. }
  12197.  
  12198. /**
  12199. * Starts a fight
  12200. *
  12201. * Начинает бой
  12202. */
  12203. startBattle(path) {
  12204. this.args.path = path;
  12205. this.callStartBattle.name = this.actions[this.type].startBattle;
  12206. this.callStartBattle.args = this.args
  12207. const calls = [this.callStartBattle];
  12208. return Send(JSON.stringify({ calls }));
  12209. }
  12210.  
  12211. cancelBattle(battle) {
  12212. const fixBattle = function (heroes) {
  12213. for (const ids in heroes) {
  12214. const hero = heroes[ids];
  12215. hero.energy = random(1, 999);
  12216. if (hero.hp > 0) {
  12217. hero.hp = random(1, hero.hp);
  12218. }
  12219. }
  12220. }
  12221. fixBattle(battle.progress[0].attackers.heroes);
  12222. fixBattle(battle.progress[0].defenders.heroes);
  12223. return this.endBattle(battle);
  12224. }
  12225.  
  12226. /**
  12227. * Ends the fight
  12228. *
  12229. * Заканчивает бой
  12230. */
  12231. endBattle(battle) {
  12232. this.callEndBattle.name = this.actions[this.type].endBattle;
  12233. this.callEndBattle.args.result = battle.result
  12234. this.callEndBattle.args.progress = battle.progress
  12235. const calls = [this.callEndBattle];
  12236. return Send(JSON.stringify({ calls }));
  12237. }
  12238.  
  12239. /**
  12240. * Checks if you can get a buff
  12241. *
  12242. * Проверяет можно ли получить баф
  12243. */
  12244. checkBuff(nodeInfo) {
  12245. let id = null;
  12246. let value = 0;
  12247. for (const buffId in nodeInfo.buffs) {
  12248. const buff = nodeInfo.buffs[buffId];
  12249. if (buff.owner == null && buff.value > value) {
  12250. id = buffId;
  12251. value = buff.value;
  12252. }
  12253. }
  12254. nodeInfo.buffs[id].owner = 'Я';
  12255. return id;
  12256. }
  12257.  
  12258. /**
  12259. * Collects a buff
  12260. *
  12261. * Собирает баф
  12262. */
  12263. async collectBuff(buff, path) {
  12264. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  12265. this.callCollectBuff.args = { buff, path };
  12266. const calls = [this.callCollectBuff];
  12267. return Send(JSON.stringify({ calls }));
  12268. }
  12269.  
  12270. getNodeInfo(nodeId) {
  12271. return this.nodes.find(node => node.id == nodeId);
  12272. }
  12273.  
  12274. errorHandling(error, data) {
  12275. //console.error(error);
  12276. let errorInfo = error.toString() + '\n';
  12277. try {
  12278. const errorStack = error.stack.split('\n');
  12279. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  12280. errorInfo += errorStack.slice(0, endStack).join('\n');
  12281. } catch (e) {
  12282. errorInfo += error.stack;
  12283. }
  12284. if (data) {
  12285. errorInfo += '\nData: ' + JSON.stringify(data);
  12286. }
  12287. copyText(errorInfo);
  12288. }
  12289.  
  12290. end() {
  12291. setIsCancalBattle(true);
  12292. setProgress(this.terminatеReason, true);
  12293. console.log(this.terminatеReason);
  12294. this.resolve();
  12295. }
  12296. }
  12297.  
  12298. this.HWHClasses.executeAdventure = executeAdventure;
  12299.  
  12300. /**
  12301. * Passage of brawls
  12302. *
  12303. * Прохождение потасовок
  12304. */
  12305. function testBrawls(isAuto) {
  12306. const { executeBrawls } = HWHClasses;
  12307. return new Promise((resolve, reject) => {
  12308. const brawls = new executeBrawls(resolve, reject);
  12309. brawls.start(brawlsPack, isAuto);
  12310. });
  12311. }
  12312. /**
  12313. * Passage of brawls
  12314. *
  12315. * Прохождение потасовок
  12316. */
  12317. class executeBrawls {
  12318. callBrawlQuestGetInfo = {
  12319. name: "brawl_questGetInfo",
  12320. args: {},
  12321. ident: "brawl_questGetInfo"
  12322. }
  12323. callBrawlFindEnemies = {
  12324. name: "brawl_findEnemies",
  12325. args: {},
  12326. ident: "brawl_findEnemies"
  12327. }
  12328. callBrawlQuestFarm = {
  12329. name: "brawl_questFarm",
  12330. args: {},
  12331. ident: "brawl_questFarm"
  12332. }
  12333. callUserGetInfo = {
  12334. name: "userGetInfo",
  12335. args: {},
  12336. ident: "userGetInfo"
  12337. }
  12338. callTeamGetMaxUpgrade = {
  12339. name: "teamGetMaxUpgrade",
  12340. args: {},
  12341. ident: "teamGetMaxUpgrade"
  12342. }
  12343. callBrawlGetInfo = {
  12344. name: "brawl_getInfo",
  12345. args: {},
  12346. ident: "brawl_getInfo"
  12347. }
  12348.  
  12349. stats = {
  12350. win: 0,
  12351. loss: 0,
  12352. count: 0,
  12353. }
  12354.  
  12355. stage = {
  12356. '3': 1,
  12357. '7': 2,
  12358. '12': 3,
  12359. }
  12360.  
  12361. attempts = 0;
  12362.  
  12363. constructor(resolve, reject) {
  12364. this.resolve = resolve;
  12365. this.reject = reject;
  12366.  
  12367. const allHeroIds = Object.keys(lib.getData('hero'));
  12368. this.callTeamGetMaxUpgrade.args.units = {
  12369. hero: allHeroIds.filter((id) => +id < 1000),
  12370. titan: allHeroIds.filter((id) => +id >= 4000 && +id < 4100),
  12371. pet: allHeroIds.filter((id) => +id >= 6000 && +id < 6100),
  12372. };
  12373. }
  12374.  
  12375. async start(args, isAuto) {
  12376. this.isAuto = isAuto;
  12377. this.args = args;
  12378. setIsCancalBattle(false);
  12379. this.brawlInfo = await this.getBrawlInfo();
  12380. this.attempts = this.brawlInfo.attempts;
  12381.  
  12382. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12383. this.end(I18N('DONT_HAVE_LIVES'));
  12384. return;
  12385. }
  12386.  
  12387. while (1) {
  12388. if (!isBrawlsAutoStart) {
  12389. this.end(I18N('BTN_CANCELED'));
  12390. return;
  12391. }
  12392.  
  12393. const maxStage = this.brawlInfo.questInfo.stage;
  12394. const stage = this.stage[maxStage];
  12395. const progress = this.brawlInfo.questInfo.progress;
  12396.  
  12397. setProgress(
  12398. `${I18N('STAGE')} ${stage}: ${progress}/${maxStage}<br>${I18N('FIGHTS')}: ${this.stats.count}<br>${I18N('WINS')}: ${
  12399. this.stats.win
  12400. }<br>${I18N('LOSSES')}: ${this.stats.loss}<br>${I18N('LIVES')}: ${this.attempts}<br>${I18N('STOP')}`,
  12401. false,
  12402. function () {
  12403. isBrawlsAutoStart = false;
  12404. }
  12405. );
  12406.  
  12407. if (this.brawlInfo.questInfo.canFarm) {
  12408. const result = await this.questFarm();
  12409. console.log(result);
  12410. }
  12411.  
  12412. if (!this.continueAttack && this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  12413. if (
  12414. await popup.confirm(I18N('BRAWL_DAILY_TASK_COMPLETED'), [
  12415. { msg: I18N('BTN_NO'), result: true },
  12416. { msg: I18N('BTN_YES'), result: false },
  12417. ])
  12418. ) {
  12419. this.end(I18N('SUCCESS'));
  12420. return;
  12421. } else {
  12422. this.continueAttack = true;
  12423. }
  12424. }
  12425.  
  12426. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12427. this.end(I18N('DONT_HAVE_LIVES'));
  12428. return;
  12429. }
  12430.  
  12431. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  12432.  
  12433. // Автоматический подбор пачки
  12434. if (this.isAuto) {
  12435. if (this.mandatoryId <= 4000 && this.mandatoryId != 13) {
  12436. this.end(I18N('BRAWL_AUTO_PACK_NOT_CUR_HERO'));
  12437. return;
  12438. }
  12439. if (this.mandatoryId >= 4000 && this.mandatoryId < 4100) {
  12440. this.args = await this.updateTitanPack(enemie.heroes);
  12441. } else if (this.mandatoryId < 4000 && this.mandatoryId == 13) {
  12442. this.args = await this.updateHeroesPack(enemie.heroes);
  12443. }
  12444. }
  12445.  
  12446. const result = await this.battle(enemie.userId);
  12447. this.brawlInfo = {
  12448. questInfo: result[1].result.response,
  12449. findEnemies: result[2].result.response,
  12450. };
  12451. }
  12452. }
  12453.  
  12454. async updateTitanPack(enemieHeroes) {
  12455. const packs = [
  12456. [4033, 4040, 4041, 4042, 4043],
  12457. [4032, 4040, 4041, 4042, 4043],
  12458. [4031, 4040, 4041, 4042, 4043],
  12459. [4030, 4040, 4041, 4042, 4043],
  12460. [4032, 4033, 4040, 4042, 4043],
  12461. [4030, 4033, 4041, 4042, 4043],
  12462. [4031, 4033, 4040, 4042, 4043],
  12463. [4032, 4033, 4040, 4041, 4043],
  12464. [4023, 4040, 4041, 4042, 4043],
  12465. [4030, 4033, 4040, 4042, 4043],
  12466. [4031, 4033, 4040, 4041, 4043],
  12467. [4022, 4040, 4041, 4042, 4043],
  12468. [4030, 4033, 4040, 4041, 4043],
  12469. [4021, 4040, 4041, 4042, 4043],
  12470. [4020, 4040, 4041, 4042, 4043],
  12471. [4023, 4033, 4040, 4042, 4043],
  12472. [4030, 4032, 4033, 4042, 4043],
  12473. [4023, 4033, 4040, 4041, 4043],
  12474. [4031, 4032, 4033, 4040, 4043],
  12475. [4030, 4032, 4033, 4041, 4043],
  12476. [4030, 4031, 4033, 4042, 4043],
  12477. [4013, 4040, 4041, 4042, 4043],
  12478. [4030, 4032, 4033, 4040, 4043],
  12479. [4030, 4031, 4033, 4041, 4043],
  12480. [4012, 4040, 4041, 4042, 4043],
  12481. [4030, 4031, 4033, 4040, 4043],
  12482. [4011, 4040, 4041, 4042, 4043],
  12483. [4010, 4040, 4041, 4042, 4043],
  12484. [4023, 4032, 4033, 4042, 4043],
  12485. [4022, 4032, 4033, 4042, 4043],
  12486. [4023, 4032, 4033, 4041, 4043],
  12487. [4021, 4032, 4033, 4042, 4043],
  12488. [4022, 4032, 4033, 4041, 4043],
  12489. [4023, 4030, 4033, 4042, 4043],
  12490. [4023, 4032, 4033, 4040, 4043],
  12491. [4013, 4033, 4040, 4042, 4043],
  12492. [4020, 4032, 4033, 4042, 4043],
  12493. [4021, 4032, 4033, 4041, 4043],
  12494. [4022, 4030, 4033, 4042, 4043],
  12495. [4022, 4032, 4033, 4040, 4043],
  12496. [4023, 4030, 4033, 4041, 4043],
  12497. [4023, 4031, 4033, 4040, 4043],
  12498. [4013, 4033, 4040, 4041, 4043],
  12499. [4020, 4031, 4033, 4042, 4043],
  12500. [4020, 4032, 4033, 4041, 4043],
  12501. [4021, 4030, 4033, 4042, 4043],
  12502. [4021, 4032, 4033, 4040, 4043],
  12503. [4022, 4030, 4033, 4041, 4043],
  12504. [4022, 4031, 4033, 4040, 4043],
  12505. [4023, 4030, 4033, 4040, 4043],
  12506. [4030, 4031, 4032, 4033, 4043],
  12507. [4003, 4040, 4041, 4042, 4043],
  12508. [4020, 4030, 4033, 4042, 4043],
  12509. [4020, 4031, 4033, 4041, 4043],
  12510. [4020, 4032, 4033, 4040, 4043],
  12511. [4021, 4030, 4033, 4041, 4043],
  12512. [4021, 4031, 4033, 4040, 4043],
  12513. [4022, 4030, 4033, 4040, 4043],
  12514. [4030, 4031, 4032, 4033, 4042],
  12515. [4002, 4040, 4041, 4042, 4043],
  12516. [4020, 4030, 4033, 4041, 4043],
  12517. [4020, 4031, 4033, 4040, 4043],
  12518. [4021, 4030, 4033, 4040, 4043],
  12519. [4030, 4031, 4032, 4033, 4041],
  12520. [4001, 4040, 4041, 4042, 4043],
  12521. [4030, 4031, 4032, 4033, 4040],
  12522. [4000, 4040, 4041, 4042, 4043],
  12523. [4013, 4032, 4033, 4042, 4043],
  12524. [4012, 4032, 4033, 4042, 4043],
  12525. [4013, 4032, 4033, 4041, 4043],
  12526. [4023, 4031, 4032, 4033, 4043],
  12527. [4011, 4032, 4033, 4042, 4043],
  12528. [4012, 4032, 4033, 4041, 4043],
  12529. [4013, 4030, 4033, 4042, 4043],
  12530. [4013, 4032, 4033, 4040, 4043],
  12531. [4023, 4030, 4032, 4033, 4043],
  12532. [4003, 4033, 4040, 4042, 4043],
  12533. [4013, 4023, 4040, 4042, 4043],
  12534. [4010, 4032, 4033, 4042, 4043],
  12535. [4011, 4032, 4033, 4041, 4043],
  12536. [4012, 4030, 4033, 4042, 4043],
  12537. [4012, 4032, 4033, 4040, 4043],
  12538. [4013, 4030, 4033, 4041, 4043],
  12539. [4013, 4031, 4033, 4040, 4043],
  12540. [4023, 4030, 4031, 4033, 4043],
  12541. [4003, 4033, 4040, 4041, 4043],
  12542. [4013, 4023, 4040, 4041, 4043],
  12543. [4010, 4031, 4033, 4042, 4043],
  12544. [4010, 4032, 4033, 4041, 4043],
  12545. [4011, 4030, 4033, 4042, 4043],
  12546. [4011, 4032, 4033, 4040, 4043],
  12547. [4012, 4030, 4033, 4041, 4043],
  12548. [4012, 4031, 4033, 4040, 4043],
  12549. [4013, 4030, 4033, 4040, 4043],
  12550. [4010, 4030, 4033, 4042, 4043],
  12551. [4010, 4031, 4033, 4041, 4043],
  12552. [4010, 4032, 4033, 4040, 4043],
  12553. [4011, 4030, 4033, 4041, 4043],
  12554. [4011, 4031, 4033, 4040, 4043],
  12555. [4012, 4030, 4033, 4040, 4043],
  12556. [4010, 4030, 4033, 4041, 4043],
  12557. [4010, 4031, 4033, 4040, 4043],
  12558. [4011, 4030, 4033, 4040, 4043],
  12559. [4003, 4032, 4033, 4042, 4043],
  12560. [4002, 4032, 4033, 4042, 4043],
  12561. [4003, 4032, 4033, 4041, 4043],
  12562. [4013, 4031, 4032, 4033, 4043],
  12563. [4001, 4032, 4033, 4042, 4043],
  12564. [4002, 4032, 4033, 4041, 4043],
  12565. [4003, 4030, 4033, 4042, 4043],
  12566. [4003, 4032, 4033, 4040, 4043],
  12567. [4013, 4030, 4032, 4033, 4043],
  12568. [4003, 4023, 4040, 4042, 4043],
  12569. [4000, 4032, 4033, 4042, 4043],
  12570. [4001, 4032, 4033, 4041, 4043],
  12571. [4002, 4030, 4033, 4042, 4043],
  12572. [4002, 4032, 4033, 4040, 4043],
  12573. [4003, 4030, 4033, 4041, 4043],
  12574. [4003, 4031, 4033, 4040, 4043],
  12575. [4020, 4022, 4023, 4042, 4043],
  12576. [4013, 4030, 4031, 4033, 4043],
  12577. [4003, 4023, 4040, 4041, 4043],
  12578. [4000, 4031, 4033, 4042, 4043],
  12579. [4000, 4032, 4033, 4041, 4043],
  12580. [4001, 4030, 4033, 4042, 4043],
  12581. [4001, 4032, 4033, 4040, 4043],
  12582. [4002, 4030, 4033, 4041, 4043],
  12583. [4002, 4031, 4033, 4040, 4043],
  12584. [4003, 4030, 4033, 4040, 4043],
  12585. [4021, 4022, 4023, 4040, 4043],
  12586. [4020, 4022, 4023, 4041, 4043],
  12587. [4020, 4021, 4023, 4042, 4043],
  12588. [4023, 4030, 4031, 4032, 4033],
  12589. [4000, 4030, 4033, 4042, 4043],
  12590. [4000, 4031, 4033, 4041, 4043],
  12591. [4000, 4032, 4033, 4040, 4043],
  12592. [4001, 4030, 4033, 4041, 4043],
  12593. [4001, 4031, 4033, 4040, 4043],
  12594. [4002, 4030, 4033, 4040, 4043],
  12595. [4020, 4022, 4023, 4040, 4043],
  12596. [4020, 4021, 4023, 4041, 4043],
  12597. [4022, 4030, 4031, 4032, 4033],
  12598. [4000, 4030, 4033, 4041, 4043],
  12599. [4000, 4031, 4033, 4040, 4043],
  12600. [4001, 4030, 4033, 4040, 4043],
  12601. [4020, 4021, 4023, 4040, 4043],
  12602. [4021, 4030, 4031, 4032, 4033],
  12603. [4020, 4030, 4031, 4032, 4033],
  12604. [4003, 4031, 4032, 4033, 4043],
  12605. [4020, 4022, 4023, 4033, 4043],
  12606. [4003, 4030, 4032, 4033, 4043],
  12607. [4003, 4013, 4040, 4042, 4043],
  12608. [4020, 4021, 4023, 4033, 4043],
  12609. [4003, 4030, 4031, 4033, 4043],
  12610. [4003, 4013, 4040, 4041, 4043],
  12611. [4013, 4030, 4031, 4032, 4033],
  12612. [4012, 4030, 4031, 4032, 4033],
  12613. [4011, 4030, 4031, 4032, 4033],
  12614. [4010, 4030, 4031, 4032, 4033],
  12615. [4013, 4023, 4031, 4032, 4033],
  12616. [4013, 4023, 4030, 4032, 4033],
  12617. [4020, 4022, 4023, 4032, 4033],
  12618. [4013, 4023, 4030, 4031, 4033],
  12619. [4021, 4022, 4023, 4030, 4033],
  12620. [4020, 4022, 4023, 4031, 4033],
  12621. [4020, 4021, 4023, 4032, 4033],
  12622. [4020, 4021, 4022, 4023, 4043],
  12623. [4003, 4030, 4031, 4032, 4033],
  12624. [4020, 4022, 4023, 4030, 4033],
  12625. [4020, 4021, 4023, 4031, 4033],
  12626. [4020, 4021, 4022, 4023, 4042],
  12627. [4002, 4030, 4031, 4032, 4033],
  12628. [4020, 4021, 4023, 4030, 4033],
  12629. [4020, 4021, 4022, 4023, 4041],
  12630. [4001, 4030, 4031, 4032, 4033],
  12631. [4020, 4021, 4022, 4023, 4040],
  12632. [4000, 4030, 4031, 4032, 4033],
  12633. [4003, 4023, 4031, 4032, 4033],
  12634. [4013, 4020, 4022, 4023, 4043],
  12635. [4003, 4023, 4030, 4032, 4033],
  12636. [4010, 4012, 4013, 4042, 4043],
  12637. [4013, 4020, 4021, 4023, 4043],
  12638. [4003, 4023, 4030, 4031, 4033],
  12639. [4011, 4012, 4013, 4040, 4043],
  12640. [4010, 4012, 4013, 4041, 4043],
  12641. [4010, 4011, 4013, 4042, 4043],
  12642. [4020, 4021, 4022, 4023, 4033],
  12643. [4010, 4012, 4013, 4040, 4043],
  12644. [4010, 4011, 4013, 4041, 4043],
  12645. [4020, 4021, 4022, 4023, 4032],
  12646. [4010, 4011, 4013, 4040, 4043],
  12647. [4020, 4021, 4022, 4023, 4031],
  12648. [4020, 4021, 4022, 4023, 4030],
  12649. [4003, 4013, 4031, 4032, 4033],
  12650. [4010, 4012, 4013, 4033, 4043],
  12651. [4003, 4020, 4022, 4023, 4043],
  12652. [4013, 4020, 4022, 4023, 4033],
  12653. [4003, 4013, 4030, 4032, 4033],
  12654. [4010, 4011, 4013, 4033, 4043],
  12655. [4003, 4020, 4021, 4023, 4043],
  12656. [4013, 4020, 4021, 4023, 4033],
  12657. [4003, 4013, 4030, 4031, 4033],
  12658. [4010, 4012, 4013, 4023, 4043],
  12659. [4003, 4020, 4022, 4023, 4033],
  12660. [4010, 4012, 4013, 4032, 4033],
  12661. [4010, 4011, 4013, 4023, 4043],
  12662. [4003, 4020, 4021, 4023, 4033],
  12663. [4011, 4012, 4013, 4030, 4033],
  12664. [4010, 4012, 4013, 4031, 4033],
  12665. [4010, 4011, 4013, 4032, 4033],
  12666. [4013, 4020, 4021, 4022, 4023],
  12667. [4010, 4012, 4013, 4030, 4033],
  12668. [4010, 4011, 4013, 4031, 4033],
  12669. [4012, 4020, 4021, 4022, 4023],
  12670. [4010, 4011, 4013, 4030, 4033],
  12671. [4011, 4020, 4021, 4022, 4023],
  12672. [4010, 4020, 4021, 4022, 4023],
  12673. [4010, 4012, 4013, 4023, 4033],
  12674. [4000, 4002, 4003, 4042, 4043],
  12675. [4010, 4011, 4013, 4023, 4033],
  12676. [4001, 4002, 4003, 4040, 4043],
  12677. [4000, 4002, 4003, 4041, 4043],
  12678. [4000, 4001, 4003, 4042, 4043],
  12679. [4010, 4011, 4012, 4013, 4043],
  12680. [4003, 4020, 4021, 4022, 4023],
  12681. [4000, 4002, 4003, 4040, 4043],
  12682. [4000, 4001, 4003, 4041, 4043],
  12683. [4010, 4011, 4012, 4013, 4042],
  12684. [4002, 4020, 4021, 4022, 4023],
  12685. [4000, 4001, 4003, 4040, 4043],
  12686. [4010, 4011, 4012, 4013, 4041],
  12687. [4001, 4020, 4021, 4022, 4023],
  12688. [4010, 4011, 4012, 4013, 4040],
  12689. [4000, 4020, 4021, 4022, 4023],
  12690. [4001, 4002, 4003, 4033, 4043],
  12691. [4000, 4002, 4003, 4033, 4043],
  12692. [4003, 4010, 4012, 4013, 4043],
  12693. [4003, 4013, 4020, 4022, 4023],
  12694. [4000, 4001, 4003, 4033, 4043],
  12695. [4003, 4010, 4011, 4013, 4043],
  12696. [4003, 4013, 4020, 4021, 4023],
  12697. [4010, 4011, 4012, 4013, 4033],
  12698. [4010, 4011, 4012, 4013, 4032],
  12699. [4010, 4011, 4012, 4013, 4031],
  12700. [4010, 4011, 4012, 4013, 4030],
  12701. [4001, 4002, 4003, 4023, 4043],
  12702. [4000, 4002, 4003, 4023, 4043],
  12703. [4003, 4010, 4012, 4013, 4033],
  12704. [4000, 4002, 4003, 4032, 4033],
  12705. [4000, 4001, 4003, 4023, 4043],
  12706. [4003, 4010, 4011, 4013, 4033],
  12707. [4001, 4002, 4003, 4030, 4033],
  12708. [4000, 4002, 4003, 4031, 4033],
  12709. [4000, 4001, 4003, 4032, 4033],
  12710. [4010, 4011, 4012, 4013, 4023],
  12711. [4000, 4002, 4003, 4030, 4033],
  12712. [4000, 4001, 4003, 4031, 4033],
  12713. [4010, 4011, 4012, 4013, 4022],
  12714. [4000, 4001, 4003, 4030, 4033],
  12715. [4010, 4011, 4012, 4013, 4021],
  12716. [4010, 4011, 4012, 4013, 4020],
  12717. [4001, 4002, 4003, 4013, 4043],
  12718. [4001, 4002, 4003, 4023, 4033],
  12719. [4000, 4002, 4003, 4013, 4043],
  12720. [4000, 4002, 4003, 4023, 4033],
  12721. [4003, 4010, 4012, 4013, 4023],
  12722. [4000, 4001, 4003, 4013, 4043],
  12723. [4000, 4001, 4003, 4023, 4033],
  12724. [4003, 4010, 4011, 4013, 4023],
  12725. [4001, 4002, 4003, 4013, 4033],
  12726. [4000, 4002, 4003, 4013, 4033],
  12727. [4000, 4001, 4003, 4013, 4033],
  12728. [4000, 4001, 4002, 4003, 4043],
  12729. [4003, 4010, 4011, 4012, 4013],
  12730. [4000, 4001, 4002, 4003, 4042],
  12731. [4002, 4010, 4011, 4012, 4013],
  12732. [4000, 4001, 4002, 4003, 4041],
  12733. [4001, 4010, 4011, 4012, 4013],
  12734. [4000, 4001, 4002, 4003, 4040],
  12735. [4000, 4010, 4011, 4012, 4013],
  12736. [4001, 4002, 4003, 4013, 4023],
  12737. [4000, 4002, 4003, 4013, 4023],
  12738. [4000, 4001, 4003, 4013, 4023],
  12739. [4000, 4001, 4002, 4003, 4033],
  12740. [4000, 4001, 4002, 4003, 4032],
  12741. [4000, 4001, 4002, 4003, 4031],
  12742. [4000, 4001, 4002, 4003, 4030],
  12743. [4000, 4001, 4002, 4003, 4023],
  12744. [4000, 4001, 4002, 4003, 4022],
  12745. [4000, 4001, 4002, 4003, 4021],
  12746. [4000, 4001, 4002, 4003, 4020],
  12747. [4000, 4001, 4002, 4003, 4013],
  12748. [4000, 4001, 4002, 4003, 4012],
  12749. [4000, 4001, 4002, 4003, 4011],
  12750. [4000, 4001, 4002, 4003, 4010],
  12751. ].filter((p) => p.includes(this.mandatoryId));
  12752.  
  12753. const bestPack = {
  12754. pack: packs[0],
  12755. winRate: 0,
  12756. countBattle: 0,
  12757. id: 0,
  12758. };
  12759.  
  12760. for (const id in packs) {
  12761. const pack = packs[id];
  12762. const attackers = this.maxUpgrade.filter((e) => pack.includes(e.id)).reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  12763. const battle = {
  12764. attackers,
  12765. defenders: [enemieHeroes],
  12766. type: 'brawl_titan',
  12767. };
  12768. const isRandom = this.isRandomBattle(battle);
  12769. const stat = {
  12770. count: 0,
  12771. win: 0,
  12772. winRate: 0,
  12773. };
  12774. for (let i = 1; i <= 20; i++) {
  12775. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12776. const result = await Calc(battle);
  12777. stat.win += result.result.win;
  12778. stat.count += 1;
  12779. stat.winRate = stat.win / stat.count;
  12780. if (!isRandom || (i >= 2 && stat.winRate < 0.65) || (i >= 10 && stat.winRate == 1)) {
  12781. break;
  12782. }
  12783. }
  12784.  
  12785. if (!isRandom && stat.win) {
  12786. return {
  12787. favor: {},
  12788. heroes: pack,
  12789. };
  12790. }
  12791. if (stat.winRate > 0.85) {
  12792. return {
  12793. favor: {},
  12794. heroes: pack,
  12795. };
  12796. }
  12797. if (stat.winRate > bestPack.winRate) {
  12798. bestPack.countBattle = stat.count;
  12799. bestPack.winRate = stat.winRate;
  12800. bestPack.pack = pack;
  12801. bestPack.id = id;
  12802. }
  12803. }
  12804.  
  12805. //console.log(bestPack.id, bestPack.pack, bestPack.winRate, bestPack.countBattle);
  12806. return {
  12807. favor: {},
  12808. heroes: bestPack.pack,
  12809. };
  12810. }
  12811.  
  12812. isRandomPack(pack) {
  12813. const ids = Object.keys(pack);
  12814. return ids.includes('4023') || ids.includes('4021');
  12815. }
  12816.  
  12817. isRandomBattle(battle) {
  12818. return this.isRandomPack(battle.attackers) || this.isRandomPack(battle.defenders[0]);
  12819. }
  12820.  
  12821. async updateHeroesPack(enemieHeroes) {
  12822. const packs = [{id:1,args:{userId:-830021,heroes:[63,13,9,48,1],pet:6006,favor:{1:6004,9:6005,13:6002,48:6e3,63:6009}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6022:130,8268:1,8269:1},power:198058,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:419649,intelligence:3644,physicalAttack:11481.6,strength:17049,armor:12720,dodge:17232.28,magicPenetration:22780,magicPower:55816,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6004,favorPower:11064},9:{id:9,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{335:130,336:130,337:130,338:130,6027:130,8270:1,8271:1},power:195886,star:6,runes:[43750,43750,43750,43750,43750],skins:{9:60,41:60,163:60,189:60,311:60,338:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6005,type:"hero",perks:[7,2,20],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3068,hp:227134,intelligence:19003,physicalAttack:7020.32,strength:3068,armor:19995,dodge:14644,magicPower:64780.6,magicResist:31597,modifiedSkillTier:5,skin:0,favorPetId:6005,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},48:{id:48,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{240:130,241:130,242:130,243:130,6002:130},power:190584,star:6,runes:[43750,43750,43750,43750,43750],skins:{103:60,165:60,217:60,296:60,326:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6e3,type:"hero",perks:[5,2],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:17308,hp:397737,intelligence:2888,physicalAttack:40298.32,physicalCritChance:12280,strength:3169,armor:12185,armorPenetration:20137.6,magicResist:24816,skin:0,favorPetId:6e3,favorPower:11064},63:{id:63,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{442:130,443:130,444:130,445:130,6041:130,8272:1,8273:1},power:193520,star:6,runes:[43750,43750,43750,43750,43750],skins:{341:60,350:60,351:60,352:1},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6009,type:"hero",perks:[6,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17931,hp:488832,intelligence:2737,physicalAttack:54213.6,strength:2877,armor:800,armorPenetration:32477.6,magicResist:8526,physicalCritChance:9545,modifiedSkillTier:3,skin:0,favorPetId:6009,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:2,args:{userId:-830049,heroes:[46,13,52,49,4],pet:6006,favor:{4:6001,13:6002,46:6006,49:6004,52:6003}},attackers:{4:{id:4,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{255:130,256:130,257:130,258:130,6007:130},power:189782,star:6,runes:[43750,43750,43750,43750,43750],skins:{4:60,35:60,92:60,161:60,236:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[4,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:3065,hp:482631,intelligence:3402,physicalAttack:2800,strength:17488,armor:56262.6,magicPower:51021,magicResist:36971,skin:0,favorPetId:6001,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},46:{id:46,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{230:130,231:130,232:130,233:130,6032:130},power:189653,star:6,runes:[43750,43750,43750,43750,43750],skins:{101:60,159:60,178:60,262:60,315:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[9,5,1,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2122,hp:637517,intelligence:16208,physicalAttack:50,strength:5151,armor:38507.6,magicPower:74495.6,magicResist:22237,skin:0,favorPetId:6006,favorPower:11064},49:{id:49,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{245:130,246:130,247:130,248:130,6022:130},power:193163,star:6,runes:[43750,43750,43750,43750,43750],skins:{104:60,191:60,252:60,305:60,329:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[10,1,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:17935,hp:250405,intelligence:2790,physicalAttack:40413.6,strength:2987,armor:11655,dodge:14844.28,magicResist:3175,physicalCritChance:14135,skin:0,favorPetId:6004,favorPower:11064},52:{id:52,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{310:130,311:130,312:130,313:130,6017:130},power:185075,star:6,runes:[43750,43750,43750,43750,43750],skins:{188:60,213:60,248:60,297:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6003,type:"hero",perks:[5,8,2,13,15,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:18270,hp:226207,intelligence:2620,physicalAttack:44206,strength:3260,armor:13150,armorPenetration:40301,magicPower:9957.6,magicResist:33892.6,skin:0,favorPetId:6003,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:3,args:{userId:8263225,heroes:[29,63,13,48,1],pet:6006,favor:{1:6004,13:6002,29:6006,48:6e3,63:6003}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6022:130,8268:1,8269:1},power:198058,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:419649,intelligence:3644,physicalAttack:11481.6,strength:17049,armor:12720,dodge:17232.28,magicPenetration:22780,magicPower:55816,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6004,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},29:{id:29,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{145:130,146:130,147:130,148:130,6032:130},power:189790,star:6,runes:[43750,43750,43750,43750,43750],skins:{29:60,72:60,88:60,147:60,242:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[9,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2885,hp:491431,intelligence:18331,physicalAttack:106,strength:3020,armor:37716.6,magicPower:76792.6,magicResist:31377,skin:0,favorPetId:6006,favorPower:11064},48:{id:48,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{240:130,241:130,242:130,243:130,6002:130},power:190584,star:6,runes:[43750,43750,43750,43750,43750],skins:{103:60,165:60,217:60,296:60,326:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6e3,type:"hero",perks:[5,2],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:17308,hp:397737,intelligence:2888,physicalAttack:40298.32,physicalCritChance:12280,strength:3169,armor:12185,armorPenetration:20137.6,magicResist:24816,skin:0,favorPetId:6e3,favorPower:11064},63:{id:63,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{442:130,443:130,444:130,445:130,6017:130,8272:1,8273:1},power:191031,star:6,runes:[43750,43750,43750,43750,43750],skins:{341:60,350:60,351:60,352:1},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6003,type:"hero",perks:[6,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17931,hp:488832,intelligence:2737,physicalAttack:44256,strength:2877,armor:800,armorPenetration:22520,magicPower:9957.6,magicResist:18483.6,physicalCritChance:9545,modifiedSkillTier:3,skin:0,favorPetId:6003,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:4,args:{userId:8263247,heroes:[55,13,40,51,1],pet:6006,favor:{1:6007,13:6002,40:6004,51:6006,55:6001}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6035:130,8268:1,8269:1},power:195170,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6007,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:419649,intelligence:3644,physicalAttack:1524,strength:17049,armor:22677.6,dodge:14245,magicPenetration:22780,magicPower:65773.6,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6007,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},40:{id:40,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{200:130,201:130,202:130,203:130,6022:130,8244:1,8245:1},power:192541,star:6,runes:[43750,43750,43750,43750,43750],skins:{53:60,89:60,129:60,168:60,314:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[5,9,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17540,hp:343191,intelligence:2805,physicalAttack:48430.6,strength:2976,armor:24410,dodge:15732.28,magicResist:17633,modifiedSkillTier:3,skin:0,favorPetId:6004,favorPower:11064},51:{id:51,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{305:130,306:130,307:130,308:130,6032:130},power:190005,star:6,runes:[43750,43750,43750,43750,43750],skins:{181:60,219:60,260:60,290:60,334:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[5,9,1,12],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2526,hp:438205,intelligence:18851,physicalAttack:50,strength:2921,armor:39442.6,magicPower:88978.6,magicResist:22960,skin:0,favorPetId:6006,favorPower:11064},55:{id:55,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{325:130,326:130,327:130,328:130,6007:130},power:190529,star:6,runes:[43750,43750,43750,43750,43750],skins:{239:60,278:60,309:60,327:60,346:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[7,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2631,hp:499591,intelligence:19438,physicalAttack:50,strength:3286,armor:32892.6,armorPenetration:36870,magicPower:60704,magicResist:10010,skin:0,favorPetId:6001,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:5,args:{userId:8263303,heroes:[31,29,13,40,1],pet:6004,favor:{1:6001,13:6007,29:6002,31:6006,40:6004}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6007:130,8268:1,8269:1},power:195170,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:519225,intelligence:3644,physicalAttack:1524,strength:17049,armor:22677.6,dodge:14245,magicPenetration:22780,magicPower:55816,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6001,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6035:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6007,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:29017.6,magicPenetration:48181,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6007,favorPower:11064},29:{id:29,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{145:130,146:130,147:130,148:130,6012:130},power:189790,star:6,runes:[43750,43750,43750,43750,43750],skins:{29:60,72:60,88:60,147:60,242:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[9,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2885,hp:491431,intelligence:18331,physicalAttack:106,strength:3020,armor:27759,magicPenetration:9957.6,magicPower:76792.6,magicResist:31377,skin:0,favorPetId:6002,favorPower:11064},31:{id:31,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{155:130,156:130,157:130,158:130,6032:130},power:190305,star:6,runes:[43750,43750,43750,43750,43750],skins:{44:60,94:60,133:60,200:60,295:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[9,5,2,20],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2781,dodge:12620,hp:374484,intelligence:18945,physicalAttack:78,strength:2916,armor:28049.6,magicPower:67686.6,magicResist:15252,skin:0,favorPetId:6006,favorPower:11064},40:{id:40,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{200:130,201:130,202:130,203:130,6022:130,8244:1,8245:1},power:192541,star:6,runes:[43750,43750,43750,43750,43750],skins:{53:60,89:60,129:60,168:60,314:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[5,9,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17540,hp:343191,intelligence:2805,physicalAttack:48430.6,strength:2976,armor:24410,dodge:15732.28,magicResist:17633,modifiedSkillTier:3,skin:0,favorPetId:6004,favorPower:11064},6004:{id:6004,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6020:130,6021:130},power:181943,type:"pet",perks:[5],name:null,armorPenetration:47911,intelligence:11064,strength:12360}}},{id:6,args:{userId:8263317,heroes:[62,13,9,56,61],pet:6003,favor:{9:6004,13:6002,56:6006,61:6001,62:6003}},attackers:{9:{id:9,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{335:130,336:130,337:130,338:130,6022:130,8270:1,8271:1},power:198525,star:6,runes:[43750,43750,43750,43750,43750],skins:{9:60,41:60,163:60,189:60,311:60,338:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[7,2,20],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3068,hp:227134,intelligence:19003,physicalAttack:10007.6,strength:3068,armor:19995,dodge:17631.28,magicPower:54823,magicResist:31597,modifiedSkillTier:5,skin:0,favorPetId:6004,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},56:{id:56,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{376:130,377:130,378:130,379:130,6032:130},power:184420,star:6,runes:[43750,43750,43750,43750,43750],skins:{264:60,279:60,294:60,321:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[5,7,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2791,hp:235111,intelligence:18813,physicalAttack:50,strength:2656,armor:22982.6,magicPenetration:48159,magicPower:75598.6,magicResist:13990,skin:0,favorPetId:6006,favorPower:11064},61:{id:61,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{411:130,412:130,413:130,414:130,6007:130},power:184868,star:6,runes:[43750,43750,43750,43750,43750],skins:{302:60,306:60,323:60,340:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[4,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2545,hp:466176,intelligence:3320,physicalAttack:34305,strength:18309,armor:31077.6,magicResist:24101,physicalCritChance:9009,skin:0,favorPetId:6001,favorPower:11064},62:{id:62,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{437:130,438:130,439:130,440:130,6017:130},power:173991,star:6,runes:[43750,43750,43750,43750,43750],skins:{320:60,343:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6003,type:"hero",perks:[8,7,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2530,hp:276010,intelligence:19245,physicalAttack:50,strength:3543,armor:12890,magicPenetration:23658,magicPower:80966.6,magicResist:12447.6,skin:0,favorPetId:6003,favorPower:11064},6003:{id:6003,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6015:130,6016:130},power:181943,type:"pet",perks:[8],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:7,args:{userId:8263335,heroes:[32,29,13,43,1],pet:6006,favor:{1:6004,13:6008,29:6006,32:6002,43:6007}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6022:130,8268:1,8269:1},power:198058,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:419649,intelligence:3644,physicalAttack:11481.6,strength:17049,armor:12720,dodge:17232.28,magicPenetration:22780,magicPower:55816,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6004,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6038:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6008,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:29017.6,magicPenetration:48181,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6008,favorPower:11064},29:{id:29,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{145:130,146:130,147:130,148:130,6032:130},power:189790,star:6,runes:[43750,43750,43750,43750,43750],skins:{29:60,72:60,88:60,147:60,242:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[9,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2885,hp:491431,intelligence:18331,physicalAttack:106,strength:3020,armor:37716.6,magicPower:76792.6,magicResist:31377,skin:0,favorPetId:6006,favorPower:11064},32:{id:32,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{160:130,161:130,162:130,163:130,6012:130},power:189956,star:6,runes:[43750,43750,43750,43750,43750],skins:{45:60,73:60,81:60,135:60,212:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2815,hp:551066,intelligence:18800,physicalAttack:50,strength:2810,armor:19040,magicPenetration:9957.6,magicPower:89495.6,magicResist:20805,skin:0,favorPetId:6002,favorPower:11064},43:{id:43,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{215:130,216:130,217:130,218:130,6035:130},power:189593,star:6,runes:[43750,43750,43750,43750,43750],skins:{98:60,130:60,169:60,201:60,304:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6007,type:"hero",perks:[7,9,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2447,hp:265217,intelligence:18758,physicalAttack:50,strength:2842,armor:18637.6,magicPenetration:52439,magicPower:75465.6,magicResist:22695,skin:0,favorPetId:6007,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}}];
  12823.  
  12824. const bestPack = {
  12825. pack: packs[0],
  12826. countWin: 0,
  12827. }
  12828.  
  12829. for (const pack of packs) {
  12830. const attackers = pack.attackers;
  12831. const battle = {
  12832. attackers,
  12833. defenders: [enemieHeroes],
  12834. type: 'brawl',
  12835. };
  12836.  
  12837. let countWinBattles = 0;
  12838. let countTestBattle = 10;
  12839. for (let i = 0; i < countTestBattle; i++) {
  12840. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12841. const result = await Calc(battle);
  12842. if (result.result.win) {
  12843. countWinBattles++;
  12844. }
  12845. if (countWinBattles > 7) {
  12846. console.log(pack)
  12847. return pack.args;
  12848. }
  12849. }
  12850. if (countWinBattles > bestPack.countWin) {
  12851. bestPack.countWin = countWinBattles;
  12852. bestPack.pack = pack.args;
  12853. }
  12854. }
  12855.  
  12856. console.log(bestPack);
  12857. return bestPack.pack;
  12858. }
  12859.  
  12860. async questFarm() {
  12861. const calls = [this.callBrawlQuestFarm];
  12862. const result = await Send(JSON.stringify({ calls }));
  12863. return result.results[0].result.response;
  12864. }
  12865.  
  12866. async getBrawlInfo() {
  12867. const data = await Send(JSON.stringify({
  12868. calls: [
  12869. this.callUserGetInfo,
  12870. this.callBrawlQuestGetInfo,
  12871. this.callBrawlFindEnemies,
  12872. this.callTeamGetMaxUpgrade,
  12873. this.callBrawlGetInfo,
  12874. ]
  12875. }));
  12876.  
  12877. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  12878.  
  12879. const maxUpgrade = data.results[3].result.response;
  12880. const maxHero = Object.values(maxUpgrade.hero);
  12881. const maxTitan = Object.values(maxUpgrade.titan);
  12882. const maxPet = Object.values(maxUpgrade.pet);
  12883. this.maxUpgrade = [...maxHero, ...maxPet, ...maxTitan];
  12884.  
  12885. this.info = data.results[4].result.response;
  12886. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  12887. return {
  12888. attempts: attempts.amount,
  12889. questInfo: data.results[1].result.response,
  12890. findEnemies: data.results[2].result.response,
  12891. }
  12892. }
  12893.  
  12894. /**
  12895. * Carrying out a fight
  12896. *
  12897. * Проведение боя
  12898. */
  12899. async battle(userId) {
  12900. this.stats.count++;
  12901. const battle = await this.startBattle(userId, this.args);
  12902. const result = await Calc(battle);
  12903. console.log(result.result);
  12904. if (result.result.win) {
  12905. this.stats.win++;
  12906. } else {
  12907. this.stats.loss++;
  12908. if (!this.info.boughtEndlessLivesToday) {
  12909. this.attempts--;
  12910. }
  12911. }
  12912. return await this.endBattle(result);
  12913. // return await this.cancelBattle(result);
  12914. }
  12915.  
  12916. /**
  12917. * Starts a fight
  12918. *
  12919. * Начинает бой
  12920. */
  12921. async startBattle(userId, args) {
  12922. const call = {
  12923. name: "brawl_startBattle",
  12924. args,
  12925. ident: "brawl_startBattle"
  12926. }
  12927. call.args.userId = userId;
  12928. const calls = [call];
  12929. const result = await Send(JSON.stringify({ calls }));
  12930. return result.results[0].result.response;
  12931. }
  12932.  
  12933. cancelBattle(battle) {
  12934. const fixBattle = function (heroes) {
  12935. for (const ids in heroes) {
  12936. const hero = heroes[ids];
  12937. hero.energy = random(1, 999);
  12938. if (hero.hp > 0) {
  12939. hero.hp = random(1, hero.hp);
  12940. }
  12941. }
  12942. }
  12943. fixBattle(battle.progress[0].attackers.heroes);
  12944. fixBattle(battle.progress[0].defenders.heroes);
  12945. return this.endBattle(battle);
  12946. }
  12947.  
  12948. /**
  12949. * Ends the fight
  12950. *
  12951. * Заканчивает бой
  12952. */
  12953. async endBattle(battle) {
  12954. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  12955. const calls = [{
  12956. name: "brawl_endBattle",
  12957. args: {
  12958. result: battle.result,
  12959. progress: battle.progress
  12960. },
  12961. ident: "brawl_endBattle"
  12962. },
  12963. this.callBrawlQuestGetInfo,
  12964. this.callBrawlFindEnemies,
  12965. ];
  12966. const result = await Send(JSON.stringify({ calls }));
  12967. return result.results;
  12968. }
  12969.  
  12970. end(endReason) {
  12971. setIsCancalBattle(true);
  12972. isBrawlsAutoStart = false;
  12973. setProgress(endReason, true);
  12974. console.log(endReason);
  12975. this.resolve();
  12976. }
  12977. }
  12978.  
  12979. this.HWHClasses.executeBrawls = executeBrawls;
  12980.  
  12981. })();
  12982.  
  12983. /**
  12984. * TODO:
  12985. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  12986. * Добивание на арене титанов
  12987. * Закрытие окошек по Esc +-
  12988. * Починить работу скрипта на уровне команды ниже 10 +-
  12989. * Написать номальную синхронизацию
  12990. * Запрет сбора квестов и отправки экспеиций в промежуток между локальным обновлением и глобальным обновлением дня
  12991. * Улучшение боев
  12992. */