HeroWarsHelper

Automation of actions for the game Hero Wars

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

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @name:ru HeroWarsHelper
  5. // @namespace HeroWarsHelper
  6. // @version 2.327
  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. return header;
  4800. }
  4801.  
  4802. addButton(btn, main = this.mainMenu) {
  4803. const { name, onClick, title, color, dot, classes = [], isCombine } = btn;
  4804. const button = document.createElement('div');
  4805. if (!isCombine) {
  4806. classes.push('scriptMenu_mainButton');
  4807. }
  4808. button.classList.add('scriptMenu_button', this.getButtonColor(color), ...classes);
  4809. button.title = title;
  4810. button.addEventListener('click', onClick);
  4811. main.appendChild(button);
  4812.  
  4813. const buttonText = document.createElement('div');
  4814. buttonText.classList.add('scriptMenu_buttonText');
  4815. buttonText.innerText = name;
  4816. button.appendChild(buttonText);
  4817.  
  4818. if (dot) {
  4819. const dotAtention = document.createElement('div');
  4820. dotAtention.classList.add('scriptMenu_dot');
  4821. dotAtention.title = dot;
  4822. button.appendChild(dotAtention);
  4823. }
  4824.  
  4825. this.buttons.push(button);
  4826. return button;
  4827. }
  4828.  
  4829. addCombinedButton(buttonList, main = this.mainMenu) {
  4830. const buttonGroup = document.createElement('div');
  4831. buttonGroup.classList.add('scriptMenu_buttonGroup');
  4832. let count = 0;
  4833.  
  4834. for (const btn of buttonList) {
  4835. btn.isCombine = true;
  4836. btn.classes ??= [];
  4837. if (count === 0) {
  4838. btn.classes.push('scriptMenu_combineButtonLeft');
  4839. } else if (count === buttonList.length - 1) {
  4840. btn.classes.push('scriptMenu_combineButtonRight');
  4841. } else {
  4842. btn.classes.push('scriptMenu_combineButtonCenter');
  4843. }
  4844. this.addButton(btn, buttonGroup);
  4845. count++;
  4846. }
  4847.  
  4848. const dotAtention = document.createElement('div');
  4849. dotAtention.classList.add('scriptMenu_dot');
  4850. buttonGroup.appendChild(dotAtention);
  4851.  
  4852. main.appendChild(buttonGroup);
  4853. return buttonGroup;
  4854. }
  4855.  
  4856. addCheckbox(label, title, main = this.mainMenu) {
  4857. const divCheckbox = document.createElement('div');
  4858. divCheckbox.classList.add('scriptMenu_divInput');
  4859. divCheckbox.title = title;
  4860. main.appendChild(divCheckbox);
  4861.  
  4862. const checkbox = document.createElement('input');
  4863. checkbox.type = 'checkbox';
  4864. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  4865. checkbox.classList.add('scriptMenu_checkbox');
  4866. divCheckbox.appendChild(checkbox);
  4867.  
  4868. const checkboxLabel = document.createElement('label');
  4869. checkboxLabel.innerText = label;
  4870. checkboxLabel.setAttribute('for', checkbox.id);
  4871. divCheckbox.appendChild(checkboxLabel);
  4872.  
  4873. this.checkboxes.push(checkbox);
  4874. return checkbox;
  4875. }
  4876.  
  4877. addInputText(title, placeholder, main = this.mainMenu) {
  4878. const divInputText = document.createElement('div');
  4879. divInputText.classList.add('scriptMenu_divInputText');
  4880. divInputText.title = title;
  4881. main.appendChild(divInputText);
  4882.  
  4883. const newInputText = document.createElement('input');
  4884. newInputText.type = 'text';
  4885. if (placeholder) {
  4886. newInputText.placeholder = placeholder;
  4887. }
  4888. newInputText.classList.add('scriptMenu_InputText');
  4889. divInputText.appendChild(newInputText);
  4890. return newInputText;
  4891. }
  4892.  
  4893. addDetails(summaryText, name = null) {
  4894. const details = document.createElement('details');
  4895. details.classList.add('scriptMenu_Details');
  4896. this.mainMenu.appendChild(details);
  4897.  
  4898. const summary = document.createElement('summary');
  4899. summary.classList.add('scriptMenu_Summary');
  4900. summary.innerText = summaryText;
  4901. if (name) {
  4902. const self = this;
  4903. details.open = this.option.showDetails[name];
  4904. details.dataset.name = name;
  4905. summary.addEventListener('click', () => {
  4906. self.option.showDetails[details.dataset.name] = !details.open;
  4907. self.saveShowDetails(self.option.showDetails);
  4908. });
  4909. }
  4910. details.appendChild(summary);
  4911.  
  4912. return details;
  4913. }
  4914.  
  4915. saveShowDetails(value) {
  4916. try {
  4917. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  4918. } catch (e) {
  4919. console.log('¯\\_(ツ)_/¯');
  4920. }
  4921. }
  4922.  
  4923. loadShowDetails() {
  4924. let showDetails = null;
  4925. try {
  4926. showDetails = localStorage.getItem('scriptMenu_showDetails');
  4927. } catch (e) {
  4928. console.log('¯\\_(ツ)_/¯');
  4929. }
  4930.  
  4931. if (!showDetails) {
  4932. return {};
  4933. }
  4934.  
  4935. try {
  4936. showDetails = JSON.parse(showDetails);
  4937. } catch (e) {
  4938. return {};
  4939. }
  4940.  
  4941. return showDetails;
  4942. }
  4943. }
  4944.  
  4945. const scriptMenu = new ScriptMenu();
  4946.  
  4947. /**
  4948. * Пример использования
  4949. const scriptMenu = new ScriptMenu();
  4950. scriptMenu.init();
  4951. scriptMenu.addHeader('v1.508');
  4952. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  4953. scriptMenu.addButton({
  4954. text: 'Запуск!',
  4955. onClick: () => console.log('click'),
  4956. title: 'подсказака',
  4957. });
  4958. scriptMenu.addInputText('input подсказака');
  4959. */
  4960.  
  4961. /**
  4962. * Game Library
  4963. *
  4964. * Игровая библиотека
  4965. */
  4966. class Library {
  4967. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  4968.  
  4969. constructor() {
  4970. if (!Library.instance) {
  4971. Library.instance = this;
  4972. }
  4973.  
  4974. return Library.instance;
  4975. }
  4976.  
  4977. async load() {
  4978. try {
  4979. await this.getUrlLib();
  4980. console.log(this.defaultLibUrl);
  4981. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  4982. } catch (error) {
  4983. console.error('Не удалось загрузить библиотеку', error)
  4984. }
  4985. }
  4986.  
  4987. async getUrlLib() {
  4988. try {
  4989. const db = new Database('hw_cache', 'cache');
  4990. await db.open();
  4991. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  4992. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  4993. } catch(e) {}
  4994. }
  4995.  
  4996. getData(id) {
  4997. return this.data[id];
  4998. }
  4999.  
  5000. setData(data) {
  5001. this.data = data;
  5002. }
  5003. }
  5004.  
  5005. this.lib = new Library();
  5006. /**
  5007. * Database
  5008. *
  5009. * База данных
  5010. */
  5011. class Database {
  5012. constructor(dbName, storeName) {
  5013. this.dbName = dbName;
  5014. this.storeName = storeName;
  5015. this.db = null;
  5016. }
  5017.  
  5018. async open() {
  5019. return new Promise((resolve, reject) => {
  5020. const request = indexedDB.open(this.dbName);
  5021.  
  5022. request.onerror = () => {
  5023. reject(new Error(`Failed to open database ${this.dbName}`));
  5024. };
  5025.  
  5026. request.onsuccess = () => {
  5027. this.db = request.result;
  5028. resolve();
  5029. };
  5030.  
  5031. request.onupgradeneeded = (event) => {
  5032. const db = event.target.result;
  5033. if (!db.objectStoreNames.contains(this.storeName)) {
  5034. db.createObjectStore(this.storeName);
  5035. }
  5036. };
  5037. });
  5038. }
  5039.  
  5040. async set(key, value) {
  5041. return new Promise((resolve, reject) => {
  5042. const transaction = this.db.transaction([this.storeName], 'readwrite');
  5043. const store = transaction.objectStore(this.storeName);
  5044. const request = store.put(value, key);
  5045.  
  5046. request.onerror = () => {
  5047. reject(new Error(`Failed to save value with key ${key}`));
  5048. };
  5049.  
  5050. request.onsuccess = () => {
  5051. resolve();
  5052. };
  5053. });
  5054. }
  5055.  
  5056. async get(key, def) {
  5057. return new Promise((resolve, reject) => {
  5058. const transaction = this.db.transaction([this.storeName], 'readonly');
  5059. const store = transaction.objectStore(this.storeName);
  5060. const request = store.get(key);
  5061.  
  5062. request.onerror = () => {
  5063. resolve(def);
  5064. };
  5065.  
  5066. request.onsuccess = () => {
  5067. resolve(request.result);
  5068. };
  5069. });
  5070. }
  5071.  
  5072. async delete(key) {
  5073. return new Promise((resolve, reject) => {
  5074. const transaction = this.db.transaction([this.storeName], 'readwrite');
  5075. const store = transaction.objectStore(this.storeName);
  5076. const request = store.delete(key);
  5077.  
  5078. request.onerror = () => {
  5079. reject(new Error(`Failed to delete value with key ${key}`));
  5080. };
  5081.  
  5082. request.onsuccess = () => {
  5083. resolve();
  5084. };
  5085. });
  5086. }
  5087. }
  5088.  
  5089. /**
  5090. * Returns the stored value
  5091. *
  5092. * Возвращает сохраненное значение
  5093. */
  5094. function getSaveVal(saveName, def) {
  5095. const result = storage.get(saveName, def);
  5096. return result;
  5097. }
  5098. this.HWHFuncs.getSaveVal = getSaveVal;
  5099.  
  5100. /**
  5101. * Stores value
  5102. *
  5103. * Сохраняет значение
  5104. */
  5105. function setSaveVal(saveName, value) {
  5106. storage.set(saveName, value);
  5107. }
  5108. this.HWHFuncs.setSaveVal = setSaveVal;
  5109.  
  5110. /**
  5111. * Database initialization
  5112. *
  5113. * Инициализация базы данных
  5114. */
  5115. const db = new Database(GM_info.script.name, 'settings');
  5116.  
  5117. /**
  5118. * Data store
  5119. *
  5120. * Хранилище данных
  5121. */
  5122. const storage = {
  5123. userId: 0,
  5124. /**
  5125. * Default values
  5126. *
  5127. * Значения по умолчанию
  5128. */
  5129. values: [
  5130. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  5131. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  5132. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  5133. name: GM_info.script.name,
  5134. get: function (key, def) {
  5135. if (key in this.values) {
  5136. return this.values[key];
  5137. }
  5138. return def;
  5139. },
  5140. set: function (key, value) {
  5141. this.values[key] = value;
  5142. db.set(this.userId, this.values).catch(
  5143. e => null
  5144. );
  5145. localStorage[this.name + ':' + key] = value;
  5146. },
  5147. delete: function (key) {
  5148. delete this.values[key];
  5149. db.set(this.userId, this.values);
  5150. delete localStorage[this.name + ':' + key];
  5151. }
  5152. }
  5153.  
  5154. /**
  5155. * Returns all keys from localStorage that start with prefix (for migration)
  5156. *
  5157. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  5158. */
  5159. function getAllValuesStartingWith(prefix) {
  5160. const values = [];
  5161. for (let i = 0; i < localStorage.length; i++) {
  5162. const key = localStorage.key(i);
  5163. if (key.startsWith(prefix)) {
  5164. const val = localStorage.getItem(key);
  5165. const keyValue = key.split(':')[1];
  5166. values.push({ key: keyValue, val });
  5167. }
  5168. }
  5169. return values;
  5170. }
  5171.  
  5172. /**
  5173. * Opens or migrates to a database
  5174. *
  5175. * Открывает или мигрирует в базу данных
  5176. */
  5177. async function openOrMigrateDatabase(userId) {
  5178. storage.userId = userId;
  5179. try {
  5180. await db.open();
  5181. } catch(e) {
  5182. return;
  5183. }
  5184. let settings = await db.get(userId, false);
  5185.  
  5186. if (settings) {
  5187. storage.values = settings;
  5188. return;
  5189. }
  5190.  
  5191. const values = getAllValuesStartingWith(GM_info.script.name);
  5192. for (const value of values) {
  5193. let val = null;
  5194. try {
  5195. val = JSON.parse(value.val);
  5196. } catch {
  5197. break;
  5198. }
  5199. storage.values[value.key] = val;
  5200. }
  5201. await db.set(userId, storage.values);
  5202. }
  5203.  
  5204. class ZingerYWebsiteAPI {
  5205. /**
  5206. * Class for interaction with the API of the zingery.ru website
  5207. * Intended only for use with the HeroWarsHelper script:
  5208. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  5209. * Copyright ZingerY
  5210. */
  5211. url = 'https://zingery.ru/heroes/';
  5212. // YWJzb2x1dGVseSB1c2VsZXNzIGxpbmU=
  5213. constructor(urn, env, data = {}) {
  5214. this.urn = urn;
  5215. this.fd = {
  5216. now: Date.now(),
  5217. fp: this.constructor.toString().replaceAll(/\s/g, ''),
  5218. env: env.callee.toString().replaceAll(/\s/g, ''),
  5219. info: (({ name, version, author }) => [name, version, author])(GM_info.script),
  5220. ...data,
  5221. };
  5222. }
  5223.  
  5224. sign() {
  5225. return md5([...this.fd.info, ~(this.fd.now % 1e3), this.fd.fp].join('_'));
  5226. }
  5227.  
  5228. encode(data) {
  5229. return btoa(encodeURIComponent(JSON.stringify(data)));
  5230. }
  5231.  
  5232. decode(data) {
  5233. return JSON.parse(decodeURIComponent(atob(data)));
  5234. }
  5235.  
  5236. headers() {
  5237. return {
  5238. 'X-Request-Signature': this.sign(),
  5239. 'X-Script-Name': GM_info.script.name,
  5240. 'X-Script-Version': GM_info.script.version,
  5241. 'X-Script-Author': GM_info.script.author,
  5242. 'X-Script-ZingerY': 42,
  5243. };
  5244. }
  5245.  
  5246. async request() {
  5247. try {
  5248. const response = await fetch(this.url + this.urn, {
  5249. method: 'POST',
  5250. headers: this.headers(),
  5251. body: this.encode(this.fd),
  5252. });
  5253. const text = await response.text();
  5254. return this.decode(text);
  5255. } catch (e) {
  5256. console.error(e);
  5257. return [];
  5258. }
  5259. }
  5260. /**
  5261. * Класс для взаимодействия с API сайта zingery.ru
  5262. * Предназначен только для использования со скриптом HeroWarsHelper:
  5263. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  5264. * Copyright ZingerY
  5265. */
  5266. }
  5267.  
  5268. /**
  5269. * Sending expeditions
  5270. *
  5271. * Отправка экспедиций
  5272. */
  5273. function checkExpedition() {
  5274. const { Expedition } = HWHClasses;
  5275. return new Promise((resolve, reject) => {
  5276. const expedition = new Expedition(resolve, reject);
  5277. expedition.start();
  5278. });
  5279. }
  5280.  
  5281. class Expedition {
  5282. checkExpedInfo = {
  5283. calls: [
  5284. {
  5285. name: 'expeditionGet',
  5286. args: {},
  5287. ident: 'expeditionGet',
  5288. },
  5289. {
  5290. name: 'heroGetAll',
  5291. args: {},
  5292. ident: 'heroGetAll',
  5293. },
  5294. ],
  5295. };
  5296.  
  5297. constructor(resolve, reject) {
  5298. this.resolve = resolve;
  5299. this.reject = reject;
  5300. }
  5301.  
  5302. async start() {
  5303. const data = await Send(JSON.stringify(this.checkExpedInfo));
  5304.  
  5305. const expedInfo = data.results[0].result.response;
  5306. const dataHeroes = data.results[1].result.response;
  5307. const dataExped = { useHeroes: [], exped: [] };
  5308. const calls = [];
  5309.  
  5310. /**
  5311. * Adding expeditions to collect
  5312. * Добавляем экспедиции для сбора
  5313. */
  5314. let countGet = 0;
  5315. for (var n in expedInfo) {
  5316. const exped = expedInfo[n];
  5317. const dateNow = Date.now() / 1000;
  5318. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  5319. countGet++;
  5320. calls.push({
  5321. name: 'expeditionFarm',
  5322. args: { expeditionId: exped.id },
  5323. ident: 'expeditionFarm_' + exped.id,
  5324. });
  5325. } else {
  5326. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  5327. }
  5328. if (exped.status == 1) {
  5329. dataExped.exped.push({ id: exped.id, power: exped.power });
  5330. }
  5331. }
  5332. dataExped.exped = dataExped.exped.sort((a, b) => b.power - a.power);
  5333.  
  5334. /**
  5335. * Putting together a list of heroes
  5336. * Собираем список героев
  5337. */
  5338. const heroesArr = [];
  5339. for (let n in dataHeroes) {
  5340. const hero = dataHeroes[n];
  5341. if (hero.power > 0 && !dataExped.useHeroes.includes(hero.id)) {
  5342. let heroPower = hero.power;
  5343. // Лара Крофт * 3
  5344. if (hero.id == 63 && hero.color >= 16) {
  5345. heroPower *= 3;
  5346. }
  5347. heroesArr.push({ id: hero.id, power: heroPower });
  5348. }
  5349. }
  5350.  
  5351. /**
  5352. * Adding expeditions to send
  5353. * Добавляем экспедиции для отправки
  5354. */
  5355. let countSend = 0;
  5356. heroesArr.sort((a, b) => a.power - b.power);
  5357. for (const exped of dataExped.exped) {
  5358. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  5359. if (heroesIds && heroesIds.length > 4) {
  5360. for (let q in heroesArr) {
  5361. if (heroesIds.includes(heroesArr[q].id)) {
  5362. delete heroesArr[q];
  5363. }
  5364. }
  5365. countSend++;
  5366. calls.push({
  5367. name: 'expeditionSendHeroes',
  5368. args: {
  5369. expeditionId: exped.id,
  5370. heroes: heroesIds,
  5371. },
  5372. ident: 'expeditionSendHeroes_' + exped.id,
  5373. });
  5374. }
  5375. }
  5376.  
  5377. if (calls.length) {
  5378. await Send({ calls });
  5379. this.end(I18N('EXPEDITIONS_SENT', {countGet, countSend}));
  5380. return;
  5381. }
  5382.  
  5383. this.end(I18N('EXPEDITIONS_NOTHING'));
  5384. }
  5385.  
  5386. /**
  5387. * Selection of heroes for expeditions
  5388. *
  5389. * Подбор героев для экспедиций
  5390. */
  5391. selectionHeroes(heroes, power) {
  5392. const resultHeroers = [];
  5393. const heroesIds = [];
  5394. for (let q = 0; q < 5; q++) {
  5395. for (let i in heroes) {
  5396. let hero = heroes[i];
  5397. if (heroesIds.includes(hero.id)) {
  5398. continue;
  5399. }
  5400.  
  5401. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5402. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  5403. if (hero.power > need) {
  5404. resultHeroers.push(hero);
  5405. heroesIds.push(hero.id);
  5406. break;
  5407. }
  5408. }
  5409. }
  5410.  
  5411. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5412. if (summ < power) {
  5413. return false;
  5414. }
  5415. return heroesIds;
  5416. }
  5417.  
  5418. /**
  5419. * Ends expedition script
  5420. *
  5421. * Завершает скрипт экспедиции
  5422. */
  5423. end(msg) {
  5424. setProgress(msg, true);
  5425. this.resolve();
  5426. }
  5427. }
  5428.  
  5429. this.HWHClasses.Expedition = Expedition;
  5430.  
  5431. /**
  5432. * Walkthrough of the dungeon
  5433. *
  5434. * Прохождение подземелья
  5435. */
  5436. function testDungeon() {
  5437. const { executeDungeon } = HWHClasses;
  5438. return new Promise((resolve, reject) => {
  5439. const dung = new executeDungeon(resolve, reject);
  5440. const titanit = getInput('countTitanit');
  5441. dung.start(titanit);
  5442. });
  5443. }
  5444.  
  5445. /**
  5446. * Walkthrough of the dungeon
  5447. *
  5448. * Прохождение подземелья
  5449. */
  5450. function executeDungeon(resolve, reject) {
  5451. dungeonActivity = 0;
  5452. maxDungeonActivity = 150;
  5453.  
  5454. titanGetAll = [];
  5455.  
  5456. teams = {
  5457. heroes: [],
  5458. earth: [],
  5459. fire: [],
  5460. neutral: [],
  5461. water: [],
  5462. }
  5463.  
  5464. titanStats = [];
  5465.  
  5466. titansStates = {};
  5467.  
  5468. let talentMsg = '';
  5469. let talentMsgReward = '';
  5470.  
  5471. callsExecuteDungeon = {
  5472. calls: [{
  5473. name: "dungeonGetInfo",
  5474. args: {},
  5475. ident: "dungeonGetInfo"
  5476. }, {
  5477. name: "teamGetAll",
  5478. args: {},
  5479. ident: "teamGetAll"
  5480. }, {
  5481. name: "teamGetFavor",
  5482. args: {},
  5483. ident: "teamGetFavor"
  5484. }, {
  5485. name: "clanGetInfo",
  5486. args: {},
  5487. ident: "clanGetInfo"
  5488. }, {
  5489. name: "titanGetAll",
  5490. args: {},
  5491. ident: "titanGetAll"
  5492. }, {
  5493. name: "inventoryGet",
  5494. args: {},
  5495. ident: "inventoryGet"
  5496. }]
  5497. }
  5498.  
  5499. this.start = function(titanit) {
  5500. maxDungeonActivity = titanit || getInput('countTitanit');
  5501. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  5502. }
  5503.  
  5504. /**
  5505. * Getting data on the dungeon
  5506. *
  5507. * Получаем данные по подземелью
  5508. */
  5509. function startDungeon(e) {
  5510. res = e.results;
  5511. dungeonGetInfo = res[0].result.response;
  5512. if (!dungeonGetInfo) {
  5513. endDungeon('noDungeon', res);
  5514. return;
  5515. }
  5516. teamGetAll = res[1].result.response;
  5517. teamGetFavor = res[2].result.response;
  5518. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  5519. titanGetAll = Object.values(res[4].result.response);
  5520. countPredictionCard = res[5].result.response.consumable[81];
  5521.  
  5522. teams.hero = {
  5523. favor: teamGetFavor.dungeon_hero,
  5524. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  5525. teamNum: 0,
  5526. }
  5527. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  5528. if (heroPet) {
  5529. teams.hero.pet = heroPet;
  5530. }
  5531.  
  5532. teams.neutral = {
  5533. favor: {},
  5534. heroes: getTitanTeam(titanGetAll, 'neutral'),
  5535. teamNum: 0,
  5536. };
  5537. teams.water = {
  5538. favor: {},
  5539. heroes: getTitanTeam(titanGetAll, 'water'),
  5540. teamNum: 0,
  5541. };
  5542. teams.fire = {
  5543. favor: {},
  5544. heroes: getTitanTeam(titanGetAll, 'fire'),
  5545. teamNum: 0,
  5546. };
  5547. teams.earth = {
  5548. favor: {},
  5549. heroes: getTitanTeam(titanGetAll, 'earth'),
  5550. teamNum: 0,
  5551. };
  5552.  
  5553.  
  5554. checkFloor(dungeonGetInfo);
  5555. }
  5556.  
  5557. function getTitanTeam(titans, type) {
  5558. switch (type) {
  5559. case 'neutral':
  5560. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5561. case 'water':
  5562. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  5563. case 'fire':
  5564. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  5565. case 'earth':
  5566. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  5567. }
  5568. }
  5569.  
  5570. function getNeutralTeam() {
  5571. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5572. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5573. }
  5574.  
  5575. function fixTitanTeam(titans) {
  5576. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  5577. return titans;
  5578. }
  5579.  
  5580. /**
  5581. * Checking the floor
  5582. *
  5583. * Проверяем этаж
  5584. */
  5585. async function checkFloor(dungeonInfo) {
  5586. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  5587. saveProgress();
  5588. return;
  5589. }
  5590. checkTalent(dungeonInfo);
  5591. // console.log(dungeonInfo, dungeonActivity);
  5592. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5593. if (dungeonActivity >= maxDungeonActivity) {
  5594. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  5595. return;
  5596. }
  5597. titansStates = dungeonInfo.states.titans;
  5598. titanStats = titanObjToArray(titansStates);
  5599. const floorChoices = dungeonInfo.floor.userData;
  5600. const floorType = dungeonInfo.floorType;
  5601. //const primeElement = dungeonInfo.elements.prime;
  5602. if (floorType == "battle") {
  5603. const calls = [];
  5604. for (let teamNum in floorChoices) {
  5605. attackerType = floorChoices[teamNum].attackerType;
  5606. const args = fixTitanTeam(teams[attackerType]);
  5607. if (attackerType == 'neutral') {
  5608. args.heroes = getNeutralTeam();
  5609. }
  5610. if (!args.heroes.length) {
  5611. continue;
  5612. }
  5613. args.teamNum = teamNum;
  5614. calls.push({
  5615. name: "dungeonStartBattle",
  5616. args,
  5617. ident: "body_" + teamNum
  5618. })
  5619. }
  5620. if (!calls.length) {
  5621. endDungeon('endDungeon', 'All Dead');
  5622. return;
  5623. }
  5624. const battleDatas = await Send(JSON.stringify({ calls }))
  5625. .then(e => e.results.map(n => n.result.response))
  5626. const battleResults = [];
  5627. for (n in battleDatas) {
  5628. battleData = battleDatas[n]
  5629. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5630. battleResults.push(await Calc(battleData).then(result => {
  5631. result.teamNum = n;
  5632. result.attackerType = floorChoices[n].attackerType;
  5633. return result;
  5634. }));
  5635. }
  5636. processingPromises(battleResults)
  5637. }
  5638. }
  5639.  
  5640. async function checkTalent(dungeonInfo) {
  5641. const talent = dungeonInfo.talent;
  5642. if (!talent) {
  5643. return;
  5644. }
  5645. const dungeonFloor = +dungeonInfo.floorNumber;
  5646. const talentFloor = +talent.floorRandValue;
  5647. let doorsAmount = 3 - talent.conditions.doorsAmount;
  5648.  
  5649. if (dungeonFloor === talentFloor && (!doorsAmount || !talent.conditions?.farmedDoors[dungeonFloor])) {
  5650. const reward = await Send({
  5651. calls: [
  5652. { name: 'heroTalent_getReward', args: { talentType: 'tmntDungeonTalent', reroll: false }, ident: 'group_0_body' },
  5653. { name: 'heroTalent_farmReward', args: { talentType: 'tmntDungeonTalent' }, ident: 'group_1_body' },
  5654. ],
  5655. }).then((e) => e.results[0].result.response);
  5656. const type = Object.keys(reward).pop();
  5657. const itemId = Object.keys(reward[type]).pop();
  5658. const count = reward[type][itemId];
  5659. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  5660. talentMsgReward += `<br> ${count} ${itemName}`;
  5661. doorsAmount++;
  5662. }
  5663. talentMsg = `<br>TMNT Talent: ${doorsAmount}/3 ${talentMsgReward}<br>`;
  5664. }
  5665.  
  5666. function processingPromises(results) {
  5667. let selectBattle = results[0];
  5668. if (results.length < 2) {
  5669. // console.log(selectBattle);
  5670. if (!selectBattle.result.win) {
  5671. endDungeon('dungeonEndBattle\n', selectBattle);
  5672. return;
  5673. }
  5674. endBattle(selectBattle);
  5675. return;
  5676. }
  5677.  
  5678. selectBattle = false;
  5679. let bestState = -1000;
  5680. for (const result of results) {
  5681. const recovery = getState(result);
  5682. if (recovery > bestState) {
  5683. bestState = recovery;
  5684. selectBattle = result
  5685. }
  5686. }
  5687. // console.log(selectBattle.teamNum, results);
  5688. if (!selectBattle || bestState <= -1000) {
  5689. endDungeon('dungeonEndBattle\n', results);
  5690. return;
  5691. }
  5692.  
  5693. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  5694. .then(endBattle);
  5695. }
  5696.  
  5697. /**
  5698. * Let's start the fight
  5699. *
  5700. * Начинаем бой
  5701. */
  5702. function startBattle(teamNum, attackerType) {
  5703. return new Promise(function (resolve, reject) {
  5704. args = fixTitanTeam(teams[attackerType]);
  5705. args.teamNum = teamNum;
  5706. if (attackerType == 'neutral') {
  5707. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5708. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5709. }
  5710. startBattleCall = {
  5711. calls: [{
  5712. name: "dungeonStartBattle",
  5713. args,
  5714. ident: "body"
  5715. }]
  5716. }
  5717. send(JSON.stringify(startBattleCall), resultBattle, {
  5718. resolve,
  5719. teamNum,
  5720. attackerType
  5721. });
  5722. });
  5723. }
  5724. /**
  5725. * Returns the result of the battle in a promise
  5726. *
  5727. * Возращает резульат боя в промис
  5728. */
  5729. function resultBattle(resultBattles, args) {
  5730. battleData = resultBattles.results[0].result.response;
  5731. battleType = "get_tower";
  5732. if (battleData.type == "dungeon_titan") {
  5733. battleType = "get_titan";
  5734. }
  5735. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5736. BattleCalc(battleData, battleType, function (result) {
  5737. result.teamNum = args.teamNum;
  5738. result.attackerType = args.attackerType;
  5739. args.resolve(result);
  5740. });
  5741. }
  5742. /**
  5743. * Finishing the fight
  5744. *
  5745. * Заканчиваем бой
  5746. */
  5747. async function endBattle(battleInfo) {
  5748. if (battleInfo.result.win) {
  5749. const args = {
  5750. result: battleInfo.result,
  5751. progress: battleInfo.progress,
  5752. }
  5753. if (countPredictionCard > 0) {
  5754. args.isRaid = true;
  5755. } else {
  5756. const timer = getTimer(battleInfo.battleTime);
  5757. console.log(timer);
  5758. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5759. }
  5760. const calls = [{
  5761. name: "dungeonEndBattle",
  5762. args,
  5763. ident: "body"
  5764. }];
  5765. lastDungeonBattleData = null;
  5766. send(JSON.stringify({ calls }), resultEndBattle);
  5767. } else {
  5768. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  5769. }
  5770. }
  5771.  
  5772. /**
  5773. * Getting and processing battle results
  5774. *
  5775. * Получаем и обрабатываем результаты боя
  5776. */
  5777. function resultEndBattle(e) {
  5778. if ('error' in e) {
  5779. popup.confirm(I18N('ERROR_MSG', {
  5780. name: e.error.name,
  5781. description: e.error.description,
  5782. }));
  5783. endDungeon('errorRequest', e);
  5784. return;
  5785. }
  5786. battleResult = e.results[0].result.response;
  5787. if ('error' in battleResult) {
  5788. endDungeon('errorBattleResult', battleResult);
  5789. return;
  5790. }
  5791. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  5792. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  5793. checkFloor(dungeonGetInfo);
  5794. }
  5795.  
  5796. /**
  5797. * Returns the coefficient of condition of the
  5798. * difference in titanium before and after the battle
  5799. *
  5800. * Возвращает коэффициент состояния титанов после боя
  5801. */
  5802. function getState(result) {
  5803. if (!result.result.win) {
  5804. return -1000;
  5805. }
  5806.  
  5807. let beforeSumFactor = 0;
  5808. const beforeTitans = result.battleData.attackers;
  5809. for (let titanId in beforeTitans) {
  5810. const titan = beforeTitans[titanId];
  5811. const state = titan.state;
  5812. let factor = 1;
  5813. if (state) {
  5814. const hp = state.hp / titan.hp;
  5815. const energy = state.energy / 1e3;
  5816. factor = hp + energy / 20
  5817. }
  5818. beforeSumFactor += factor;
  5819. }
  5820.  
  5821. let afterSumFactor = 0;
  5822. const afterTitans = result.progress[0].attackers.heroes;
  5823. for (let titanId in afterTitans) {
  5824. const titan = afterTitans[titanId];
  5825. const hp = titan.hp / beforeTitans[titanId].hp;
  5826. const energy = titan.energy / 1e3;
  5827. const factor = hp + energy / 20;
  5828. afterSumFactor += factor;
  5829. }
  5830. return afterSumFactor - beforeSumFactor;
  5831. }
  5832.  
  5833. /**
  5834. * Converts an object with IDs to an array with IDs
  5835. *
  5836. * Преобразует объект с идетификаторами в массив с идетификаторами
  5837. */
  5838. function titanObjToArray(obj) {
  5839. let titans = [];
  5840. for (let id in obj) {
  5841. obj[id].id = id;
  5842. titans.push(obj[id]);
  5843. }
  5844. return titans;
  5845. }
  5846.  
  5847. function saveProgress() {
  5848. let saveProgressCall = {
  5849. calls: [{
  5850. name: "dungeonSaveProgress",
  5851. args: {},
  5852. ident: "body"
  5853. }]
  5854. }
  5855. send(JSON.stringify(saveProgressCall), resultEndBattle);
  5856. }
  5857.  
  5858. function endDungeon(reason, info) {
  5859. console.warn(reason, info);
  5860. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  5861. resolve();
  5862. }
  5863. }
  5864.  
  5865. this.HWHClasses.executeDungeon = executeDungeon;
  5866.  
  5867. /**
  5868. * Passing the tower
  5869. *
  5870. * Прохождение башни
  5871. */
  5872. function testTower() {
  5873. const { executeTower } = HWHClasses;
  5874. return new Promise((resolve, reject) => {
  5875. tower = new executeTower(resolve, reject);
  5876. tower.start();
  5877. });
  5878. }
  5879.  
  5880. /**
  5881. * Passing the tower
  5882. *
  5883. * Прохождение башни
  5884. */
  5885. function executeTower(resolve, reject) {
  5886. lastTowerInfo = {};
  5887.  
  5888. scullCoin = 0;
  5889.  
  5890. heroGetAll = [];
  5891.  
  5892. heroesStates = {};
  5893.  
  5894. argsBattle = {
  5895. heroes: [],
  5896. favor: {},
  5897. };
  5898.  
  5899. callsExecuteTower = {
  5900. calls: [{
  5901. name: "towerGetInfo",
  5902. args: {},
  5903. ident: "towerGetInfo"
  5904. }, {
  5905. name: "teamGetAll",
  5906. args: {},
  5907. ident: "teamGetAll"
  5908. }, {
  5909. name: "teamGetFavor",
  5910. args: {},
  5911. ident: "teamGetFavor"
  5912. }, {
  5913. name: "inventoryGet",
  5914. args: {},
  5915. ident: "inventoryGet"
  5916. }, {
  5917. name: "heroGetAll",
  5918. args: {},
  5919. ident: "heroGetAll"
  5920. }]
  5921. }
  5922.  
  5923. buffIds = [
  5924. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  5925. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  5926. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  5927. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  5928. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  5929. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  5930. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  5931. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  5932. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  5933. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5934. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  5935. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5936. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  5937. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  5938. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  5939. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  5940. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  5941. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5942. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5943. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  5944. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  5945. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  5946. ]
  5947.  
  5948. this.start = function () {
  5949. send(JSON.stringify(callsExecuteTower), startTower);
  5950. }
  5951.  
  5952. /**
  5953. * Getting data on the Tower
  5954. *
  5955. * Получаем данные по башне
  5956. */
  5957. function startTower(e) {
  5958. res = e.results;
  5959. towerGetInfo = res[0].result.response;
  5960. if (!towerGetInfo) {
  5961. endTower('noTower', res);
  5962. return;
  5963. }
  5964. teamGetAll = res[1].result.response;
  5965. teamGetFavor = res[2].result.response;
  5966. inventoryGet = res[3].result.response;
  5967. heroGetAll = Object.values(res[4].result.response);
  5968.  
  5969. scullCoin = inventoryGet.coin[7] ?? 0;
  5970.  
  5971. argsBattle.favor = teamGetFavor.tower;
  5972. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5973. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  5974. if (pet) {
  5975. argsBattle.pet = pet;
  5976. }
  5977.  
  5978. checkFloor(towerGetInfo);
  5979. }
  5980.  
  5981. function fixHeroesTeam(argsBattle) {
  5982. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  5983. if (fixHeroes.length < 5) {
  5984. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  5985. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5986. Object.keys(argsBattle.favor).forEach(e => {
  5987. if (!fixHeroes.includes(+e)) {
  5988. delete argsBattle.favor[e];
  5989. }
  5990. })
  5991. }
  5992. argsBattle.heroes = fixHeroes;
  5993. return argsBattle;
  5994. }
  5995.  
  5996. /**
  5997. * Check the floor
  5998. *
  5999. * Проверяем этаж
  6000. */
  6001. function checkFloor(towerInfo) {
  6002. lastTowerInfo = towerInfo;
  6003. maySkipFloor = +towerInfo.maySkipFloor;
  6004. floorNumber = +towerInfo.floorNumber;
  6005. heroesStates = towerInfo.states.heroes;
  6006. floorInfo = towerInfo.floor;
  6007.  
  6008. /**
  6009. * Is there at least one chest open on the floor
  6010. * Открыт ли на этаже хоть один сундук
  6011. */
  6012. isOpenChest = false;
  6013. if (towerInfo.floorType == "chest") {
  6014. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  6015. }
  6016.  
  6017. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  6018. if (floorNumber > 49) {
  6019. if (isOpenChest) {
  6020. endTower('alreadyOpenChest 50 floor', floorNumber);
  6021. return;
  6022. }
  6023. }
  6024. /**
  6025. * If the chest is open and you can skip floors, then move on
  6026. * Если сундук открыт и можно скипать этажи, то переходим дальше
  6027. */
  6028. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  6029. if (floorNumber == 1) {
  6030. fullSkipTower();
  6031. return;
  6032. }
  6033. if (isOpenChest) {
  6034. nextOpenChest(floorNumber);
  6035. } else {
  6036. nextChestOpen(floorNumber);
  6037. }
  6038. return;
  6039. }
  6040.  
  6041. // console.log(towerInfo, scullCoin);
  6042. switch (towerInfo.floorType) {
  6043. case "battle":
  6044. if (floorNumber <= maySkipFloor) {
  6045. skipFloor();
  6046. return;
  6047. }
  6048. if (floorInfo.state == 2) {
  6049. nextFloor();
  6050. return;
  6051. }
  6052. startBattle().then(endBattle);
  6053. return;
  6054. case "buff":
  6055. checkBuff(towerInfo);
  6056. return;
  6057. case "chest":
  6058. openChest(floorNumber);
  6059. return;
  6060. default:
  6061. console.log('!', towerInfo.floorType, towerInfo);
  6062. break;
  6063. }
  6064. }
  6065.  
  6066. /**
  6067. * Let's start the fight
  6068. *
  6069. * Начинаем бой
  6070. */
  6071. function startBattle() {
  6072. return new Promise(function (resolve, reject) {
  6073. towerStartBattle = {
  6074. calls: [{
  6075. name: "towerStartBattle",
  6076. args: fixHeroesTeam(argsBattle),
  6077. ident: "body"
  6078. }]
  6079. }
  6080. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  6081. });
  6082. }
  6083. /**
  6084. * Returns the result of the battle in a promise
  6085. *
  6086. * Возращает резульат боя в промис
  6087. */
  6088. function resultBattle(resultBattles, resolve) {
  6089. battleData = resultBattles.results[0].result.response;
  6090. battleType = "get_tower";
  6091. BattleCalc(battleData, battleType, function (result) {
  6092. resolve(result);
  6093. });
  6094. }
  6095. /**
  6096. * Finishing the fight
  6097. *
  6098. * Заканчиваем бой
  6099. */
  6100. function endBattle(battleInfo) {
  6101. if (battleInfo.result.stars >= 3) {
  6102. endBattleCall = {
  6103. calls: [{
  6104. name: "towerEndBattle",
  6105. args: {
  6106. result: battleInfo.result,
  6107. progress: battleInfo.progress,
  6108. },
  6109. ident: "body"
  6110. }]
  6111. }
  6112. send(JSON.stringify(endBattleCall), resultEndBattle);
  6113. } else {
  6114. endTower('towerEndBattle win: false\n', battleInfo);
  6115. }
  6116. }
  6117.  
  6118. /**
  6119. * Getting and processing battle results
  6120. *
  6121. * Получаем и обрабатываем результаты боя
  6122. */
  6123. function resultEndBattle(e) {
  6124. battleResult = e.results[0].result.response;
  6125. if ('error' in battleResult) {
  6126. endTower('errorBattleResult', battleResult);
  6127. return;
  6128. }
  6129. if ('reward' in battleResult) {
  6130. scullCoin += battleResult.reward?.coin[7] ?? 0;
  6131. }
  6132. nextFloor();
  6133. }
  6134.  
  6135. function nextFloor() {
  6136. nextFloorCall = {
  6137. calls: [{
  6138. name: "towerNextFloor",
  6139. args: {},
  6140. ident: "body"
  6141. }]
  6142. }
  6143. send(JSON.stringify(nextFloorCall), checkDataFloor);
  6144. }
  6145.  
  6146. function openChest(floorNumber) {
  6147. floorNumber = floorNumber || 0;
  6148. openChestCall = {
  6149. calls: [{
  6150. name: "towerOpenChest",
  6151. args: {
  6152. num: 2
  6153. },
  6154. ident: "body"
  6155. }]
  6156. }
  6157. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  6158. }
  6159.  
  6160. function lastChest() {
  6161. endTower('openChest 50 floor', floorNumber);
  6162. }
  6163.  
  6164. function skipFloor() {
  6165. skipFloorCall = {
  6166. calls: [{
  6167. name: "towerSkipFloor",
  6168. args: {},
  6169. ident: "body"
  6170. }]
  6171. }
  6172. send(JSON.stringify(skipFloorCall), checkDataFloor);
  6173. }
  6174.  
  6175. function checkBuff(towerInfo) {
  6176. buffArr = towerInfo.floor;
  6177. promises = [];
  6178. for (let buff of buffArr) {
  6179. buffInfo = buffIds[buff.id];
  6180. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  6181. scullCoin -= buffInfo.cost;
  6182. promises.push(buyBuff(buff.id));
  6183. }
  6184. }
  6185. Promise.all(promises).then(nextFloor);
  6186. }
  6187.  
  6188. function buyBuff(buffId) {
  6189. return new Promise(function (resolve, reject) {
  6190. buyBuffCall = {
  6191. calls: [{
  6192. name: "towerBuyBuff",
  6193. args: {
  6194. buffId
  6195. },
  6196. ident: "body"
  6197. }]
  6198. }
  6199. send(JSON.stringify(buyBuffCall), resolve);
  6200. });
  6201. }
  6202.  
  6203. function checkDataFloor(result) {
  6204. towerInfo = result.results[0].result.response;
  6205. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  6206. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  6207. }
  6208. if ('tower' in towerInfo) {
  6209. towerInfo = towerInfo.tower;
  6210. }
  6211. if ('skullReward' in towerInfo) {
  6212. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6213. }
  6214. checkFloor(towerInfo);
  6215. }
  6216. /**
  6217. * Getting tower rewards
  6218. *
  6219. * Получаем награды башни
  6220. */
  6221. function farmTowerRewards(reason) {
  6222. let { pointRewards, points } = lastTowerInfo;
  6223. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  6224. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  6225. if (!farmPoints.length) {
  6226. return;
  6227. }
  6228. let farmTowerRewardsCall = {
  6229. calls: [{
  6230. name: "tower_farmPointRewards",
  6231. args: {
  6232. points: farmPoints
  6233. },
  6234. ident: "tower_farmPointRewards"
  6235. }]
  6236. }
  6237.  
  6238. if (scullCoin > 0) {
  6239. farmTowerRewardsCall.calls.push({
  6240. name: "tower_farmSkullReward",
  6241. args: {},
  6242. ident: "tower_farmSkullReward"
  6243. });
  6244. }
  6245.  
  6246. send(JSON.stringify(farmTowerRewardsCall), () => { });
  6247. }
  6248.  
  6249. function fullSkipTower() {
  6250. /**
  6251. * Next chest
  6252. *
  6253. * Следующий сундук
  6254. */
  6255. function nextChest(n) {
  6256. return {
  6257. name: "towerNextChest",
  6258. args: {},
  6259. ident: "group_" + n + "_body"
  6260. }
  6261. }
  6262. /**
  6263. * Open chest
  6264. *
  6265. * Открыть сундук
  6266. */
  6267. function openChest(n) {
  6268. return {
  6269. name: "towerOpenChest",
  6270. args: {
  6271. "num": 2
  6272. },
  6273. ident: "group_" + n + "_body"
  6274. }
  6275. }
  6276.  
  6277. const fullSkipTowerCall = {
  6278. calls: []
  6279. }
  6280.  
  6281. let n = 0;
  6282. for (let i = 0; i < 15; i++) {
  6283. // 15 сундуков
  6284. fullSkipTowerCall.calls.push(nextChest(++n));
  6285. fullSkipTowerCall.calls.push(openChest(++n));
  6286. // +5 сундуков, 250 изюма // towerOpenChest
  6287. // if (i < 5) {
  6288. // fullSkipTowerCall.calls.push(openChest(++n, 2));
  6289. // }
  6290. }
  6291.  
  6292. fullSkipTowerCall.calls.push({
  6293. name: 'towerGetInfo',
  6294. args: {},
  6295. ident: 'group_' + ++n + '_body',
  6296. });
  6297.  
  6298. send(JSON.stringify(fullSkipTowerCall), data => {
  6299. for (const r of data.results) {
  6300. const towerInfo = r?.result?.response;
  6301. if (towerInfo && 'skullReward' in towerInfo) {
  6302. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6303. }
  6304. }
  6305. data.results[0] = data.results[data.results.length - 1];
  6306. checkDataFloor(data);
  6307. });
  6308. }
  6309.  
  6310. function nextChestOpen(floorNumber) {
  6311. const calls = [{
  6312. name: "towerOpenChest",
  6313. args: {
  6314. num: 2
  6315. },
  6316. ident: "towerOpenChest"
  6317. }];
  6318.  
  6319. Send(JSON.stringify({ calls })).then(e => {
  6320. nextOpenChest(floorNumber);
  6321. });
  6322. }
  6323.  
  6324. function nextOpenChest(floorNumber) {
  6325. if (floorNumber > 49) {
  6326. endTower('openChest 50 floor', floorNumber);
  6327. return;
  6328. }
  6329.  
  6330. let nextOpenChestCall = {
  6331. calls: [{
  6332. name: "towerNextChest",
  6333. args: {},
  6334. ident: "towerNextChest"
  6335. }, {
  6336. name: "towerOpenChest",
  6337. args: {
  6338. num: 2
  6339. },
  6340. ident: "towerOpenChest"
  6341. }]
  6342. }
  6343. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  6344. }
  6345.  
  6346. function endTower(reason, info) {
  6347. console.log(reason, info);
  6348. if (reason != 'noTower') {
  6349. farmTowerRewards(reason);
  6350. }
  6351. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  6352. resolve();
  6353. }
  6354. }
  6355.  
  6356. this.HWHClasses.executeTower = executeTower;
  6357.  
  6358. /**
  6359. * Passage of the arena of the titans
  6360. *
  6361. * Прохождение арены титанов
  6362. */
  6363. function testTitanArena() {
  6364. const { executeTitanArena } = HWHClasses;
  6365. return new Promise((resolve, reject) => {
  6366. titAren = new executeTitanArena(resolve, reject);
  6367. titAren.start();
  6368. });
  6369. }
  6370.  
  6371. /**
  6372. * Passage of the arena of the titans
  6373. *
  6374. * Прохождение арены титанов
  6375. */
  6376. function executeTitanArena(resolve, reject) {
  6377. let titan_arena = [];
  6378. let finishListBattle = [];
  6379. /**
  6380. * ID of the current batch
  6381. *
  6382. * Идетификатор текущей пачки
  6383. */
  6384. let currentRival = 0;
  6385. /**
  6386. * Number of attempts to finish off the pack
  6387. *
  6388. * Количество попыток добития пачки
  6389. */
  6390. let attempts = 0;
  6391. /**
  6392. * Was there an attempt to finish off the current shooting range
  6393. *
  6394. * Была ли попытка добития текущего тира
  6395. */
  6396. let isCheckCurrentTier = false;
  6397. /**
  6398. * Current shooting range
  6399. *
  6400. * Текущий тир
  6401. */
  6402. let currTier = 0;
  6403. /**
  6404. * Number of battles on the current dash
  6405. *
  6406. * Количество битв на текущем тире
  6407. */
  6408. let countRivalsTier = 0;
  6409.  
  6410. let callsStart = {
  6411. calls: [{
  6412. name: "titanArenaGetStatus",
  6413. args: {},
  6414. ident: "titanArenaGetStatus"
  6415. }, {
  6416. name: "teamGetAll",
  6417. args: {},
  6418. ident: "teamGetAll"
  6419. }]
  6420. }
  6421.  
  6422. this.start = function () {
  6423. send(JSON.stringify(callsStart), startTitanArena);
  6424. }
  6425.  
  6426. function startTitanArena(data) {
  6427. let titanArena = data.results[0].result.response;
  6428. if (titanArena.status == 'disabled') {
  6429. endTitanArena('disabled', titanArena);
  6430. return;
  6431. }
  6432.  
  6433. let teamGetAll = data.results[1].result.response;
  6434. titan_arena = teamGetAll.titan_arena;
  6435.  
  6436. checkTier(titanArena)
  6437. }
  6438.  
  6439. function checkTier(titanArena) {
  6440. if (titanArena.status == "peace_time") {
  6441. endTitanArena('Peace_time', titanArena);
  6442. return;
  6443. }
  6444. currTier = titanArena.tier;
  6445. if (currTier) {
  6446. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  6447. }
  6448.  
  6449. if (titanArena.status == "completed_tier") {
  6450. titanArenaCompleteTier();
  6451. return;
  6452. }
  6453. /**
  6454. * Checking for the possibility of a raid
  6455. * Проверка на возможность рейда
  6456. */
  6457. if (titanArena.canRaid) {
  6458. titanArenaStartRaid();
  6459. return;
  6460. }
  6461. /**
  6462. * Check was an attempt to achieve the current shooting range
  6463. * Проверка была ли попытка добития текущего тира
  6464. */
  6465. if (!isCheckCurrentTier) {
  6466. checkRivals(titanArena.rivals);
  6467. return;
  6468. }
  6469.  
  6470. endTitanArena('Done or not canRaid', titanArena);
  6471. }
  6472. /**
  6473. * Submit dash information for verification
  6474. *
  6475. * Отправка информации о тире на проверку
  6476. */
  6477. function checkResultInfo(data) {
  6478. let titanArena = data.results[0].result.response;
  6479. checkTier(titanArena);
  6480. }
  6481. /**
  6482. * Finish the current tier
  6483. *
  6484. * Завершить текущий тир
  6485. */
  6486. function titanArenaCompleteTier() {
  6487. isCheckCurrentTier = false;
  6488. let calls = [{
  6489. name: "titanArenaCompleteTier",
  6490. args: {},
  6491. ident: "body"
  6492. }];
  6493. send(JSON.stringify({calls}), checkResultInfo);
  6494. }
  6495. /**
  6496. * Gathering points to be completed
  6497. *
  6498. * Собираем точки которые нужно добить
  6499. */
  6500. function checkRivals(rivals) {
  6501. finishListBattle = [];
  6502. for (let n in rivals) {
  6503. if (rivals[n].attackScore < 250) {
  6504. finishListBattle.push(n);
  6505. }
  6506. }
  6507. console.log('checkRivals', finishListBattle);
  6508. countRivalsTier = finishListBattle.length;
  6509. roundRivals();
  6510. }
  6511. /**
  6512. * Selecting the next point to finish off
  6513. *
  6514. * Выбор следующей точки для добития
  6515. */
  6516. function roundRivals() {
  6517. let countRivals = finishListBattle.length;
  6518. if (!countRivals) {
  6519. /**
  6520. * Whole range checked
  6521. *
  6522. * Весь тир проверен
  6523. */
  6524. isCheckCurrentTier = true;
  6525. titanArenaGetStatus();
  6526. return;
  6527. }
  6528. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  6529. currentRival = finishListBattle.pop();
  6530. attempts = +currentRival;
  6531. // console.log('roundRivals', currentRival);
  6532. titanArenaStartBattle(currentRival);
  6533. }
  6534. /**
  6535. * The start of a solo battle
  6536. *
  6537. * Начало одиночной битвы
  6538. */
  6539. function titanArenaStartBattle(rivalId) {
  6540. let calls = [{
  6541. name: "titanArenaStartBattle",
  6542. args: {
  6543. rivalId: rivalId,
  6544. titans: titan_arena
  6545. },
  6546. ident: "body"
  6547. }];
  6548. send(JSON.stringify({calls}), calcResult);
  6549. }
  6550. /**
  6551. * Calculation of the results of the battle
  6552. *
  6553. * Расчет результатов боя
  6554. */
  6555. function calcResult(data) {
  6556. let battlesInfo = data.results[0].result.response.battle;
  6557. /**
  6558. * If attempts are equal to the current battle number we make
  6559. * Если попытки равны номеру текущего боя делаем прерасчет
  6560. */
  6561. if (attempts == currentRival) {
  6562. preCalcBattle(battlesInfo);
  6563. return;
  6564. }
  6565. /**
  6566. * If there are still attempts, we calculate a new battle
  6567. * Если попытки еще есть делаем расчет нового боя
  6568. */
  6569. if (attempts > 0) {
  6570. attempts--;
  6571. calcBattleResult(battlesInfo)
  6572. .then(resultCalcBattle);
  6573. return;
  6574. }
  6575. /**
  6576. * Otherwise, go to the next opponent
  6577. * Иначе переходим к следующему сопернику
  6578. */
  6579. roundRivals();
  6580. }
  6581. /**
  6582. * Processing the results of the battle calculation
  6583. *
  6584. * Обработка результатов расчета битвы
  6585. */
  6586. function resultCalcBattle(resultBattle) {
  6587. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  6588. /**
  6589. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  6590. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  6591. */
  6592. if (resultBattle.result.win || !attempts) {
  6593. titanArenaEndBattle({
  6594. progress: resultBattle.progress,
  6595. result: resultBattle.result,
  6596. rivalId: resultBattle.battleData.typeId
  6597. });
  6598. return;
  6599. }
  6600. /**
  6601. * If not victory and there are attempts we start a new battle
  6602. * Если не победа и есть попытки начинаем новый бой
  6603. */
  6604. titanArenaStartBattle(resultBattle.battleData.typeId);
  6605. }
  6606. /**
  6607. * Returns the promise of calculating the results of the battle
  6608. *
  6609. * Возращает промис расчета результатов битвы
  6610. */
  6611. function getBattleInfo(battle, isRandSeed) {
  6612. return new Promise(function (resolve) {
  6613. if (isRandSeed) {
  6614. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  6615. }
  6616. // console.log(battle.seed);
  6617. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  6618. });
  6619. }
  6620. /**
  6621. * Recalculate battles
  6622. *
  6623. * Прерасчтет битвы
  6624. */
  6625. function preCalcBattle(battle) {
  6626. let actions = [getBattleInfo(battle, false)];
  6627. const countTestBattle = getInput('countTestBattle');
  6628. for (let i = 0; i < countTestBattle; i++) {
  6629. actions.push(getBattleInfo(battle, true));
  6630. }
  6631. Promise.all(actions)
  6632. .then(resultPreCalcBattle);
  6633. }
  6634. /**
  6635. * Processing the results of the battle recalculation
  6636. *
  6637. * Обработка результатов прерасчета битвы
  6638. */
  6639. function resultPreCalcBattle(e) {
  6640. let wins = e.map(n => n.result.win);
  6641. let firstBattle = e.shift();
  6642. let countWin = wins.reduce((w, s) => w + s);
  6643. const countTestBattle = getInput('countTestBattle');
  6644. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  6645. if (countWin > 0) {
  6646. attempts = getInput('countAutoBattle');
  6647. } else {
  6648. attempts = 0;
  6649. }
  6650. resultCalcBattle(firstBattle);
  6651. }
  6652.  
  6653. /**
  6654. * Complete an arena battle
  6655. *
  6656. * Завершить битву на арене
  6657. */
  6658. function titanArenaEndBattle(args) {
  6659. let calls = [{
  6660. name: "titanArenaEndBattle",
  6661. args,
  6662. ident: "body"
  6663. }];
  6664. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  6665. }
  6666.  
  6667. function resultTitanArenaEndBattle(e) {
  6668. let attackScore = e.results[0].result.response.attackScore;
  6669. let numReval = countRivalsTier - finishListBattle.length;
  6670. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  6671. /**
  6672. * TODO: Might need to improve the results.
  6673. * TODO: Возможно стоит сделать улучшение результатов
  6674. */
  6675. // console.log('resultTitanArenaEndBattle', e)
  6676. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  6677. roundRivals();
  6678. }
  6679. /**
  6680. * Arena State
  6681. *
  6682. * Состояние арены
  6683. */
  6684. function titanArenaGetStatus() {
  6685. let calls = [{
  6686. name: "titanArenaGetStatus",
  6687. args: {},
  6688. ident: "body"
  6689. }];
  6690. send(JSON.stringify({calls}), checkResultInfo);
  6691. }
  6692. /**
  6693. * Arena Raid Request
  6694. *
  6695. * Запрос рейда арены
  6696. */
  6697. function titanArenaStartRaid() {
  6698. let calls = [{
  6699. name: "titanArenaStartRaid",
  6700. args: {
  6701. titans: titan_arena
  6702. },
  6703. ident: "body"
  6704. }];
  6705. send(JSON.stringify({calls}), calcResults);
  6706. }
  6707.  
  6708. function calcResults(data) {
  6709. let battlesInfo = data.results[0].result.response;
  6710. let {attackers, rivals} = battlesInfo;
  6711.  
  6712. let promises = [];
  6713. for (let n in rivals) {
  6714. rival = rivals[n];
  6715. promises.push(calcBattleResult({
  6716. attackers: attackers,
  6717. defenders: [rival.team],
  6718. seed: rival.seed,
  6719. typeId: n,
  6720. }));
  6721. }
  6722.  
  6723. Promise.all(promises)
  6724. .then(results => {
  6725. const endResults = {};
  6726. for (let info of results) {
  6727. let id = info.battleData.typeId;
  6728. endResults[id] = {
  6729. progress: info.progress,
  6730. result: info.result,
  6731. }
  6732. }
  6733. titanArenaEndRaid(endResults);
  6734. });
  6735. }
  6736.  
  6737. function calcBattleResult(battleData) {
  6738. return new Promise(function (resolve, reject) {
  6739. BattleCalc(battleData, "get_titanClanPvp", resolve);
  6740. });
  6741. }
  6742.  
  6743. /**
  6744. * Sending Raid Results
  6745. *
  6746. * Отправка результатов рейда
  6747. */
  6748. function titanArenaEndRaid(results) {
  6749. titanArenaEndRaidCall = {
  6750. calls: [{
  6751. name: "titanArenaEndRaid",
  6752. args: {
  6753. results
  6754. },
  6755. ident: "body"
  6756. }]
  6757. }
  6758. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  6759. }
  6760.  
  6761. function checkRaidResults(data) {
  6762. results = data.results[0].result.response.results;
  6763. isSucsesRaid = true;
  6764. for (let i in results) {
  6765. isSucsesRaid &&= (results[i].attackScore >= 250);
  6766. }
  6767.  
  6768. if (isSucsesRaid) {
  6769. titanArenaCompleteTier();
  6770. } else {
  6771. titanArenaGetStatus();
  6772. }
  6773. }
  6774.  
  6775. function titanArenaFarmDailyReward() {
  6776. titanArenaFarmDailyRewardCall = {
  6777. calls: [{
  6778. name: "titanArenaFarmDailyReward",
  6779. args: {},
  6780. ident: "body"
  6781. }]
  6782. }
  6783. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  6784. }
  6785.  
  6786. function endTitanArena(reason, info) {
  6787. if (!['Peace_time', 'disabled'].includes(reason)) {
  6788. titanArenaFarmDailyReward();
  6789. }
  6790. console.log(reason, info);
  6791. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  6792. resolve();
  6793. }
  6794. }
  6795.  
  6796. this.HWHClasses.executeTitanArena = executeTitanArena;
  6797.  
  6798. function hackGame() {
  6799. const self = this;
  6800. selfGame = null;
  6801. bindId = 1e9;
  6802. this.libGame = null;
  6803. this.doneLibLoad = () => {};
  6804.  
  6805. /**
  6806. * List of correspondence of used classes to their names
  6807. *
  6808. * Список соответствия используемых классов их названиям
  6809. */
  6810. ObjectsList = [
  6811. { name: 'BattlePresets', prop: 'game.battle.controller.thread.BattlePresets' },
  6812. { name: 'DataStorage', prop: 'game.data.storage.DataStorage' },
  6813. { name: 'BattleConfigStorage', prop: 'game.data.storage.battle.BattleConfigStorage' },
  6814. { name: 'BattleInstantPlay', prop: 'game.battle.controller.instant.BattleInstantPlay' },
  6815. { name: 'MultiBattleInstantReplay', prop: 'game.battle.controller.instant.MultiBattleInstantReplay' },
  6816. { name: 'MultiBattleResult', prop: 'game.battle.controller.MultiBattleResult' },
  6817.  
  6818. { name: 'PlayerMissionData', prop: 'game.model.user.mission.PlayerMissionData' },
  6819. { name: 'PlayerMissionBattle', prop: 'game.model.user.mission.PlayerMissionBattle' },
  6820. { name: 'GameModel', prop: 'game.model.GameModel' },
  6821. { name: 'CommandManager', prop: 'game.command.CommandManager' },
  6822. { name: 'MissionCommandList', prop: 'game.command.rpc.mission.MissionCommandList' },
  6823. { name: 'RPCCommandBase', prop: 'game.command.rpc.RPCCommandBase' },
  6824. { name: 'PlayerTowerData', prop: 'game.model.user.tower.PlayerTowerData' },
  6825. { name: 'TowerCommandList', prop: 'game.command.tower.TowerCommandList' },
  6826. { name: 'PlayerHeroTeamResolver', prop: 'game.model.user.hero.PlayerHeroTeamResolver' },
  6827. { name: 'BattlePausePopup', prop: 'game.view.popup.battle.BattlePausePopup' },
  6828. { name: 'BattlePopup', prop: 'game.view.popup.battle.BattlePopup' },
  6829. { name: 'DisplayObjectContainer', prop: 'starling.display.DisplayObjectContainer' },
  6830. { name: 'GuiClipContainer', prop: 'engine.core.clipgui.GuiClipContainer' },
  6831. { name: 'BattlePausePopupClip', prop: 'game.view.popup.battle.BattlePausePopupClip' },
  6832. { name: 'ClipLabel', prop: 'game.view.gui.components.ClipLabel' },
  6833. { name: 'ClipLabelBase', prop: 'game.view.gui.components.ClipLabelBase' },
  6834. { name: 'Translate', prop: 'com.progrestar.common.lang.Translate' },
  6835. { name: 'ClipButtonLabeledCentered', prop: 'game.view.gui.components.ClipButtonLabeledCentered' },
  6836. { name: 'BattlePausePopupMediator', prop: 'game.mediator.gui.popup.battle.BattlePausePopupMediator' },
  6837. { name: 'SettingToggleButton', prop: 'game.mechanics.settings.popup.view.SettingToggleButton' },
  6838. { name: 'PlayerDungeonData', prop: 'game.mechanics.dungeon.model.PlayerDungeonData' },
  6839. { name: 'NextDayUpdatedManager', prop: 'game.model.user.NextDayUpdatedManager' },
  6840. { name: 'BattleController', prop: 'game.battle.controller.BattleController' },
  6841. { name: 'BattleSettingsModel', prop: 'game.battle.controller.BattleSettingsModel' },
  6842. { name: 'BooleanProperty', prop: 'engine.core.utils.property.BooleanProperty' },
  6843. { name: 'RuleStorage', prop: 'game.data.storage.rule.RuleStorage' },
  6844. { name: 'BattleConfig', prop: 'battle.BattleConfig' },
  6845. { name: 'BattleGuiMediator', prop: 'game.battle.gui.BattleGuiMediator' },
  6846. { name: 'BooleanPropertyWriteable', prop: 'engine.core.utils.property.BooleanPropertyWriteable' },
  6847. { name: 'BattleLogEncoder', prop: 'battle.log.BattleLogEncoder' },
  6848. { name: 'BattleLogReader', prop: 'battle.log.BattleLogReader' },
  6849. { name: 'PlayerSubscriptionInfoValueObject', prop: 'game.model.user.subscription.PlayerSubscriptionInfoValueObject' },
  6850. { name: 'AdventureMapCamera', prop: 'game.mechanics.adventure.popup.map.AdventureMapCamera' },
  6851. ];
  6852.  
  6853. /**
  6854. * Contains the game classes needed to write and override game methods
  6855. *
  6856. * Содержит классы игры необходимые для написания и подмены методов игры
  6857. */
  6858. Game = {
  6859. /**
  6860. * Function 'e'
  6861. * Функция 'e'
  6862. */
  6863. bindFunc: function (a, b) {
  6864. if (null == b) return null;
  6865. null == b.__id__ && (b.__id__ = bindId++);
  6866. var c;
  6867. null == a.hx__closures__ ? (a.hx__closures__ = {}) : (c = a.hx__closures__[b.__id__]);
  6868. null == c && ((c = b.bind(a)), (a.hx__closures__[b.__id__] = c));
  6869. return c;
  6870. },
  6871. };
  6872.  
  6873. /**
  6874. * Connects to game objects via the object creation event
  6875. *
  6876. * Подключается к объектам игры через событие создания объекта
  6877. */
  6878. function connectGame() {
  6879. for (let obj of ObjectsList) {
  6880. /**
  6881. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  6882. */
  6883. Object.defineProperty(Object.prototype, obj.prop, {
  6884. set: function (value) {
  6885. if (!selfGame) {
  6886. selfGame = this;
  6887. }
  6888. if (!Game[obj.name]) {
  6889. Game[obj.name] = value;
  6890. }
  6891. // console.log('set ' + obj.prop, this, value);
  6892. this[obj.prop + '_'] = value;
  6893. },
  6894. get: function () {
  6895. // console.log('get ' + obj.prop, this);
  6896. return this[obj.prop + '_'];
  6897. },
  6898. });
  6899. }
  6900. }
  6901.  
  6902. /**
  6903. * Game.BattlePresets
  6904. * @param {bool} a isReplay
  6905. * @param {bool} b autoToggleable
  6906. * @param {bool} c auto On Start
  6907. * @param {object} d config
  6908. * @param {bool} f showBothTeams
  6909. */
  6910. /**
  6911. * Returns the results of the battle to the callback function
  6912. * Возвращает в функцию callback результаты боя
  6913. * @param {*} battleData battle data данные боя
  6914. * @param {*} battleConfig combat configuration type options:
  6915. *
  6916. * тип конфигурации боя варианты:
  6917. *
  6918. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  6919. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  6920. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  6921. *
  6922. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  6923. *
  6924. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  6925. * @param {*} callback функция в которую вернуться результаты боя
  6926. */
  6927. this.BattleCalc = function (battleData, battleConfig, callback) {
  6928. // battleConfig = battleConfig || getBattleType(battleData.type)
  6929. if (!Game.BattlePresets) throw Error('Use connectGame');
  6930. battlePresets = new Game.BattlePresets(
  6931. battleData.progress,
  6932. !1,
  6933. !0,
  6934. Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](),
  6935. !1
  6936. );
  6937. let battleInstantPlay;
  6938. if (battleData.progress?.length > 1) {
  6939. battleInstantPlay = new Game.MultiBattleInstantReplay(battleData, battlePresets);
  6940. } else {
  6941. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  6942. }
  6943. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 9)].add((battleInstant) => {
  6944. const MBR_2 = getProtoFn(Game.MultiBattleResult, 2);
  6945. const battleResults = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  6946. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  6947. const battleLogs = [];
  6948. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  6949. let battleTime = 0;
  6950. let battleTimer = 0;
  6951. for (const battleResult of battleResults[MBR_2]) {
  6952. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult));
  6953. battleLogs.push(battleLog);
  6954. const maxTime = Math.max(...battleLog.map((e) => (e.time < timeLimit && e.time !== 168.8 ? e.time : 0)));
  6955. battleTimer += getTimer(maxTime);
  6956. battleTime += maxTime;
  6957. }
  6958. callback({
  6959. battleLogs,
  6960. battleTime,
  6961. battleTimer,
  6962. battleData,
  6963. progress: battleResults[getF(Game.MultiBattleResult, 'get_progress')](),
  6964. result: battleResults[getF(Game.MultiBattleResult, 'get_result')](),
  6965. });
  6966. });
  6967. battleInstantPlay.start();
  6968. };
  6969.  
  6970. /**
  6971. * Returns a function with the specified name from the class
  6972. *
  6973. * Возвращает из класса функцию с указанным именем
  6974. * @param {Object} classF Class // класс
  6975. * @param {String} nameF function name // имя функции
  6976. * @param {String} pos name and alias order // порядок имени и псевдонима
  6977. * @returns
  6978. */
  6979. function getF(classF, nameF, pos) {
  6980. pos = pos || false;
  6981. let prop = Object.entries(classF.prototype.__properties__);
  6982. if (!pos) {
  6983. return prop.filter((e) => e[1] == nameF).pop()[0];
  6984. } else {
  6985. return prop.filter((e) => e[0] == nameF).pop()[1];
  6986. }
  6987. }
  6988.  
  6989. /**
  6990. * Returns a function with the specified name from the class
  6991. *
  6992. * Возвращает из класса функцию с указанным именем
  6993. * @param {Object} classF Class // класс
  6994. * @param {String} nameF function name // имя функции
  6995. * @returns
  6996. */
  6997. function getFnP(classF, nameF) {
  6998. let prop = Object.entries(classF.__properties__);
  6999. return prop.filter((e) => e[1] == nameF).pop()[0];
  7000. }
  7001.  
  7002. /**
  7003. * Returns the function name with the specified ordinal from the class
  7004. *
  7005. * Возвращает имя функции с указаным порядковым номером из класса
  7006. * @param {Object} classF Class // класс
  7007. * @param {Number} nF Order number of function // порядковый номер функции
  7008. * @returns
  7009. */
  7010. function getFn(classF, nF) {
  7011. let prop = Object.keys(classF);
  7012. return prop[nF];
  7013. }
  7014.  
  7015. /**
  7016. * Returns the name of the function with the specified serial number from the prototype of the class
  7017. *
  7018. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  7019. * @param {Object} classF Class // класс
  7020. * @param {Number} nF Order number of function // порядковый номер функции
  7021. * @returns
  7022. */
  7023. function getProtoFn(classF, nF) {
  7024. let prop = Object.keys(classF.prototype);
  7025. return prop[nF];
  7026. }
  7027. /**
  7028. * Description of replaced functions
  7029. *
  7030. * Описание подменяемых функций
  7031. */
  7032. replaceFunction = {
  7033. company: function () {
  7034. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  7035. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  7036. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  7037. if (!isChecked('passBattle')) {
  7038. oldSkipMisson.call(this, a, b, c);
  7039. return;
  7040. }
  7041.  
  7042. try {
  7043. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  7044.  
  7045. var a = new Game.BattlePresets(
  7046. !1,
  7047. !1,
  7048. !0,
  7049. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  7050. !1
  7051. );
  7052. a = new Game.BattleInstantPlay(c, a);
  7053. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  7054. a.start();
  7055. } catch (error) {
  7056. console.error('company', error);
  7057. oldSkipMisson.call(this, a, b, c);
  7058. }
  7059. };
  7060.  
  7061. Game.PlayerMissionData.prototype.P$h = function (a) {
  7062. let GM_2 = getFn(Game.GameModel, 2);
  7063. let GM_P2 = getProtoFn(Game.GameModel, 2);
  7064. let CM_20 = getProtoFn(Game.CommandManager, 20);
  7065. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  7066. let MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  7067. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  7068. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  7069. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]));
  7070. };
  7071. },
  7072. /*
  7073. tower: function () {
  7074. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  7075. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  7076. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  7077. if (!isChecked('passBattle')) {
  7078. oldSkipTower.call(this, a);
  7079. return;
  7080. }
  7081. try {
  7082. var p = new Game.BattlePresets(
  7083. !1,
  7084. !1,
  7085. !0,
  7086. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  7087. !1
  7088. );
  7089. a = new Game.BattleInstantPlay(a, p);
  7090. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  7091. a.start();
  7092. } catch (error) {
  7093. console.error('tower', error);
  7094. oldSkipMisson.call(this, a, b, c);
  7095. }
  7096. };
  7097.  
  7098. Game.PlayerTowerData.prototype.P$h = function (a) {
  7099. const GM_2 = getFnP(Game.GameModel, 'get_instance');
  7100. const GM_P2 = getProtoFn(Game.GameModel, 2);
  7101. const CM_29 = getProtoFn(Game.CommandManager, 29);
  7102. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  7103. const MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  7104. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  7105. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  7106. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  7107. };
  7108. },
  7109. */
  7110. // skipSelectHero: function() {
  7111. // if (!HOST) throw Error('Use connectGame');
  7112. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  7113. // },
  7114. passBattle: function () {
  7115. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  7116. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  7117. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  7118. if (!isChecked('passBattle')) {
  7119. oldPassBattle.call(this, a);
  7120. return;
  7121. }
  7122. try {
  7123. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  7124. this[getProtoFn(Game.BattlePausePopup, 3)]();
  7125. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  7126. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](
  7127. Game.Translate.translate('UI_POPUP_BATTLE_PAUSE')
  7128. );
  7129.  
  7130. this.clip[getProtoFn(Game.BattlePausePopupClip, 2)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7131. Game.Translate.translate('UI_POPUP_BATTLE_RETREAT'),
  7132. ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 17)]))
  7133. );
  7134. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7135. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  7136. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]()
  7137. ? ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7138. : ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7139. );
  7140.  
  7141. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][
  7142. getProtoFn(Game.ClipLabelBase, 24)
  7143. ]();
  7144. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](
  7145. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]()
  7146. );
  7147. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](
  7148. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]()
  7149. );
  7150. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](
  7151. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]()
  7152. );
  7153. } catch (error) {
  7154. console.error('passBattle', error);
  7155. oldPassBattle.call(this, a);
  7156. }
  7157. };
  7158.  
  7159. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, 'get_retreatButtonLabel');
  7160. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  7161. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  7162. if (isChecked('passBattle')) {
  7163. return I18N('BTN_PASS');
  7164. } else {
  7165. return oldFunc.call(this);
  7166. }
  7167. };
  7168. },
  7169. endlessCards: function () {
  7170. let PDD_21 = getProtoFn(Game.PlayerDungeonData, 21);
  7171. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_21];
  7172. Game.PlayerDungeonData.prototype[PDD_21] = function () {
  7173. if (countPredictionCard <= 0) {
  7174. return true;
  7175. } else {
  7176. return oldEndlessCards.call(this);
  7177. }
  7178. };
  7179. },
  7180. speedBattle: function () {
  7181. const get_timeScale = getF(Game.BattleController, 'get_timeScale');
  7182. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  7183. Game.BattleController.prototype[get_timeScale] = function () {
  7184. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  7185. if (!speedBattle) {
  7186. return oldSpeedBattle.call(this);
  7187. }
  7188. try {
  7189. const BC_12 = getProtoFn(Game.BattleController, 12);
  7190. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  7191. const BP_get_value = getF(Game.BooleanProperty, 'get_value');
  7192. if (this[BC_12][BSM_12][BP_get_value]()) {
  7193. return 0;
  7194. }
  7195. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  7196. const BC_49 = getProtoFn(Game.BattleController, 49);
  7197. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  7198. const BC_14 = getProtoFn(Game.BattleController, 14);
  7199. const BC_3 = getFn(Game.BattleController, 3);
  7200. if (this[BC_12][BSM_2][BP_get_value]()) {
  7201. var a = speedBattle * this[BC_49]();
  7202. } else {
  7203. a = this[BC_12][BSM_1][BP_get_value]();
  7204. const maxSpeed = Math.max(...this[BC_14]);
  7205. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  7206. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_49]();
  7207. }
  7208. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  7209. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  7210. const DS_23 = getFn(Game.DataStorage, 23);
  7211. const get_battleSpeedMultiplier = getF(Game.RuleStorage, 'get_battleSpeedMultiplier', true);
  7212. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  7213. const R_1 = getFn(selfGame.Reflect, 1);
  7214. const BC_1 = getFn(Game.BattleController, 1);
  7215. const get_config = getF(Game.BattlePresets, 'get_config');
  7216. null != b &&
  7217. (a = selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7218. ? a * selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7219. : a * selfGame.Reflect[R_1](b, 'default'));
  7220. return a;
  7221. } catch (error) {
  7222. console.error('passBatspeedBattletle', error);
  7223. return oldSpeedBattle.call(this);
  7224. }
  7225. };
  7226. },
  7227.  
  7228. /**
  7229. * Acceleration button without Valkyries favor
  7230. *
  7231. * Кнопка ускорения без Покровительства Валькирий
  7232. */
  7233. battleFastKey: function () {
  7234. const BGM_44 = getProtoFn(Game.BattleGuiMediator, 44);
  7235. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_44];
  7236. Game.BattleGuiMediator.prototype[BGM_44] = function () {
  7237. let flag = true;
  7238. //console.log(flag)
  7239. if (!flag) {
  7240. return oldBattleFastKey.call(this);
  7241. }
  7242. try {
  7243. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  7244. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  7245. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  7246. this[BGM_9][BPW_0](true);
  7247. this[BGM_10][BPW_0](true);
  7248. } catch (error) {
  7249. console.error(error);
  7250. return oldBattleFastKey.call(this);
  7251. }
  7252. };
  7253. },
  7254. fastSeason: function () {
  7255. const GameNavigator = selfGame['game.screen.navigator.GameNavigator'];
  7256. const oldFuncName = getProtoFn(GameNavigator, 18);
  7257. const newFuncName = getProtoFn(GameNavigator, 16);
  7258. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  7259. const newFastSeason = GameNavigator.prototype[newFuncName];
  7260. GameNavigator.prototype[oldFuncName] = function (a, b) {
  7261. if (isChecked('fastSeason')) {
  7262. return newFastSeason.apply(this, [a]);
  7263. } else {
  7264. return oldFastSeason.apply(this, [a, b]);
  7265. }
  7266. };
  7267. },
  7268. ShowChestReward: function () {
  7269. const TitanArtifactChest = selfGame['game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator'];
  7270. const getOpenAmountTitan = getF(TitanArtifactChest, 'get_openAmount');
  7271. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  7272. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  7273. if (correctShowOpenArtifact) {
  7274. correctShowOpenArtifact--;
  7275. return 100;
  7276. }
  7277. return oldGetOpenAmountTitan.call(this);
  7278. };
  7279.  
  7280. const ArtifactChest = selfGame['game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator'];
  7281. const getOpenAmount = getF(ArtifactChest, 'get_openAmount');
  7282. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  7283. ArtifactChest.prototype[getOpenAmount] = function () {
  7284. if (correctShowOpenArtifact) {
  7285. correctShowOpenArtifact--;
  7286. return 100;
  7287. }
  7288. return oldGetOpenAmount.call(this);
  7289. };
  7290. },
  7291. fixCompany: function () {
  7292. const GameBattleView = selfGame['game.mediator.gui.popup.battle.GameBattleView'];
  7293. const BattleThread = selfGame['game.battle.controller.thread.BattleThread'];
  7294. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  7295. const getThread = getF(GameBattleView, 'get_thread');
  7296. const oldFunc = GameBattleView.prototype[getThread];
  7297. GameBattleView.prototype[getThread] = function () {
  7298. return (
  7299. oldFunc.call(this) || {
  7300. [getOnViewDisposed]: async () => {},
  7301. }
  7302. );
  7303. };
  7304. },
  7305. BuyTitanArtifact: function () {
  7306. const BIP_4 = getProtoFn(selfGame['game.view.popup.shop.buy.BuyItemPopup'], 4);
  7307. const BuyItemPopup = selfGame['game.view.popup.shop.buy.BuyItemPopup'];
  7308. const oldFunc = BuyItemPopup.prototype[BIP_4];
  7309. BuyItemPopup.prototype[BIP_4] = function () {
  7310. if (isChecked('countControl')) {
  7311. const BuyTitanArtifactItemPopup = selfGame['game.view.popup.shop.buy.BuyTitanArtifactItemPopup'];
  7312. const BTAP_0 = getProtoFn(BuyTitanArtifactItemPopup, 0);
  7313. if (this[BTAP_0]) {
  7314. const BuyTitanArtifactPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyTitanArtifactItemPopupMediator'];
  7315. const BTAM_1 = getProtoFn(BuyTitanArtifactPopupMediator, 1);
  7316. const BuyItemPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyItemPopupMediator'];
  7317. const BIPM_5 = getProtoFn(BuyItemPopupMediator, 5);
  7318. const BIPM_7 = getProtoFn(BuyItemPopupMediator, 7);
  7319. const BIPM_9 = getProtoFn(BuyItemPopupMediator, 9);
  7320.  
  7321. let need = Math.min(this[BTAP_0][BTAM_1](), this[BTAP_0][BIPM_7]);
  7322. need = need ? need : 60;
  7323. this[BTAP_0][BIPM_9] = need;
  7324. this[BTAP_0][BIPM_5] = 10;
  7325. }
  7326. }
  7327. oldFunc.call(this);
  7328. };
  7329. },
  7330. ClanQuestsFastFarm: function () {
  7331. const VipRuleValueObject = selfGame['game.data.storage.rule.VipRuleValueObject'];
  7332. const getClanQuestsFastFarm = getF(VipRuleValueObject, 'get_clanQuestsFastFarm', 1);
  7333. VipRuleValueObject.prototype[getClanQuestsFastFarm] = function () {
  7334. return 0;
  7335. };
  7336. },
  7337. adventureCamera: function () {
  7338. const AMC_40 = getProtoFn(Game.AdventureMapCamera, 40);
  7339. const AMC_5 = getProtoFn(Game.AdventureMapCamera, 5);
  7340. const oldFunc = Game.AdventureMapCamera.prototype[AMC_40];
  7341. Game.AdventureMapCamera.prototype[AMC_40] = function (a) {
  7342. this[AMC_5] = 0.4;
  7343. oldFunc.bind(this)(a);
  7344. };
  7345. },
  7346. unlockMission: function () {
  7347. const WorldMapStoryDrommerHelper = selfGame['game.mediator.gui.worldmap.WorldMapStoryDrommerHelper'];
  7348. const WMSDH_4 = getFn(WorldMapStoryDrommerHelper, 4);
  7349. const WMSDH_7 = getFn(WorldMapStoryDrommerHelper, 7);
  7350. WorldMapStoryDrommerHelper[WMSDH_4] = function () {
  7351. return true;
  7352. };
  7353. WorldMapStoryDrommerHelper[WMSDH_7] = function () {
  7354. return true;
  7355. };
  7356. },
  7357. };
  7358.  
  7359. /**
  7360. * Starts replacing recorded functions
  7361. *
  7362. * Запускает замену записанных функций
  7363. */
  7364. this.activateHacks = function () {
  7365. if (!selfGame) throw Error('Use connectGame');
  7366. for (let func in replaceFunction) {
  7367. try {
  7368. replaceFunction[func]();
  7369. } catch (error) {
  7370. console.error(error);
  7371. }
  7372. }
  7373. };
  7374.  
  7375. /**
  7376. * Returns the game object
  7377. *
  7378. * Возвращает объект игры
  7379. */
  7380. this.getSelfGame = function () {
  7381. return selfGame;
  7382. };
  7383.  
  7384. /**
  7385. * Updates game data
  7386. *
  7387. * Обновляет данные игры
  7388. */
  7389. this.refreshGame = function () {
  7390. new Game.NextDayUpdatedManager()[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  7391. try {
  7392. cheats.refreshInventory();
  7393. } catch (e) {}
  7394. };
  7395.  
  7396. /**
  7397. * Update inventory
  7398. *
  7399. * Обновляет инвентарь
  7400. */
  7401. this.refreshInventory = async function () {
  7402. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7403. const GM_0 = getProtoFn(Game.GameModel, 0);
  7404. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7405. const Player = Game.GameModel[GM_INST]()[GM_0];
  7406. Player[P_24] = new selfGame['game.model.user.inventory.PlayerInventory']();
  7407. Player[P_24].init(await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'body' }] }).then((e) => e.results[0].result.response));
  7408. };
  7409. this.updateInventory = function (reward) {
  7410. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7411. const GM_0 = getProtoFn(Game.GameModel, 0);
  7412. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7413. const Player = Game.GameModel[GM_INST]()[GM_0];
  7414. Player[P_24].init(reward);
  7415. };
  7416.  
  7417. this.updateMap = function (data) {
  7418. const PCDD_21 = getProtoFn(selfGame['game.mechanics.clanDomination.model.PlayerClanDominationData'], 21);
  7419. const P_60 = getProtoFn(selfGame['game.model.user.Player'], 60);
  7420. const GM_0 = getProtoFn(Game.GameModel, 0);
  7421. const getInstance = getFnP(selfGame['Game'], 'get_instance');
  7422. const PlayerClanDominationData = Game.GameModel[getInstance]()[GM_0];
  7423. PlayerClanDominationData[P_60][PCDD_21].update(data);
  7424. };
  7425.  
  7426. /**
  7427. * Change the play screen on windowName
  7428. *
  7429. * Сменить экран игры на windowName
  7430. *
  7431. * Possible options:
  7432. *
  7433. * Возможные варианты:
  7434. *
  7435. * 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
  7436. */
  7437. this.goNavigtor = function (windowName) {
  7438. let mechanicStorage = selfGame['game.data.storage.mechanic.MechanicStorage'];
  7439. let window = mechanicStorage[windowName];
  7440. let event = new selfGame['game.mediator.gui.popup.PopupStashEventParams']();
  7441. let Game = selfGame['Game'];
  7442. let navigator = getF(Game, 'get_navigator');
  7443. let navigate = getProtoFn(selfGame['game.screen.navigator.GameNavigator'], 20);
  7444. let instance = getFnP(Game, 'get_instance');
  7445. Game[instance]()[navigator]()[navigate](window, event);
  7446. };
  7447.  
  7448. /**
  7449. * Move to the sanctuary cheats.goSanctuary()
  7450. *
  7451. * Переместиться в святилище cheats.goSanctuary()
  7452. */
  7453. this.goSanctuary = () => {
  7454. this.goNavigtor('SANCTUARY');
  7455. };
  7456.  
  7457. /** Перейти в Долину титанов */
  7458. this.goTitanValley = () => {
  7459. this.goNavigtor('TITAN_VALLEY');
  7460. };
  7461.  
  7462. /**
  7463. * Go to Guild War
  7464. *
  7465. * Перейти к Войне Гильдий
  7466. */
  7467. this.goClanWar = function () {
  7468. let instance = getFnP(Game.GameModel, 'get_instance');
  7469. let player = Game.GameModel[instance]().A;
  7470. let clanWarSelect = selfGame['game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator'];
  7471. new clanWarSelect(player).open();
  7472. };
  7473.  
  7474. /** Перейти к Острову гильдии */
  7475. this.goClanIsland = function () {
  7476. let instance = getFnP(Game.GameModel, 'get_instance');
  7477. let player = Game.GameModel[instance]().A;
  7478. let clanIslandSelect = selfGame['game.view.gui.ClanIslandPopupMediator'];
  7479. new clanIslandSelect(player).open();
  7480. };
  7481.  
  7482. /**
  7483. * Go to BrawlShop
  7484. *
  7485. * Переместиться в BrawlShop
  7486. */
  7487. this.goBrawlShop = () => {
  7488. const instance = getFnP(Game.GameModel, 'get_instance');
  7489. const P_36 = getProtoFn(selfGame['game.model.user.Player'], 36);
  7490. const PSD_0 = getProtoFn(selfGame['game.model.user.shop.PlayerShopData'], 0);
  7491. const IM_0 = getProtoFn(selfGame['haxe.ds.IntMap'], 0);
  7492. const PSDE_4 = getProtoFn(selfGame['game.model.user.shop.PlayerShopDataEntry'], 4);
  7493.  
  7494. const player = Game.GameModel[instance]().A;
  7495. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  7496. const shopPopup = new selfGame['game.mechanics.brawl.mediator.BrawlShopPopupMediator'](player, shop);
  7497. shopPopup.open(new selfGame['game.mediator.gui.popup.PopupStashEventParams']());
  7498. };
  7499.  
  7500. /**
  7501. * Returns all stores from game data
  7502. *
  7503. * Возвращает все магазины из данных игры
  7504. */
  7505. this.getShops = () => {
  7506. const instance = getFnP(Game.GameModel, 'get_instance');
  7507. const P_36 = getProtoFn(selfGame['game.model.user.Player'], 36);
  7508. const PSD_0 = getProtoFn(selfGame['game.model.user.shop.PlayerShopData'], 0);
  7509. const IM_0 = getProtoFn(selfGame['haxe.ds.IntMap'], 0);
  7510.  
  7511. const player = Game.GameModel[instance]().A;
  7512. return player[P_36][PSD_0][IM_0];
  7513. };
  7514.  
  7515. /**
  7516. * Returns the store from the game data by ID
  7517. *
  7518. * Возвращает магазин из данных игры по идетификатору
  7519. */
  7520. this.getShop = (id) => {
  7521. const PSDE_4 = getProtoFn(selfGame['game.model.user.shop.PlayerShopDataEntry'], 4);
  7522. const shops = this.getShops();
  7523. const shop = shops[id]?.[PSDE_4];
  7524. return shop;
  7525. };
  7526.  
  7527. /**
  7528. * Change island map
  7529. *
  7530. * Сменить карту острова
  7531. */
  7532. this.changeIslandMap = (mapId = 2) => {
  7533. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  7534. const GM_0 = getProtoFn(Game.GameModel, 0);
  7535. const P_59 = getProtoFn(selfGame['game.model.user.Player'], 60);
  7536. const PSAD_31 = getProtoFn(selfGame['game.mechanics.season_adventure.model.PlayerSeasonAdventureData'], 31);
  7537. const Player = Game.GameModel[GameInst]()[GM_0];
  7538. Player[P_59][PSAD_31]({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  7539.  
  7540. const GN_15 = getProtoFn(selfGame['game.screen.navigator.GameNavigator'], 17);
  7541. const navigator = getF(selfGame['Game'], 'get_navigator');
  7542. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame['game.mediator.gui.popup.PopupStashEventParams']());
  7543. };
  7544.  
  7545. /**
  7546. * Game library availability tracker
  7547. *
  7548. * Отслеживание доступности игровой библиотеки
  7549. */
  7550. function checkLibLoad() {
  7551. timeout = setTimeout(() => {
  7552. if (Game.GameModel) {
  7553. changeLib();
  7554. } else {
  7555. checkLibLoad();
  7556. }
  7557. }, 100);
  7558. }
  7559.  
  7560. /**
  7561. * Game library data spoofing
  7562. *
  7563. * Подмена данных игровой библиотеки
  7564. */
  7565. function changeLib() {
  7566. console.log('lib connect');
  7567. const originalStartFunc = Game.GameModel.prototype.start;
  7568. Game.GameModel.prototype.start = function (a, b, c) {
  7569. self.libGame = b.raw;
  7570. self.doneLibLoad(self.libGame);
  7571. try {
  7572. const levels = b.raw.seasonAdventure.level;
  7573. for (const id in levels) {
  7574. const level = levels[id];
  7575. level.clientData.graphics.fogged = level.clientData.graphics.visible;
  7576. }
  7577. const adv = b.raw.seasonAdventure.list[1];
  7578. adv.clientData.asset = 'dialog_season_adventure_tiles';
  7579. } catch (e) {
  7580. console.warn(e);
  7581. }
  7582. originalStartFunc.call(this, a, b, c);
  7583. };
  7584. }
  7585.  
  7586. this.LibLoad = function () {
  7587. return new Promise((e) => {
  7588. this.doneLibLoad = e;
  7589. });
  7590. };
  7591.  
  7592. /**
  7593. * Returns the value of a language constant
  7594. *
  7595. * Возвращает значение языковой константы
  7596. * @param {*} langConst language constant // языковая константа
  7597. * @returns
  7598. */
  7599. this.translate = function (langConst) {
  7600. return Game.Translate.translate(langConst);
  7601. };
  7602.  
  7603. connectGame();
  7604. checkLibLoad();
  7605. }
  7606.  
  7607. /**
  7608. * Auto collection of gifts
  7609. *
  7610. * Автосбор подарков
  7611. */
  7612. function getAutoGifts() {
  7613. // c3ltYm9scyB0aGF0IG1lYW4gbm90aGluZw==
  7614. let valName = 'giftSendIds_' + userInfo.id;
  7615.  
  7616. if (!localStorage['clearGift' + userInfo.id]) {
  7617. localStorage[valName] = '';
  7618. localStorage['clearGift' + userInfo.id] = '+';
  7619. }
  7620.  
  7621. if (!localStorage[valName]) {
  7622. localStorage[valName] = '';
  7623. }
  7624.  
  7625. const giftsAPI = new ZingerYWebsiteAPI('getGifts.php', arguments);
  7626. /**
  7627. * Submit a request to receive gift codes
  7628. *
  7629. * Отправка запроса для получения кодов подарков
  7630. */
  7631. giftsAPI.request().then((data) => {
  7632. let freebieCheckCalls = {
  7633. calls: [],
  7634. };
  7635. data.forEach((giftId, n) => {
  7636. if (localStorage[valName].includes(giftId)) return;
  7637. freebieCheckCalls.calls.push({
  7638. name: 'registration',
  7639. args: {
  7640. user: { referrer: {} },
  7641. giftId,
  7642. },
  7643. context: {
  7644. actionTs: Math.floor(performance.now()),
  7645. cookie: window?.NXAppInfo?.session_id || null,
  7646. },
  7647. ident: giftId,
  7648. });
  7649. });
  7650.  
  7651. if (!freebieCheckCalls.calls.length) {
  7652. return;
  7653. }
  7654.  
  7655. send(JSON.stringify(freebieCheckCalls), (e) => {
  7656. let countGetGifts = 0;
  7657. const gifts = [];
  7658. for (check of e.results) {
  7659. gifts.push(check.ident);
  7660. if (check.result.response != null) {
  7661. countGetGifts++;
  7662. }
  7663. }
  7664. const saveGifts = localStorage[valName].split(';');
  7665. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  7666. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  7667. });
  7668. });
  7669. }
  7670.  
  7671. /**
  7672. * To fill the kills in the Forge of Souls
  7673. *
  7674. * Набить килов в горниле душ
  7675. */
  7676. async function bossRatingEvent() {
  7677. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  7678. if (!topGet || !topGet.results[0].result.response[0]) {
  7679. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7680. return;
  7681. }
  7682. const replayId = topGet.results[0].result.response[0].userData.replayId;
  7683. const result = await Send(JSON.stringify({
  7684. calls: [
  7685. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  7686. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  7687. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  7688. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  7689. ]
  7690. }));
  7691. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  7692. if (!bossEventInfo) {
  7693. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7694. return;
  7695. }
  7696. const usedHeroes = bossEventInfo.progress.usedHeroes;
  7697. const party = Object.values(result.results[0].result.response.replay.attackers);
  7698. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  7699. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  7700. const calls = [];
  7701. /**
  7702. * First pack
  7703. *
  7704. * Первая пачка
  7705. */
  7706. const args = {
  7707. heroes: [],
  7708. favor: {}
  7709. }
  7710. for (let hero of party) {
  7711. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  7712. args.pet = hero.id;
  7713. continue;
  7714. }
  7715. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  7716. continue;
  7717. }
  7718. args.heroes.push(hero.id);
  7719. if (hero.favorPetId) {
  7720. args.favor[hero.id] = hero.favorPetId;
  7721. }
  7722. }
  7723. if (args.heroes.length) {
  7724. calls.push({
  7725. name: "bossRatingEvent_startBattle",
  7726. args,
  7727. ident: "body_0"
  7728. });
  7729. }
  7730. /**
  7731. * Other packs
  7732. *
  7733. * Другие пачки
  7734. */
  7735. let heroes = [];
  7736. let count = 1;
  7737. while (heroId = availableHeroes.pop()) {
  7738. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  7739. continue;
  7740. }
  7741. heroes.push(heroId);
  7742. if (heroes.length == 5) {
  7743. calls.push({
  7744. name: "bossRatingEvent_startBattle",
  7745. args: {
  7746. heroes: [...heroes],
  7747. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  7748. },
  7749. ident: "body_" + count
  7750. });
  7751. heroes = [];
  7752. count++;
  7753. }
  7754. }
  7755.  
  7756. if (!calls.length) {
  7757. setProgress(`${I18N('NO_HEROES')}`, true);
  7758. return;
  7759. }
  7760.  
  7761. const resultBattles = await Send(JSON.stringify({ calls }));
  7762. console.log(resultBattles);
  7763. rewardBossRatingEvent();
  7764. }
  7765.  
  7766. /**
  7767. * Collecting Rewards from the Forge of Souls
  7768. *
  7769. * Сбор награды из Горнила Душ
  7770. */
  7771. function rewardBossRatingEvent() {
  7772. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7773. send(rewardBossRatingCall, function (data) {
  7774. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  7775. if (!bossEventInfo) {
  7776. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7777. return;
  7778. }
  7779.  
  7780. let farmedChests = bossEventInfo.progress.farmedChests;
  7781. let score = bossEventInfo.progress.score;
  7782. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  7783. let revard = bossEventInfo.reward;
  7784.  
  7785. let getRewardCall = {
  7786. calls: []
  7787. }
  7788.  
  7789. let count = 0;
  7790. for (let i = 1; i < 10; i++) {
  7791. if (farmedChests.includes(i)) {
  7792. continue;
  7793. }
  7794. if (score < revard[i].score) {
  7795. break;
  7796. }
  7797. getRewardCall.calls.push({
  7798. name: "bossRatingEvent_getReward",
  7799. args: {
  7800. rewardId: i
  7801. },
  7802. ident: "body_" + i
  7803. });
  7804. count++;
  7805. }
  7806. if (!count) {
  7807. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7808. return;
  7809. }
  7810.  
  7811. send(JSON.stringify(getRewardCall), e => {
  7812. console.log(e);
  7813. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7814. });
  7815. });
  7816. }
  7817.  
  7818. /**
  7819. * Collect Easter eggs and event rewards
  7820. *
  7821. * Собрать пасхалки и награды событий
  7822. */
  7823. function offerFarmAllReward() {
  7824. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7825. return Send(offerGetAllCall).then((data) => {
  7826. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  7827. if (!offerGetAll.length) {
  7828. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7829. return;
  7830. }
  7831.  
  7832. const calls = [];
  7833. for (let reward of offerGetAll) {
  7834. calls.push({
  7835. name: "offerFarmReward",
  7836. args: {
  7837. offerId: reward.id
  7838. },
  7839. ident: "offerFarmReward_" + reward.id
  7840. });
  7841. }
  7842.  
  7843. return Send(JSON.stringify({ calls })).then(e => {
  7844. console.log(e);
  7845. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7846. });
  7847. });
  7848. }
  7849.  
  7850. /**
  7851. * Assemble Outland
  7852. *
  7853. * Собрать запределье
  7854. */
  7855. function getOutland() {
  7856. return new Promise(function (resolve, reject) {
  7857. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  7858. let bosses = e.results[0].result.response;
  7859.  
  7860. let bossRaidOpenChestCall = {
  7861. calls: []
  7862. };
  7863.  
  7864. for (let boss of bosses) {
  7865. if (boss.mayRaid) {
  7866. bossRaidOpenChestCall.calls.push({
  7867. name: "bossRaid",
  7868. args: {
  7869. bossId: boss.id
  7870. },
  7871. ident: "bossRaid_" + boss.id
  7872. });
  7873. bossRaidOpenChestCall.calls.push({
  7874. name: "bossOpenChest",
  7875. args: {
  7876. bossId: boss.id,
  7877. amount: 1,
  7878. starmoney: 0
  7879. },
  7880. ident: "bossOpenChest_" + boss.id
  7881. });
  7882. } else if (boss.chestId == 1) {
  7883. bossRaidOpenChestCall.calls.push({
  7884. name: "bossOpenChest",
  7885. args: {
  7886. bossId: boss.id,
  7887. amount: 1,
  7888. starmoney: 0
  7889. },
  7890. ident: "bossOpenChest_" + boss.id
  7891. });
  7892. }
  7893. }
  7894.  
  7895. if (!bossRaidOpenChestCall.calls.length) {
  7896. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  7897. resolve();
  7898. return;
  7899. }
  7900.  
  7901. send(JSON.stringify(bossRaidOpenChestCall), e => {
  7902. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  7903. resolve();
  7904. });
  7905. });
  7906. });
  7907. }
  7908.  
  7909. /**
  7910. * Collect all rewards
  7911. *
  7912. * Собрать все награды
  7913. */
  7914. function questAllFarm() {
  7915. return new Promise(function (resolve, reject) {
  7916. let questGetAllCall = {
  7917. calls: [{
  7918. name: "questGetAll",
  7919. args: {},
  7920. ident: "body"
  7921. }]
  7922. }
  7923. send(JSON.stringify(questGetAllCall), function (data) {
  7924. let questGetAll = data.results[0].result.response;
  7925. const questAllFarmCall = {
  7926. calls: []
  7927. }
  7928. let number = 0;
  7929. for (let quest of questGetAll) {
  7930. if (quest.id < 1e6 && quest.state == 2) {
  7931. questAllFarmCall.calls.push({
  7932. name: "questFarm",
  7933. args: {
  7934. questId: quest.id
  7935. },
  7936. ident: `group_${number}_body`
  7937. });
  7938. number++;
  7939. }
  7940. }
  7941.  
  7942. if (!questAllFarmCall.calls.length) {
  7943. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7944. resolve();
  7945. return;
  7946. }
  7947.  
  7948. send(JSON.stringify(questAllFarmCall), function (res) {
  7949. console.log(res);
  7950. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7951. resolve();
  7952. });
  7953. });
  7954. })
  7955. }
  7956.  
  7957. /**
  7958. * Mission auto repeat
  7959. *
  7960. * Автоповтор миссии
  7961. * isStopSendMission = false;
  7962. * isSendsMission = true;
  7963. **/
  7964. this.sendsMission = async function (param) {
  7965. if (isStopSendMission) {
  7966. isSendsMission = false;
  7967. console.log(I18N('STOPPED'));
  7968. setProgress('');
  7969. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  7970. msg: 'Ok',
  7971. result: true
  7972. }, ])
  7973. return;
  7974. }
  7975. lastMissionBattleStart = Date.now();
  7976. let missionStartCall = {
  7977. "calls": [{
  7978. "name": "missionStart",
  7979. "args": lastMissionStart,
  7980. "ident": "body"
  7981. }]
  7982. }
  7983. /**
  7984. * Mission Request
  7985. *
  7986. * Запрос на выполнение мисии
  7987. */
  7988. SendRequest(JSON.stringify(missionStartCall), async e => {
  7989. if (e['error']) {
  7990. isSendsMission = false;
  7991. console.log(e['error']);
  7992. setProgress('');
  7993. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  7994. await popup.confirm(msg, [
  7995. {msg: 'Ok', result: true},
  7996. ])
  7997. return;
  7998. }
  7999. /**
  8000. * Mission data calculation
  8001. *
  8002. * Расчет данных мисии
  8003. */
  8004. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  8005. /** missionTimer */
  8006. let timer = getTimer(r.battleTime) + 5;
  8007. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  8008. if (period < timer) {
  8009. timer = timer - period;
  8010. await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`);
  8011. }
  8012.  
  8013. let missionEndCall = {
  8014. "calls": [{
  8015. "name": "missionEnd",
  8016. "args": {
  8017. "id": param.id,
  8018. "result": r.result,
  8019. "progress": r.progress
  8020. },
  8021. "ident": "body"
  8022. }]
  8023. }
  8024. /**
  8025. * Mission Completion Request
  8026. *
  8027. * Запрос на завершение миссии
  8028. */
  8029. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  8030. if (e['error']) {
  8031. isSendsMission = false;
  8032. console.log(e['error']);
  8033. setProgress('');
  8034. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  8035. await popup.confirm(msg, [
  8036. {msg: 'Ok', result: true},
  8037. ])
  8038. return;
  8039. }
  8040. r = e.results[0].result.response;
  8041. if (r['error']) {
  8042. isSendsMission = false;
  8043. console.log(r['error']);
  8044. setProgress('');
  8045. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  8046. {msg: 'Ok', result: true},
  8047. ])
  8048. return;
  8049. }
  8050.  
  8051. param.count++;
  8052. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  8053. isStopSendMission = true;
  8054. });
  8055. setTimeout(sendsMission, 1, param);
  8056. });
  8057. })
  8058. });
  8059. }
  8060.  
  8061. /**
  8062. * Opening of russian dolls
  8063. *
  8064. * Открытие матрешек
  8065. */
  8066. async function openRussianDolls(libId, amount) {
  8067. let sum = 0;
  8068. const sumResult = {};
  8069. let count = 0;
  8070.  
  8071. while (amount) {
  8072. sum += amount;
  8073. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  8074. const calls = [
  8075. {
  8076. name: 'consumableUseLootBox',
  8077. args: { libId, amount },
  8078. ident: 'body',
  8079. },
  8080. ];
  8081. const response = await Send(JSON.stringify({ calls })).then((e) => e.results[0].result.response);
  8082. let [countLootBox, result] = Object.entries(response).pop();
  8083. count += +countLootBox;
  8084. let newCount = 0;
  8085.  
  8086. if (result?.consumable && result.consumable[libId]) {
  8087. newCount = result.consumable[libId];
  8088. delete result.consumable[libId];
  8089. }
  8090.  
  8091. mergeItemsObj(sumResult, result);
  8092. amount = newCount;
  8093. }
  8094.  
  8095. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  8096. return [count, sumResult];
  8097. }
  8098.  
  8099. function mergeItemsObj(obj1, obj2) {
  8100. for (const key in obj2) {
  8101. if (obj1[key]) {
  8102. if (typeof obj1[key] == 'object') {
  8103. for (const innerKey in obj2[key]) {
  8104. obj1[key][innerKey] = (obj1[key][innerKey] || 0) + obj2[key][innerKey];
  8105. }
  8106. } else {
  8107. obj1[key] += obj2[key] || 0;
  8108. }
  8109. } else {
  8110. obj1[key] = obj2[key];
  8111. }
  8112. }
  8113.  
  8114. return obj1;
  8115. }
  8116.  
  8117. /**
  8118. * Collect all mail, except letters with energy and charges of the portal
  8119. *
  8120. * Собрать всю почту, кроме писем с энергией и зарядами портала
  8121. */
  8122. function mailGetAll() {
  8123. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  8124.  
  8125. return Send(getMailInfo).then(dataMail => {
  8126. const letters = dataMail.results[0].result.response.letters;
  8127. const letterIds = lettersFilter(letters);
  8128. if (!letterIds.length) {
  8129. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8130. return;
  8131. }
  8132.  
  8133. const calls = [
  8134. { name: "mailFarm", args: { letterIds }, ident: "body" }
  8135. ];
  8136.  
  8137. return Send(JSON.stringify({ calls })).then(res => {
  8138. const lettersIds = res.results[0].result.response;
  8139. if (lettersIds) {
  8140. const countLetters = Object.keys(lettersIds).length;
  8141. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  8142. }
  8143. });
  8144. });
  8145. }
  8146.  
  8147. /**
  8148. * Filters received emails
  8149. *
  8150. * Фильтрует получаемые письма
  8151. */
  8152. function lettersFilter(letters) {
  8153. const lettersIds = [];
  8154. for (let l in letters) {
  8155. letter = letters[l];
  8156. const reward = letter?.reward;
  8157. if (!reward || !Object.keys(reward).length) {
  8158. continue;
  8159. }
  8160. /**
  8161. * Mail Collection Exceptions
  8162. *
  8163. * Исключения на сбор писем
  8164. */
  8165. const isFarmLetter = !(
  8166. /** Portals // сферы портала */
  8167. (reward?.refillable ? reward.refillable[45] : false) ||
  8168. /** Energy // энергия */
  8169. (reward?.stamina ? reward.stamina : false) ||
  8170. /** accelerating energy gain // ускорение набора энергии */
  8171. (reward?.buff ? true : false) ||
  8172. /** VIP Points // вип очки */
  8173. (reward?.vipPoints ? reward.vipPoints : false) ||
  8174. /** souls of heroes // душы героев */
  8175. (reward?.fragmentHero ? true : false) ||
  8176. /** heroes // герои */
  8177. (reward?.bundleHeroReward ? true : false)
  8178. );
  8179. if (isFarmLetter) {
  8180. lettersIds.push(~~letter.id);
  8181. continue;
  8182. }
  8183. /**
  8184. * Если до окончания годности письма менее 24 часов,
  8185. * то оно собирается не смотря на исключения
  8186. */
  8187. const availableUntil = +letter?.availableUntil;
  8188. if (availableUntil) {
  8189. const maxTimeLeft = 24 * 60 * 60 * 1000;
  8190. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  8191. console.log('Time left:', timeLeft)
  8192. if (timeLeft < maxTimeLeft) {
  8193. lettersIds.push(~~letter.id);
  8194. continue;
  8195. }
  8196. }
  8197. }
  8198. return lettersIds;
  8199. }
  8200.  
  8201. /**
  8202. * Displaying information about the areas of the portal and attempts on the VG
  8203. *
  8204. * Отображение информации о сферах портала и попытках на ВГ
  8205. */
  8206. async function justInfo() {
  8207. return new Promise(async (resolve, reject) => {
  8208. const calls = [{
  8209. name: "userGetInfo",
  8210. args: {},
  8211. ident: "userGetInfo"
  8212. },
  8213. {
  8214. name: "clanWarGetInfo",
  8215. args: {},
  8216. ident: "clanWarGetInfo"
  8217. },
  8218. {
  8219. name: "titanArenaGetStatus",
  8220. args: {},
  8221. ident: "titanArenaGetStatus"
  8222. }];
  8223. const result = await Send(JSON.stringify({ calls }));
  8224. const infos = result.results;
  8225. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  8226. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  8227. const arePointsMax = infos[1].result.response?.arePointsMax;
  8228. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  8229. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  8230.  
  8231. const sanctuaryButton = buttons['testAdventure'].button;
  8232. const sanctuaryDot = sanctuaryButton.querySelector('.scriptMenu_dot');
  8233. const clanWarButton = buttons['goToClanWar'].button;
  8234. const clanWarDot = clanWarButton.querySelector('.scriptMenu_dot');
  8235. const titansArenaButton = buttons['testTitanArena'].button;
  8236. const titansArenaDot = titansArenaButton.querySelector('.scriptMenu_dot');
  8237.  
  8238. if (portalSphere.amount) {
  8239. sanctuaryButton.classList.add('scriptMenu_attention');
  8240. sanctuaryDot.title = `${portalSphere.amount} ${I18N('PORTALS')}`;
  8241. sanctuaryDot.innerText = portalSphere.amount;
  8242. sanctuaryDot.style.backgroundColor = 'red';
  8243. } else {
  8244. sanctuaryButton.classList.remove('scriptMenu_attention');
  8245. }
  8246. if (clanWarMyTries && !arePointsMax) {
  8247. clanWarButton.classList.add('scriptMenu_attention');
  8248. clanWarDot.title = `${clanWarMyTries} ${I18N('ATTEMPTS')}`;
  8249. clanWarDot.innerText = clanWarMyTries;
  8250. clanWarDot.style.backgroundColor = 'red';
  8251. } else {
  8252. clanWarButton.classList.remove('scriptMenu_attention');
  8253. }
  8254.  
  8255. if (titansLevel < 7 && titansStatus == 'battle') { ;
  8256. titansArenaButton.classList.add('scriptMenu_attention');
  8257. titansArenaDot.title = `${titansLevel} ${I18N('LEVEL')}`;
  8258. titansArenaDot.innerText = titansLevel;
  8259. titansArenaDot.style.backgroundColor = 'red';
  8260. } else {
  8261. titansArenaButton.classList.remove('scriptMenu_attention');
  8262. }
  8263.  
  8264. const imgPortal =
  8265. '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';
  8266.  
  8267. setProgress('<img src="' + imgPortal + '" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  8268. resolve();
  8269. });
  8270. }
  8271.  
  8272. async function getDailyBonus() {
  8273. const dailyBonusInfo = await Send(JSON.stringify({
  8274. calls: [{
  8275. name: "dailyBonusGetInfo",
  8276. args: {},
  8277. ident: "body"
  8278. }]
  8279. })).then(e => e.results[0].result.response);
  8280. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  8281.  
  8282. if (!availableToday) {
  8283. console.log('Уже собрано');
  8284. return;
  8285. }
  8286.  
  8287. const currentVipPoints = +userInfo.vipPoints;
  8288. const dailyBonusStat = lib.getData('dailyBonusStatic');
  8289. const vipInfo = lib.getData('level').vip;
  8290. let currentVipLevel = 0;
  8291. for (let i in vipInfo) {
  8292. vipLvl = vipInfo[i];
  8293. if (currentVipPoints >= vipLvl.vipPoints) {
  8294. currentVipLevel = vipLvl.level;
  8295. }
  8296. }
  8297. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  8298.  
  8299. const calls = [{
  8300. name: "dailyBonusFarm",
  8301. args: {
  8302. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  8303. },
  8304. ident: "body"
  8305. }];
  8306.  
  8307. const result = await Send(JSON.stringify({ calls }));
  8308. if (result.error) {
  8309. console.error(result.error);
  8310. return;
  8311. }
  8312.  
  8313. const reward = result.results[0].result.response;
  8314. const type = Object.keys(reward).pop();
  8315. const itemId = Object.keys(reward[type]).pop();
  8316. const count = reward[type][itemId];
  8317. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  8318.  
  8319. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  8320. }
  8321.  
  8322. async function farmStamina(lootBoxId = 148) {
  8323. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  8324. .then(e => e.results[0].result.response.consumable[148]);
  8325.  
  8326. /** Добавить другие ящики */
  8327. /**
  8328. * 144 - медная шкатулка
  8329. * 145 - бронзовая шкатулка
  8330. * 148 - платиновая шкатулка
  8331. */
  8332. if (!lootBox) {
  8333. setProgress(I18N('NO_BOXES'), true);
  8334. return;
  8335. }
  8336.  
  8337. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  8338. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  8339. { result: false, isClose: true },
  8340. { msg: I18N('BTN_YES'), result: true },
  8341. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  8342. ]);
  8343. if (!+result) {
  8344. return;
  8345. }
  8346.  
  8347. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  8348. maxFarmEnergy = +result;
  8349. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  8350. } else {
  8351. maxFarmEnergy = 0;
  8352. }
  8353.  
  8354. let collectEnergy = 0;
  8355. for (let count = lootBox; count > 0; count--) {
  8356. const response = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}').then(
  8357. (e) => e.results[0].result.response
  8358. );
  8359. const result = Object.values(response).pop();
  8360. if ('stamina' in result) {
  8361. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8362. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  8363. if (!maxFarmEnergy) {
  8364. return;
  8365. }
  8366. collectEnergy += +result.stamina;
  8367. if (collectEnergy >= maxFarmEnergy) {
  8368. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  8369. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  8370. return;
  8371. }
  8372. } else {
  8373. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8374. console.log(result);
  8375. }
  8376. }
  8377.  
  8378. setProgress(I18N('BOXES_OVER'), true);
  8379. }
  8380.  
  8381. async function fillActive() {
  8382. const data = await Send(JSON.stringify({
  8383. calls: [{
  8384. name: "questGetAll",
  8385. args: {},
  8386. ident: "questGetAll"
  8387. }, {
  8388. name: "inventoryGet",
  8389. args: {},
  8390. ident: "inventoryGet"
  8391. }, {
  8392. name: "clanGetInfo",
  8393. args: {},
  8394. ident: "clanGetInfo"
  8395. }
  8396. ]
  8397. })).then(e => e.results.map(n => n.result.response));
  8398.  
  8399. const quests = data[0];
  8400. const inv = data[1];
  8401. const stat = data[2].stat;
  8402. const maxActive = 2000 - stat.todayItemsActivity;
  8403. if (maxActive <= 0) {
  8404. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  8405. return;
  8406. }
  8407. let countGetActive = 0;
  8408. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  8409. if (quest) {
  8410. countGetActive = 1750 - quest.progress;
  8411. }
  8412. if (countGetActive <= 0) {
  8413. countGetActive = maxActive;
  8414. }
  8415. console.log(countGetActive);
  8416.  
  8417. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  8418. { result: false, isClose: true },
  8419. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  8420. ]));
  8421.  
  8422. if (!countGetActive) {
  8423. return;
  8424. }
  8425.  
  8426. if (countGetActive > maxActive) {
  8427. countGetActive = maxActive;
  8428. }
  8429.  
  8430. const items = lib.getData('inventoryItem');
  8431.  
  8432. let itemsInfo = [];
  8433. for (let type of ['gear', 'scroll']) {
  8434. for (let i in inv[type]) {
  8435. const v = items[type][i]?.enchantValue || 0;
  8436. itemsInfo.push({
  8437. id: i,
  8438. count: inv[type][i],
  8439. v,
  8440. type
  8441. })
  8442. }
  8443. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  8444. for (let i in inv[invType]) {
  8445. const v = items[type][i]?.fragmentEnchantValue || 0;
  8446. itemsInfo.push({
  8447. id: i,
  8448. count: inv[invType][i],
  8449. v,
  8450. type: invType
  8451. })
  8452. }
  8453. }
  8454. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  8455. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  8456. console.log(itemsInfo);
  8457. const activeItem = itemsInfo.shift();
  8458. console.log(activeItem);
  8459. const countItem = Math.ceil(countGetActive / activeItem.v);
  8460. if (countItem > activeItem.count) {
  8461. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  8462. console.log(activeItem);
  8463. return;
  8464. }
  8465.  
  8466. await Send(JSON.stringify({
  8467. calls: [{
  8468. name: "clanItemsForActivity",
  8469. args: {
  8470. items: {
  8471. [activeItem.type]: {
  8472. [activeItem.id]: countItem
  8473. }
  8474. }
  8475. },
  8476. ident: "body"
  8477. }]
  8478. })).then(e => {
  8479. /** TODO: Вывести потраченые предметы */
  8480. console.log(e);
  8481. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  8482. });
  8483. }
  8484.  
  8485. async function buyHeroFragments() {
  8486. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  8487. .then(e => e.results.map(n => n.result.response));
  8488. const inv = result[0];
  8489. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  8490. const calls = [];
  8491.  
  8492. for (let shop of shops) {
  8493. const slots = Object.values(shop.slots);
  8494. for (const slot of slots) {
  8495. /* Уже куплено */
  8496. if (slot.bought) {
  8497. continue;
  8498. }
  8499. /* Не душа героя */
  8500. if (!('fragmentHero' in slot.reward)) {
  8501. continue;
  8502. }
  8503. const coin = Object.keys(slot.cost).pop();
  8504. const coinId = Object.keys(slot.cost[coin]).pop();
  8505. const stock = inv[coin][coinId] || 0;
  8506. /* Не хватает на покупку */
  8507. if (slot.cost[coin][coinId] > stock) {
  8508. continue;
  8509. }
  8510. inv[coin][coinId] -= slot.cost[coin][coinId];
  8511. calls.push({
  8512. name: "shopBuy",
  8513. args: {
  8514. shopId: shop.id,
  8515. slot: slot.id,
  8516. cost: slot.cost,
  8517. reward: slot.reward,
  8518. },
  8519. ident: `shopBuy_${shop.id}_${slot.id}`,
  8520. })
  8521. }
  8522. }
  8523.  
  8524. if (!calls.length) {
  8525. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  8526. return;
  8527. }
  8528.  
  8529. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8530. if (!bought) {
  8531. console.log('что-то пошло не так')
  8532. return;
  8533. }
  8534.  
  8535. let countHeroSouls = 0;
  8536. for (const buy of bought) {
  8537. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  8538. }
  8539. console.log(countHeroSouls, bought, calls);
  8540. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  8541. }
  8542.  
  8543. /** Открыть платные сундуки в Запределье за 90 */
  8544. async function bossOpenChestPay() {
  8545. const callsNames = ['userGetInfo', 'bossGetAll', 'specialOffer_getAll', 'getTime'];
  8546. const info = await Send({ calls: callsNames.map((name) => ({ name, args: {}, ident: name })) }).then((e) =>
  8547. e.results.map((n) => n.result.response)
  8548. );
  8549.  
  8550. const user = info[0];
  8551. const boses = info[1];
  8552. const offers = info[2];
  8553. const time = info[3];
  8554.  
  8555. const discountOffer = offers.find((e) => e.offerType == 'costReplaceOutlandChest');
  8556.  
  8557. let discount = 1;
  8558. if (discountOffer && discountOffer.endTime > time) {
  8559. discount = 1 - discountOffer.offerData.outlandChest.discountPercent / 100;
  8560. }
  8561.  
  8562. cost9chests = 540 * discount;
  8563. cost18chests = 1740 * discount;
  8564. costFirstChest = 90 * discount;
  8565. costSecondChest = 200 * discount;
  8566.  
  8567. const currentStarMoney = user.starMoney;
  8568. if (currentStarMoney < cost9chests) {
  8569. setProgress('Недостаточно изюма, нужно ' + cost9chests + ' у Вас ' + currentStarMoney, true);
  8570. return;
  8571. }
  8572.  
  8573. const imgEmerald =
  8574. "<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='>";
  8575.  
  8576. if (currentStarMoney < cost9chests) {
  8577. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney, imgEmerald }), true);
  8578. return;
  8579. }
  8580.  
  8581. const buttons = [{ result: false, isClose: true }];
  8582.  
  8583. if (currentStarMoney >= cost9chests) {
  8584. buttons.push({
  8585. msg: I18N('BUY_OUTLAND_BTN', { count: 9, countEmerald: cost9chests, imgEmerald }),
  8586. result: [costFirstChest, costFirstChest, 0],
  8587. });
  8588. }
  8589.  
  8590. if (currentStarMoney >= cost18chests) {
  8591. buttons.push({
  8592. msg: I18N('BUY_OUTLAND_BTN', { count: 18, countEmerald: cost18chests, imgEmerald }),
  8593. result: [costFirstChest, costFirstChest, 0, costSecondChest, costSecondChest, 0],
  8594. });
  8595. }
  8596.  
  8597. const answer = await popup.confirm(`<div style="margin-bottom: 15px;">${I18N('BUY_OUTLAND')}</div>`, buttons);
  8598.  
  8599. if (!answer) {
  8600. return;
  8601. }
  8602.  
  8603. const callBoss = [];
  8604. let n = 0;
  8605. for (let boss of boses) {
  8606. const bossId = boss.id;
  8607. if (boss.chestNum != 2) {
  8608. continue;
  8609. }
  8610. const calls = [];
  8611. for (const starmoney of answer) {
  8612. calls.push({
  8613. name: 'bossOpenChest',
  8614. args: {
  8615. amount: 1,
  8616. bossId,
  8617. starmoney,
  8618. },
  8619. ident: 'bossOpenChest_' + ++n,
  8620. });
  8621. }
  8622. callBoss.push(calls);
  8623. }
  8624.  
  8625. if (!callBoss.length) {
  8626. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  8627. return;
  8628. }
  8629.  
  8630. let count = 0;
  8631. let errors = 0;
  8632. for (const calls of callBoss) {
  8633. const result = await Send({ calls });
  8634. console.log(result);
  8635. if (result?.results) {
  8636. count += result.results.length;
  8637. } else {
  8638. errors++;
  8639. }
  8640. }
  8641.  
  8642. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ${count}`, true);
  8643. }
  8644.  
  8645. async function autoRaidAdventure() {
  8646. const calls = [
  8647. {
  8648. name: "userGetInfo",
  8649. args: {},
  8650. ident: "userGetInfo"
  8651. },
  8652. {
  8653. name: "adventure_raidGetInfo",
  8654. args: {},
  8655. ident: "adventure_raidGetInfo"
  8656. }
  8657. ];
  8658. const result = await Send(JSON.stringify({ calls }))
  8659. .then(e => e.results.map(n => n.result.response));
  8660.  
  8661. const portalSphere = result[0].refillable.find(n => n.id == 45);
  8662. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  8663. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  8664.  
  8665. if (!portalSphere.amount || !adventureId) {
  8666. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  8667. return;
  8668. }
  8669.  
  8670. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  8671. { result: false, isClose: true },
  8672. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  8673. ]));
  8674.  
  8675. if (!countRaid) {
  8676. return;
  8677. }
  8678.  
  8679. if (countRaid > portalSphere.amount) {
  8680. countRaid = portalSphere.amount;
  8681. }
  8682.  
  8683. const resultRaid = await Send(JSON.stringify({
  8684. calls: [...Array(countRaid)].map((e, i) => ({
  8685. name: "adventure_raid",
  8686. args: {
  8687. adventureId
  8688. },
  8689. ident: `body_${i}`
  8690. }))
  8691. })).then(e => e.results.map(n => n.result.response));
  8692.  
  8693. if (!resultRaid.length) {
  8694. console.log(resultRaid);
  8695. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  8696. return;
  8697. }
  8698.  
  8699. console.log(resultRaid, adventureId, portalSphere.amount);
  8700. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  8701. }
  8702.  
  8703. /** Вывести всю клановую статистику в консоль браузера */
  8704. async function clanStatistic() {
  8705. const copy = function (text) {
  8706. const copyTextarea = document.createElement("textarea");
  8707. copyTextarea.style.opacity = "0";
  8708. copyTextarea.textContent = text;
  8709. document.body.appendChild(copyTextarea);
  8710. copyTextarea.select();
  8711. document.execCommand("copy");
  8712. document.body.removeChild(copyTextarea);
  8713. delete copyTextarea;
  8714. }
  8715. const calls = [
  8716. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  8717. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  8718. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  8719. ];
  8720.  
  8721. const result = await Send(JSON.stringify({ calls }));
  8722.  
  8723. const dataClanInfo = result.results[0].result.response;
  8724. const dataClanStat = result.results[1].result.response;
  8725. const dataClanLog = result.results[2].result.response;
  8726.  
  8727. const membersStat = {};
  8728. for (let i = 0; i < dataClanStat.stat.length; i++) {
  8729. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  8730. }
  8731.  
  8732. const joinStat = {};
  8733. historyLog = dataClanLog.history;
  8734. for (let j in historyLog) {
  8735. his = historyLog[j];
  8736. if (his.event == 'join') {
  8737. joinStat[his.userId] = his.ctime;
  8738. }
  8739. }
  8740.  
  8741. const infoArr = [];
  8742. const members = dataClanInfo.clan.members;
  8743. for (let n in members) {
  8744. var member = [
  8745. n,
  8746. members[n].name,
  8747. members[n].level,
  8748. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  8749. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  8750. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  8751. membersStat[n].activity.reverse().join('\t'),
  8752. membersStat[n].adventureStat.reverse().join('\t'),
  8753. membersStat[n].clanGifts.reverse().join('\t'),
  8754. membersStat[n].clanWarStat.reverse().join('\t'),
  8755. membersStat[n].dungeonActivity.reverse().join('\t'),
  8756. ];
  8757. infoArr.push(member);
  8758. }
  8759. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  8760. console.log(info);
  8761. copy(info);
  8762. setProgress(I18N('CLAN_STAT_COPY'), true);
  8763. }
  8764.  
  8765. async function buyInStoreForGold() {
  8766. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  8767. const shops = result[0];
  8768. const user = result[1];
  8769. let gold = user.gold;
  8770. const calls = [];
  8771. if (shops[17]) {
  8772. const slots = shops[17].slots;
  8773. for (let i = 1; i <= 2; i++) {
  8774. if (!slots[i].bought) {
  8775. const costGold = slots[i].cost.gold;
  8776. if ((gold - costGold) < 0) {
  8777. continue;
  8778. }
  8779. gold -= costGold;
  8780. calls.push({
  8781. name: "shopBuy",
  8782. args: {
  8783. shopId: 17,
  8784. slot: i,
  8785. cost: slots[i].cost,
  8786. reward: slots[i].reward,
  8787. },
  8788. ident: 'body_' + i,
  8789. })
  8790. }
  8791. }
  8792. }
  8793. const slots = shops[1].slots;
  8794. for (let i = 4; i <= 6; i++) {
  8795. if (!slots[i].bought && slots[i]?.cost?.gold) {
  8796. const costGold = slots[i].cost.gold;
  8797. if ((gold - costGold) < 0) {
  8798. continue;
  8799. }
  8800. gold -= costGold;
  8801. calls.push({
  8802. name: "shopBuy",
  8803. args: {
  8804. shopId: 1,
  8805. slot: i,
  8806. cost: slots[i].cost,
  8807. reward: slots[i].reward,
  8808. },
  8809. ident: 'body_' + i,
  8810. })
  8811. }
  8812. }
  8813.  
  8814. if (!calls.length) {
  8815. setProgress(I18N('NOTHING_BUY'), true);
  8816. return;
  8817. }
  8818.  
  8819. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8820. console.log(resultBuy);
  8821. const countBuy = resultBuy.length;
  8822. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  8823. }
  8824.  
  8825. function rewardsAndMailFarm() {
  8826. return new Promise(function (resolve, reject) {
  8827. let questGetAllCall = {
  8828. calls: [{
  8829. name: "questGetAll",
  8830. args: {},
  8831. ident: "questGetAll"
  8832. }, {
  8833. name: "mailGetAll",
  8834. args: {},
  8835. ident: "mailGetAll"
  8836. }]
  8837. }
  8838. send(JSON.stringify(questGetAllCall), function (data) {
  8839. if (!data) return;
  8840. const questGetAll = data.results[0].result.response.filter((e) => e.state == 2);
  8841. const questBattlePass = lib.getData('quest').battlePass;
  8842. const questChainBPass = lib.getData('battlePass').questChain;
  8843. const listBattlePass = lib.getData('battlePass').list;
  8844.  
  8845. const questAllFarmCall = {
  8846. calls: [],
  8847. };
  8848. const questIds = [];
  8849. for (let quest of questGetAll) {
  8850. if (quest.id >= 2001e4) {
  8851. continue;
  8852. }
  8853. if (quest.id > 1e6 && quest.id < 2e7) {
  8854. const questInfo = questBattlePass[quest.id];
  8855. const chain = questChainBPass[questInfo.chain];
  8856. if (chain.requirement?.battlePassTicket) {
  8857. continue;
  8858. }
  8859. const battlePass = listBattlePass[chain.battlePass];
  8860. const startTime = battlePass.startCondition.time.value * 1e3
  8861. const endTime = new Date(startTime + battlePass.duration * 1e3);
  8862. if (startTime > Date.now() || endTime < Date.now()) {
  8863. continue;
  8864. }
  8865. }
  8866. if (quest.id >= 2e7) {
  8867. questIds.push(quest.id);
  8868. continue;
  8869. }
  8870. questAllFarmCall.calls.push({
  8871. name: 'questFarm',
  8872. args: {
  8873. questId: quest.id,
  8874. },
  8875. ident: `questFarm_${quest.id}`,
  8876. });
  8877. }
  8878.  
  8879. if (questIds.length) {
  8880. questAllFarmCall.calls.push({
  8881. name: 'quest_questsFarm',
  8882. args: { questIds },
  8883. ident: 'quest_questsFarm',
  8884. });
  8885. }
  8886.  
  8887. let letters = data?.results[1]?.result?.response?.letters;
  8888. letterIds = lettersFilter(letters);
  8889.  
  8890. if (letterIds.length) {
  8891. questAllFarmCall.calls.push({
  8892. name: 'mailFarm',
  8893. args: { letterIds },
  8894. ident: 'mailFarm',
  8895. });
  8896. }
  8897.  
  8898. if (!questAllFarmCall.calls.length) {
  8899. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8900. resolve();
  8901. return;
  8902. }
  8903.  
  8904. send(JSON.stringify(questAllFarmCall), async function (res) {
  8905. let countQuests = 0;
  8906. let countMail = 0;
  8907. let questsIds = [];
  8908. for (let call of res.results) {
  8909. if (call.ident.includes('questFarm')) {
  8910. countQuests++;
  8911. } else if (call.ident.includes('questsFarm')) {
  8912. countQuests += Object.keys(call.result.response).length;
  8913. } else if (call.ident.includes('mailFarm')) {
  8914. countMail = Object.keys(call.result.response).length;
  8915. }
  8916.  
  8917. const newQuests = call.result.newQuests;
  8918. if (newQuests) {
  8919. for (let quest of newQuests) {
  8920. if ((quest.id < 1e6 || (quest.id >= 2e7 && quest.id < 2001e4)) && quest.state == 2) {
  8921. questsIds.push(quest.id);
  8922. }
  8923. }
  8924. }
  8925. }
  8926.  
  8927. while (questsIds.length) {
  8928. const questIds = [];
  8929. const calls = [];
  8930. for (let questId of questsIds) {
  8931. if (questId < 1e6) {
  8932. calls.push({
  8933. name: 'questFarm',
  8934. args: {
  8935. questId,
  8936. },
  8937. ident: `questFarm_${questId}`,
  8938. });
  8939. countQuests++;
  8940. } else if (questId >= 2e7 && questId < 2001e4) {
  8941. questIds.push(questId);
  8942. countQuests++;
  8943. }
  8944. }
  8945. calls.push({
  8946. name: 'quest_questsFarm',
  8947. args: { questIds },
  8948. ident: 'body',
  8949. });
  8950. const results = await Send({ calls }).then((e) => e.results.map((e) => e.result));
  8951. questsIds = [];
  8952. for (const result of results) {
  8953. const newQuests = result.newQuests;
  8954. if (newQuests) {
  8955. for (let quest of newQuests) {
  8956. if (quest.state == 2) {
  8957. questsIds.push(quest.id);
  8958. }
  8959. }
  8960. }
  8961. }
  8962. }
  8963.  
  8964. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  8965. resolve();
  8966. });
  8967. });
  8968. })
  8969. }
  8970.  
  8971. class epicBrawl {
  8972. timeout = null;
  8973. time = null;
  8974.  
  8975. constructor() {
  8976. if (epicBrawl.inst) {
  8977. return epicBrawl.inst;
  8978. }
  8979. epicBrawl.inst = this;
  8980. return this;
  8981. }
  8982.  
  8983. runTimeout(func, timeDiff) {
  8984. const worker = new Worker(URL.createObjectURL(new Blob([`
  8985. self.onmessage = function(e) {
  8986. const timeDiff = e.data;
  8987.  
  8988. if (timeDiff > 0) {
  8989. setTimeout(() => {
  8990. self.postMessage(1);
  8991. self.close();
  8992. }, timeDiff);
  8993. }
  8994. };
  8995. `])));
  8996. worker.postMessage(timeDiff);
  8997. worker.onmessage = () => {
  8998. func();
  8999. };
  9000. return true;
  9001. }
  9002.  
  9003. timeDiff(date1, date2) {
  9004. const date1Obj = new Date(date1);
  9005. const date2Obj = new Date(date2);
  9006.  
  9007. const timeDiff = Math.abs(date2Obj - date1Obj);
  9008.  
  9009. const totalSeconds = timeDiff / 1000;
  9010. const minutes = Math.floor(totalSeconds / 60);
  9011. const seconds = Math.floor(totalSeconds % 60);
  9012.  
  9013. const formattedMinutes = String(minutes).padStart(2, '0');
  9014. const formattedSeconds = String(seconds).padStart(2, '0');
  9015.  
  9016. return `${formattedMinutes}:${formattedSeconds}`;
  9017. }
  9018.  
  9019. check() {
  9020. console.log(new Date(this.time))
  9021. if (Date.now() > this.time) {
  9022. this.timeout = null;
  9023. this.start()
  9024. return;
  9025. }
  9026. this.timeout = this.runTimeout(() => this.check(), 6e4);
  9027. return this.timeDiff(this.time, Date.now())
  9028. }
  9029.  
  9030. async start() {
  9031. if (this.timeout) {
  9032. const time = this.timeDiff(this.time, Date.now());
  9033. console.log(new Date(this.time))
  9034. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  9035. return;
  9036. }
  9037. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  9038. 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));
  9039. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  9040. this.time = (refill.lastRefill + 3600) * 1000
  9041. const attempts = refill.amount;
  9042. if (!attempts) {
  9043. console.log(new Date(this.time));
  9044. const time = this.check();
  9045. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  9046. return;
  9047. }
  9048.  
  9049. if (!teamInfo[0].epic_brawl) {
  9050. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  9051. return;
  9052. }
  9053.  
  9054. const args = {
  9055. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  9056. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  9057. favor: teamInfo[1].epic_brawl,
  9058. }
  9059.  
  9060. let wins = 0;
  9061. let coins = 0;
  9062. let streak = { progress: 0, nextStage: 0 };
  9063. for (let i = attempts; i > 0; i--) {
  9064. const info = await Send(JSON.stringify({
  9065. calls: [
  9066. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  9067. ]
  9068. })).then(e => e.results.map(n => n.result.response));
  9069.  
  9070. const { progress, result } = await Calc(info[1].battle);
  9071. 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));
  9072.  
  9073. const resultInfo = endResult[0].result;
  9074. streak = endResult[1];
  9075.  
  9076. wins += resultInfo.win;
  9077. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  9078.  
  9079. console.log(endResult[0].result)
  9080. if (endResult[1].progress == endResult[1].nextStage) {
  9081. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  9082. coins += farm.coin[39];
  9083. }
  9084.  
  9085. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9086. i, wins, attempts, coins,
  9087. progress: streak.progress,
  9088. nextStage: streak.nextStage,
  9089. end: '',
  9090. }), false, hideProgress);
  9091. }
  9092.  
  9093. console.log(new Date(this.time));
  9094. const time = this.check();
  9095. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9096. wins, attempts, coins,
  9097. i: '',
  9098. progress: streak.progress,
  9099. nextStage: streak.nextStage,
  9100. end: I18N('ATTEMPT_ENDED', { time }),
  9101. }), false, hideProgress);
  9102. }
  9103. }
  9104.  
  9105. function countdownTimer(seconds, message) {
  9106. message = message || I18N('TIMER');
  9107. const stopTimer = Date.now() + seconds * 1e3
  9108. return new Promise(resolve => {
  9109. const interval = setInterval(async () => {
  9110. const now = Date.now();
  9111. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  9112. if (now > stopTimer) {
  9113. clearInterval(interval);
  9114. setProgress('', 1);
  9115. resolve();
  9116. }
  9117. }, 100);
  9118. });
  9119. }
  9120.  
  9121. this.HWHFuncs.countdownTimer = countdownTimer;
  9122.  
  9123. /** Набить килов в горниле душк */
  9124. async function bossRatingEventSouls() {
  9125. const data = await Send({
  9126. calls: [
  9127. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  9128. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  9129. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  9130. ]
  9131. });
  9132. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  9133. if (!bossEventInfo) {
  9134. setProgress('Эвент завершен', true);
  9135. return;
  9136. }
  9137.  
  9138. if (bossEventInfo.progress.score > 250) {
  9139. setProgress('Уже убито больше 250 врагов');
  9140. rewardBossRatingEventSouls();
  9141. return;
  9142. }
  9143. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  9144. const heroGetAllList = data.results[0].result.response;
  9145. const usedHeroes = bossEventInfo.progress.usedHeroes;
  9146. const heroList = [];
  9147.  
  9148. for (let heroId in heroGetAllList) {
  9149. let hero = heroGetAllList[heroId];
  9150. if (usedHeroes.includes(hero.id)) {
  9151. continue;
  9152. }
  9153. heroList.push(hero.id);
  9154. }
  9155.  
  9156. if (!heroList.length) {
  9157. setProgress('Нет героев', true);
  9158. return;
  9159. }
  9160.  
  9161. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  9162. const petLib = lib.getData('pet');
  9163. let count = 1;
  9164.  
  9165. for (const heroId of heroList) {
  9166. const args = {
  9167. heroes: [heroId],
  9168. pet
  9169. }
  9170. /** Поиск питомца для героя */
  9171. for (const petId of availablePets) {
  9172. if (petLib[petId].favorHeroes.includes(heroId)) {
  9173. args.favor = {
  9174. [heroId]: petId
  9175. }
  9176. break;
  9177. }
  9178. }
  9179.  
  9180. const calls = [{
  9181. name: "bossRatingEvent_startBattle",
  9182. args,
  9183. ident: "body"
  9184. }, {
  9185. name: "offerGetAll",
  9186. args: {},
  9187. ident: "offerGetAll"
  9188. }];
  9189.  
  9190. const res = await Send({ calls });
  9191. count++;
  9192.  
  9193. if ('error' in res) {
  9194. console.error(res.error);
  9195. setProgress('Перезагрузите игру и попробуйте позже', true);
  9196. return;
  9197. }
  9198.  
  9199. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  9200. if (eventInfo.progress.score > 250) {
  9201. break;
  9202. }
  9203. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  9204. }
  9205.  
  9206. rewardBossRatingEventSouls();
  9207. }
  9208. /** Сбор награды из Горнила Душ */
  9209. async function rewardBossRatingEventSouls() {
  9210. const data = await Send({
  9211. calls: [
  9212. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  9213. ]
  9214. });
  9215.  
  9216. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  9217. if (!bossEventInfo) {
  9218. setProgress('Эвент завершен', true);
  9219. return;
  9220. }
  9221.  
  9222. const farmedChests = bossEventInfo.progress.farmedChests;
  9223. const score = bossEventInfo.progress.score;
  9224. // setProgress('Количество убитых врагов: ' + score);
  9225. const revard = bossEventInfo.reward;
  9226. const calls = [];
  9227.  
  9228. let count = 0;
  9229. for (let i = 1; i < 10; i++) {
  9230. if (farmedChests.includes(i)) {
  9231. continue;
  9232. }
  9233. if (score < revard[i].score) {
  9234. break;
  9235. }
  9236. calls.push({
  9237. name: "bossRatingEvent_getReward",
  9238. args: {
  9239. rewardId: i
  9240. },
  9241. ident: "body_" + i
  9242. });
  9243. count++;
  9244. }
  9245. if (!count) {
  9246. setProgress('Нечего собирать', true);
  9247. return;
  9248. }
  9249.  
  9250. Send({ calls }).then(e => {
  9251. console.log(e);
  9252. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  9253. })
  9254. }
  9255. /**
  9256. * Spin the Seer
  9257. *
  9258. * Покрутить провидца
  9259. */
  9260. async function rollAscension() {
  9261. const refillable = await Send({calls:[
  9262. {
  9263. name:"userGetInfo",
  9264. args:{},
  9265. ident:"userGetInfo"
  9266. }
  9267. ]}).then(e => e.results[0].result.response.refillable);
  9268. const i47 = refillable.find(i => i.id == 47);
  9269. if (i47?.amount) {
  9270. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  9271. setProgress(I18N('DONE'), true);
  9272. } else {
  9273. setProgress(I18N('NOT_ENOUGH_AP'), true);
  9274. }
  9275. }
  9276.  
  9277. /**
  9278. * Collect gifts for the New Year
  9279. *
  9280. * Собрать подарки на новый год
  9281. */
  9282. function getGiftNewYear() {
  9283. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  9284. const gifts = e.results[0].result.response.gifts;
  9285. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  9286. name: "newYearGiftOpen",
  9287. args: {
  9288. giftId: e.id
  9289. },
  9290. ident: `body_${e.id}`
  9291. }));
  9292. if (!calls.length) {
  9293. setProgress(I18N('NY_NO_GIFTS'), 5000);
  9294. return;
  9295. }
  9296. Send({ calls }).then(e => {
  9297. console.log(e.results)
  9298. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  9299. console.log(msg);
  9300. setProgress(msg, 5000);
  9301. });
  9302. })
  9303. }
  9304.  
  9305. async function updateArtifacts() {
  9306. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9307. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9308. { result: false, isClose: true }
  9309. ]);
  9310. if (!count) {
  9311. return;
  9312. }
  9313. const quest = new questRun;
  9314. await quest.autoInit();
  9315. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9316. const inventory = quest.questInfo['inventoryGet'];
  9317. const calls = [];
  9318. for (let i = count; i > 0; i--) {
  9319. const upArtifact = quest.getUpgradeArtifact();
  9320. if (!upArtifact.heroId) {
  9321. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9322. { msg: I18N('YES'), result: true },
  9323. { result: false, isClose: true }
  9324. ])) {
  9325. break;
  9326. } else {
  9327. return;
  9328. }
  9329. }
  9330. const hero = heroes.find(e => e.id == upArtifact.heroId);
  9331. hero.artifacts[upArtifact.slotId].level++;
  9332. inventory[upArtifact.costCurrency][upArtifact.costId] -= upArtifact.costValue;
  9333. calls.push({
  9334. name: "heroArtifactLevelUp",
  9335. args: {
  9336. heroId: upArtifact.heroId,
  9337. slotId: upArtifact.slotId
  9338. },
  9339. ident: `heroArtifactLevelUp_${i}`
  9340. });
  9341. }
  9342.  
  9343. if (!calls.length) {
  9344. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9345. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9346. return;
  9347. }
  9348.  
  9349. await Send(JSON.stringify({ calls })).then(e => {
  9350. if ('error' in e) {
  9351. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9352. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9353. } else {
  9354. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9355. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9356. }
  9357. });
  9358. }
  9359.  
  9360. window.sign = a => {
  9361. const i = this['\x78\x79\x7a'];
  9362. 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'))
  9363. }
  9364.  
  9365. async function updateSkins() {
  9366. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9367. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9368. { result: false, isClose: true }
  9369. ]);
  9370. if (!count) {
  9371. return;
  9372. }
  9373.  
  9374. const quest = new questRun;
  9375. await quest.autoInit();
  9376. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9377. const inventory = quest.questInfo['inventoryGet'];
  9378. const calls = [];
  9379. for (let i = count; i > 0; i--) {
  9380. const upSkin = quest.getUpgradeSkin();
  9381. if (!upSkin.heroId) {
  9382. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9383. { msg: I18N('YES'), result: true },
  9384. { result: false, isClose: true }
  9385. ])) {
  9386. break;
  9387. } else {
  9388. return;
  9389. }
  9390. }
  9391. const hero = heroes.find(e => e.id == upSkin.heroId);
  9392. hero.skins[upSkin.skinId]++;
  9393. inventory[upSkin.costCurrency][upSkin.costCurrencyId] -= upSkin.cost;
  9394. calls.push({
  9395. name: "heroSkinUpgrade",
  9396. args: {
  9397. heroId: upSkin.heroId,
  9398. skinId: upSkin.skinId
  9399. },
  9400. ident: `heroSkinUpgrade_${i}`
  9401. })
  9402. }
  9403.  
  9404. if (!calls.length) {
  9405. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9406. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9407. return;
  9408. }
  9409.  
  9410. await Send(JSON.stringify({ calls })).then(e => {
  9411. if ('error' in e) {
  9412. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9413. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9414. } else {
  9415. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9416. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9417. }
  9418. });
  9419. }
  9420.  
  9421. function getQuestionInfo(img, nameOnly = false) {
  9422. const libHeroes = Object.values(lib.data.hero);
  9423. const parts = img.split(':');
  9424. const id = parts[1];
  9425. switch (parts[0]) {
  9426. case 'titanArtifact_id':
  9427. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  9428. case 'titan':
  9429. return cheats.translate("LIB_HERO_NAME_" + id);
  9430. case 'skill':
  9431. return cheats.translate("LIB_SKILL_" + id);
  9432. case 'inventoryItem_gear':
  9433. return cheats.translate("LIB_GEAR_NAME_" + id);
  9434. case 'inventoryItem_coin':
  9435. return cheats.translate("LIB_COIN_NAME_" + id);
  9436. case 'artifact':
  9437. if (nameOnly) {
  9438. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  9439. }
  9440. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  9441. return {
  9442. /** Как называется этот артефакт? */
  9443. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  9444. /** Какому герою принадлежит этот артефакт? */
  9445. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  9446. };
  9447. case 'hero':
  9448. if (nameOnly) {
  9449. return cheats.translate("LIB_HERO_NAME_" + id);
  9450. }
  9451. artifacts = lib.data.hero[id].artifacts;
  9452. return {
  9453. /** Как зовут этого героя? */
  9454. name: cheats.translate("LIB_HERO_NAME_" + id),
  9455. /** Какой артефакт принадлежит этому герою? */
  9456. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  9457. };
  9458. }
  9459. }
  9460.  
  9461. function hintQuest(quest) {
  9462. const result = {};
  9463. if (quest?.questionIcon) {
  9464. const info = getQuestionInfo(quest.questionIcon);
  9465. if (info?.heroes) {
  9466. /** Какому герою принадлежит этот артефакт? */
  9467. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  9468. }
  9469. if (info?.artifact) {
  9470. /** Какой артефакт принадлежит этому герою? */
  9471. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  9472. }
  9473. if (typeof info == 'string') {
  9474. result.info = { name: info };
  9475. } else {
  9476. result.info = info;
  9477. }
  9478. }
  9479.  
  9480. if (quest.answers[0]?.answerIcon) {
  9481. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  9482. }
  9483.  
  9484. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  9485. return false;
  9486. }
  9487.  
  9488. let resultText = '';
  9489. if (result?.info) {
  9490. resultText += I18N('PICTURE') + result.info.name;
  9491. }
  9492. console.log(result);
  9493. if (result?.answer && result.answer.length) {
  9494. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  9495. }
  9496.  
  9497. return resultText;
  9498. }
  9499.  
  9500. async function farmBattlePass() {
  9501. const isFarmReward = (reward) => {
  9502. return !(reward?.buff || reward?.fragmentHero || reward?.bundleHeroReward);
  9503. };
  9504.  
  9505. const battlePassProcess = (pass) => {
  9506. if (!pass.id) {return []}
  9507. const levels = Object.values(lib.data.battlePass.level).filter(x => x.battlePass == pass.id)
  9508. const last_level = levels[levels.length - 1];
  9509. let actual = Math.max(...levels.filter(p => pass.exp >= p.experience).map(p => p.level))
  9510.  
  9511. if (pass.exp > last_level.experience) {
  9512. actual = last_level.level + (pass.exp - last_level.experience) / last_level.experienceByLevel;
  9513. }
  9514. const calls = [];
  9515. for(let i = 1; i <= actual; i++) {
  9516. const level = i >= last_level.level ? last_level : levels.find(l => l.level === i);
  9517. const reward = {free: level?.freeReward, paid:level?.paidReward};
  9518.  
  9519. if (!pass.rewards[i]?.free && isFarmReward(reward.free)) {
  9520. const args = {level: i, free:true};
  9521. if (!pass.gold) { args.id = pass.id }
  9522. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_free_${args.id}_${i}` });
  9523. }
  9524. if (pass.ticket && !pass.rewards[i]?.paid && isFarmReward(reward.paid)) {
  9525. const args = {level: i, free:false};
  9526. if (!pass.gold) { args.id = pass.id}
  9527. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_paid_${args.id}_${i}` });
  9528. }
  9529. }
  9530. return calls;
  9531. }
  9532.  
  9533. const passes = await Send({
  9534. calls: [
  9535. { name: 'battlePass_getInfo', args: {}, ident: 'getInfo' },
  9536. { name: 'battlePass_getSpecial', args: {}, ident: 'getSpecial' },
  9537. ],
  9538. }).then((e) => [{...e.results[0].result.response?.battlePass, gold: true}, ...Object.values(e.results[1].result.response)]);
  9539.  
  9540. const calls = passes.map(p => battlePassProcess(p)).flat()
  9541.  
  9542. if (!calls.length) {
  9543. setProgress(I18N('NOTHING_TO_COLLECT'));
  9544. return;
  9545. }
  9546.  
  9547. let results = await Send({calls});
  9548. if (results.error) {
  9549. console.log(results.error);
  9550. setProgress(I18N('SOMETHING_WENT_WRONG'));
  9551. } else {
  9552. setProgress(I18N('SEASON_REWARD_COLLECTED', {count: results.results.length}), true);
  9553. }
  9554. }
  9555.  
  9556. async function sellHeroSoulsForGold() {
  9557. let { fragmentHero, heroes } = await Send({
  9558. calls: [
  9559. { name: 'inventoryGet', args: {}, ident: 'inventoryGet' },
  9560. { name: 'heroGetAll', args: {}, ident: 'heroGetAll' },
  9561. ],
  9562. })
  9563. .then((e) => e.results.map((r) => r.result.response))
  9564. .then((e) => ({ fragmentHero: e[0].fragmentHero, heroes: e[1] }));
  9565.  
  9566. const calls = [];
  9567. for (let i in fragmentHero) {
  9568. if (heroes[i] && heroes[i].star == 6) {
  9569. calls.push({
  9570. name: 'inventorySell',
  9571. args: {
  9572. type: 'hero',
  9573. libId: i,
  9574. amount: fragmentHero[i],
  9575. fragment: true,
  9576. },
  9577. ident: 'inventorySell_' + i,
  9578. });
  9579. }
  9580. }
  9581. if (!calls.length) {
  9582. console.log(0);
  9583. return 0;
  9584. }
  9585. const rewards = await Send({ calls }).then((e) => e.results.map((r) => r.result?.response?.gold || 0));
  9586. const gold = rewards.reduce((e, a) => e + a, 0);
  9587. setProgress(I18N('GOLD_RECEIVED', { gold }), true);
  9588. }
  9589.  
  9590. /**
  9591. * Attack of the minions of Asgard
  9592. *
  9593. * Атака прислужников Асгарда
  9594. */
  9595. function testRaidNodes() {
  9596. const { executeRaidNodes } = HWHClasses;
  9597. return new Promise((resolve, reject) => {
  9598. const tower = new executeRaidNodes(resolve, reject);
  9599. tower.start();
  9600. });
  9601. }
  9602.  
  9603. /**
  9604. * Attack of the minions of Asgard
  9605. *
  9606. * Атака прислужников Асгарда
  9607. */
  9608. function executeRaidNodes(resolve, reject) {
  9609. let raidData = {
  9610. teams: [],
  9611. favor: {},
  9612. nodes: [],
  9613. attempts: 0,
  9614. countExecuteBattles: 0,
  9615. cancelBattle: 0,
  9616. }
  9617.  
  9618. callsExecuteRaidNodes = {
  9619. calls: [{
  9620. name: "clanRaid_getInfo",
  9621. args: {},
  9622. ident: "clanRaid_getInfo"
  9623. }, {
  9624. name: "teamGetAll",
  9625. args: {},
  9626. ident: "teamGetAll"
  9627. }, {
  9628. name: "teamGetFavor",
  9629. args: {},
  9630. ident: "teamGetFavor"
  9631. }]
  9632. }
  9633.  
  9634. this.start = function () {
  9635. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  9636. }
  9637.  
  9638. async function startRaidNodes(data) {
  9639. res = data.results;
  9640. clanRaidInfo = res[0].result.response;
  9641. teamGetAll = res[1].result.response;
  9642. teamGetFavor = res[2].result.response;
  9643.  
  9644. let index = 0;
  9645. let isNotFullPack = false;
  9646. for (let team of teamGetAll.clanRaid_nodes) {
  9647. if (team.length < 6) {
  9648. isNotFullPack = true;
  9649. }
  9650. raidData.teams.push({
  9651. data: {},
  9652. heroes: team.filter(id => id < 6000),
  9653. pet: team.filter(id => id >= 6000).pop(),
  9654. battleIndex: index++
  9655. });
  9656. }
  9657. raidData.favor = teamGetFavor.clanRaid_nodes;
  9658.  
  9659. if (isNotFullPack) {
  9660. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  9661. { msg: I18N('BTN_NO'), result: true },
  9662. { msg: I18N('BTN_YES'), result: false },
  9663. ])) {
  9664. endRaidNodes('isNotFullPack');
  9665. return;
  9666. }
  9667. }
  9668.  
  9669. raidData.nodes = clanRaidInfo.nodes;
  9670. raidData.attempts = clanRaidInfo.attempts;
  9671. setIsCancalBattle(false);
  9672.  
  9673. checkNodes();
  9674. }
  9675.  
  9676. function getAttackNode() {
  9677. for (let nodeId in raidData.nodes) {
  9678. let node = raidData.nodes[nodeId];
  9679. let points = 0
  9680. for (team of node.teams) {
  9681. points += team.points;
  9682. }
  9683. let now = Date.now() / 1000;
  9684. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  9685. let countTeam = node.teams.length;
  9686. delete raidData.nodes[nodeId];
  9687. return {
  9688. nodeId,
  9689. countTeam
  9690. };
  9691. }
  9692. }
  9693. return null;
  9694. }
  9695.  
  9696. function checkNodes() {
  9697. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  9698. let nodeInfo = getAttackNode();
  9699. if (nodeInfo && raidData.attempts) {
  9700. startNodeBattles(nodeInfo);
  9701. return;
  9702. }
  9703.  
  9704. endRaidNodes('EndRaidNodes');
  9705. }
  9706.  
  9707. function startNodeBattles(nodeInfo) {
  9708. let {nodeId, countTeam} = nodeInfo;
  9709. let teams = raidData.teams.slice(0, countTeam);
  9710. let heroes = raidData.teams.map(e => e.heroes).flat();
  9711. let favor = {...raidData.favor};
  9712. for (let heroId in favor) {
  9713. if (!heroes.includes(+heroId)) {
  9714. delete favor[heroId];
  9715. }
  9716. }
  9717.  
  9718. let calls = [{
  9719. name: "clanRaid_startNodeBattles",
  9720. args: {
  9721. nodeId,
  9722. teams,
  9723. favor
  9724. },
  9725. ident: "body"
  9726. }];
  9727.  
  9728. send(JSON.stringify({calls}), resultNodeBattles);
  9729. }
  9730.  
  9731. function resultNodeBattles(e) {
  9732. if (e['error']) {
  9733. endRaidNodes('nodeBattlesError', e['error']);
  9734. return;
  9735. }
  9736.  
  9737. console.log(e);
  9738. let battles = e.results[0].result.response.battles;
  9739. let promises = [];
  9740. let battleIndex = 0;
  9741. for (let battle of battles) {
  9742. battle.battleIndex = battleIndex++;
  9743. promises.push(calcBattleResult(battle));
  9744. }
  9745.  
  9746. Promise.all(promises)
  9747. .then(results => {
  9748. const endResults = {};
  9749. let isAllWin = true;
  9750. for (let r of results) {
  9751. isAllWin &&= r.result.win;
  9752. }
  9753. if (!isAllWin) {
  9754. cancelEndNodeBattle(results[0]);
  9755. return;
  9756. }
  9757. raidData.countExecuteBattles = results.length;
  9758. let timeout = 500;
  9759. for (let r of results) {
  9760. setTimeout(endNodeBattle, timeout, r);
  9761. timeout += 500;
  9762. }
  9763. });
  9764. }
  9765. /**
  9766. * Returns the battle calculation promise
  9767. *
  9768. * Возвращает промис расчета боя
  9769. */
  9770. function calcBattleResult(battleData) {
  9771. return new Promise(function (resolve, reject) {
  9772. BattleCalc(battleData, "get_clanPvp", resolve);
  9773. });
  9774. }
  9775. /**
  9776. * Cancels the fight
  9777. *
  9778. * Отменяет бой
  9779. */
  9780. function cancelEndNodeBattle(r) {
  9781. const fixBattle = function (heroes) {
  9782. for (const ids in heroes) {
  9783. hero = heroes[ids];
  9784. hero.energy = random(1, 999);
  9785. if (hero.hp > 0) {
  9786. hero.hp = random(1, hero.hp);
  9787. }
  9788. }
  9789. }
  9790. fixBattle(r.progress[0].attackers.heroes);
  9791. fixBattle(r.progress[0].defenders.heroes);
  9792. endNodeBattle(r);
  9793. }
  9794. /**
  9795. * Ends the fight
  9796. *
  9797. * Завершает бой
  9798. */
  9799. function endNodeBattle(r) {
  9800. let nodeId = r.battleData.result.nodeId;
  9801. let battleIndex = r.battleData.battleIndex;
  9802. let calls = [{
  9803. name: "clanRaid_endNodeBattle",
  9804. args: {
  9805. nodeId,
  9806. battleIndex,
  9807. result: r.result,
  9808. progress: r.progress
  9809. },
  9810. ident: "body"
  9811. }]
  9812.  
  9813. SendRequest(JSON.stringify({calls}), battleResult);
  9814. }
  9815. /**
  9816. * Processing the results of the battle
  9817. *
  9818. * Обработка результатов боя
  9819. */
  9820. function battleResult(e) {
  9821. if (e['error']) {
  9822. endRaidNodes('missionEndError', e['error']);
  9823. return;
  9824. }
  9825. r = e.results[0].result.response;
  9826. if (r['error']) {
  9827. if (r.reason == "invalidBattle") {
  9828. raidData.cancelBattle++;
  9829. checkNodes();
  9830. } else {
  9831. endRaidNodes('missionEndError', e['error']);
  9832. }
  9833. return;
  9834. }
  9835.  
  9836. if (!(--raidData.countExecuteBattles)) {
  9837. raidData.attempts--;
  9838. checkNodes();
  9839. }
  9840. }
  9841. /**
  9842. * Completing a task
  9843. *
  9844. * Завершение задачи
  9845. */
  9846. function endRaidNodes(reason, info) {
  9847. setIsCancalBattle(true);
  9848. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  9849. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  9850. console.log(reason, info);
  9851. resolve();
  9852. }
  9853. }
  9854.  
  9855. this.HWHClasses.executeRaidNodes = executeRaidNodes;
  9856.  
  9857. /**
  9858. * Asgard Boss Attack Replay
  9859. *
  9860. * Повтор атаки босса Асгарда
  9861. */
  9862. function testBossBattle() {
  9863. const { executeBossBattle } = HWHClasses;
  9864. return new Promise((resolve, reject) => {
  9865. const bossBattle = new executeBossBattle(resolve, reject);
  9866. bossBattle.start(lastBossBattle);
  9867. });
  9868. }
  9869.  
  9870. /**
  9871. * Asgard Boss Attack Replay
  9872. *
  9873. * Повтор атаки босса Асгарда
  9874. */
  9875. function executeBossBattle(resolve, reject) {
  9876.  
  9877. this.start = function (battleInfo) {
  9878. preCalcBattle(battleInfo);
  9879. }
  9880.  
  9881. function getBattleInfo(battle) {
  9882. return new Promise(function (resolve) {
  9883. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9884. BattleCalc(battle, getBattleType(battle.type), e => {
  9885. let extra = e.progress[0].defenders.heroes[1].extra;
  9886. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  9887. });
  9888. });
  9889. }
  9890.  
  9891. function preCalcBattle(battle) {
  9892. let actions = [];
  9893. const countTestBattle = getInput('countTestBattle');
  9894. for (let i = 0; i < countTestBattle; i++) {
  9895. actions.push(getBattleInfo(battle, true));
  9896. }
  9897. Promise.all(actions)
  9898. .then(resultPreCalcBattle);
  9899. }
  9900.  
  9901. async function resultPreCalcBattle(damages) {
  9902. let maxDamage = 0;
  9903. let minDamage = 1e10;
  9904. let avgDamage = 0;
  9905. for (let damage of damages) {
  9906. avgDamage += damage
  9907. if (damage > maxDamage) {
  9908. maxDamage = damage;
  9909. }
  9910. if (damage < minDamage) {
  9911. minDamage = damage;
  9912. }
  9913. }
  9914. avgDamage /= damages.length;
  9915. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  9916.  
  9917. await popup.confirm(
  9918. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  9919. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  9920. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  9921. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  9922. , [
  9923. { msg: I18N('BTN_OK'), result: 0},
  9924. ])
  9925. endBossBattle(I18N('BTN_CANCEL'));
  9926. }
  9927.  
  9928. /**
  9929. * Completing a task
  9930. *
  9931. * Завершение задачи
  9932. */
  9933. function endBossBattle(reason, info) {
  9934. console.log(reason, info);
  9935. resolve();
  9936. }
  9937. }
  9938.  
  9939. this.HWHClasses.executeBossBattle = executeBossBattle;
  9940.  
  9941. class FixBattle {
  9942. minTimer = 1.3;
  9943. maxTimer = 15.3;
  9944.  
  9945. constructor(battle, isTimeout = true) {
  9946. this.battle = structuredClone(battle);
  9947. this.isTimeout = isTimeout;
  9948. }
  9949.  
  9950. timeout(callback, timeout) {
  9951. if (this.isTimeout) {
  9952. this.worker.postMessage(timeout);
  9953. this.worker.onmessage = callback;
  9954. } else {
  9955. callback();
  9956. }
  9957. }
  9958.  
  9959. randTimer() {
  9960. return Math.random() * (this.maxTimer - this.minTimer + 1) + this.minTimer;
  9961. }
  9962.  
  9963. setAvgTime(startTime) {
  9964. this.fixTime += Date.now() - startTime;
  9965. this.avgTime = this.fixTime / this.count;
  9966. }
  9967.  
  9968. init() {
  9969. this.fixTime = 0;
  9970. this.lastTimer = 0;
  9971. this.index = 0;
  9972. this.lastBossDamage = 0;
  9973. this.bestResult = {
  9974. count: 0,
  9975. timer: 0,
  9976. value: 0,
  9977. result: null,
  9978. progress: null,
  9979. };
  9980. this.lastBattleResult = {
  9981. win: false,
  9982. };
  9983. this.worker = new Worker(
  9984. URL.createObjectURL(
  9985. new Blob([
  9986. `self.onmessage = function(e) {
  9987. const timeout = e.data;
  9988. setTimeout(() => {
  9989. self.postMessage(1);
  9990. }, timeout);
  9991. };`,
  9992. ])
  9993. )
  9994. );
  9995. }
  9996.  
  9997. async start(endTime = Date.now() + 6e4, maxCount = 100) {
  9998. this.endTime = endTime;
  9999. this.maxCount = maxCount;
  10000. this.init();
  10001. return await new Promise((resolve) => {
  10002. this.resolve = resolve;
  10003. this.count = 0;
  10004. this.loop();
  10005. });
  10006. }
  10007.  
  10008. endFix() {
  10009. this.bestResult.maxCount = this.count;
  10010. this.worker.terminate();
  10011. this.resolve(this.bestResult);
  10012. }
  10013.  
  10014. async loop() {
  10015. const start = Date.now();
  10016. if (this.isEndLoop()) {
  10017. this.endFix();
  10018. return;
  10019. }
  10020. this.count++;
  10021. try {
  10022. this.lastResult = await Calc(this.battle);
  10023. } catch (e) {
  10024. this.updateProgressTimer(this.index++);
  10025. this.timeout(this.loop.bind(this), 0);
  10026. return;
  10027. }
  10028. const { progress, result } = this.lastResult;
  10029. this.lastBattleResult = result;
  10030. this.lastBattleProgress = progress;
  10031. this.setAvgTime(start);
  10032. this.checkResult();
  10033. this.showResult();
  10034. this.updateProgressTimer();
  10035. this.timeout(this.loop.bind(this), 0);
  10036. }
  10037.  
  10038. isEndLoop() {
  10039. return this.count >= this.maxCount || this.endTime < Date.now();
  10040. }
  10041.  
  10042. updateProgressTimer(index = 0) {
  10043. this.lastTimer = this.randTimer();
  10044. this.battle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', index, this.lastTimer] } }];
  10045. }
  10046.  
  10047. showResult() {
  10048. console.log(
  10049. this.count,
  10050. this.avgTime.toFixed(2),
  10051. (this.endTime - Date.now()) / 1000,
  10052. this.lastTimer.toFixed(2),
  10053. this.lastBossDamage.toLocaleString(),
  10054. this.bestResult.value.toLocaleString()
  10055. );
  10056. }
  10057.  
  10058. checkResult() {
  10059. const { damageTaken, damageTakenNextLevel } = this.lastBattleProgress[0].defenders.heroes[1].extra;
  10060. this.lastBossDamage = damageTaken + damageTakenNextLevel;
  10061. if (this.lastBossDamage > this.bestResult.value) {
  10062. this.bestResult = {
  10063. count: this.count,
  10064. timer: this.lastTimer,
  10065. value: this.lastBossDamage,
  10066. result: structuredClone(this.lastBattleResult),
  10067. progress: structuredClone(this.lastBattleProgress),
  10068. };
  10069. }
  10070. }
  10071.  
  10072. stopFix() {
  10073. this.endTime = 0;
  10074. }
  10075. }
  10076.  
  10077. this.HWHClasses.FixBattle = FixBattle;
  10078.  
  10079. class WinFixBattle extends FixBattle {
  10080. checkResult() {
  10081. if (this.lastBattleResult.win) {
  10082. this.bestResult = {
  10083. count: this.count,
  10084. timer: this.lastTimer,
  10085. value: this.lastBattleResult.stars,
  10086. result: structuredClone(this.lastBattleResult),
  10087. progress: structuredClone(this.lastBattleProgress),
  10088. battleTimer: this.lastResult.battleTimer,
  10089. };
  10090. }
  10091. }
  10092.  
  10093. setWinTimer(value) {
  10094. this.winTimer = value;
  10095. }
  10096.  
  10097. setMaxTimer(value) {
  10098. this.maxTimer = value;
  10099. }
  10100.  
  10101. randTimer() {
  10102. if (this.winTimer) {
  10103. return this.winTimer;
  10104. }
  10105. return super.randTimer();
  10106. }
  10107.  
  10108. isEndLoop() {
  10109. return super.isEndLoop() || this.bestResult.result?.win;
  10110. }
  10111.  
  10112. showResult() {
  10113. console.log(
  10114. this.count,
  10115. this.avgTime.toFixed(2),
  10116. (this.endTime - Date.now()) / 1000,
  10117. this.lastResult.battleTime,
  10118. this.lastTimer,
  10119. this.bestResult.value
  10120. );
  10121. const endTime = ((this.endTime - Date.now()) / 1000).toFixed(2);
  10122. const avgTime = this.avgTime.toFixed(2);
  10123. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${endTime}s<br/>${avgTime}ms`;
  10124. setProgress(msg, false, this.stopFix.bind(this));
  10125. }
  10126. }
  10127.  
  10128. this.HWHClasses.WinFixBattle = WinFixBattle;
  10129.  
  10130. class BestOrWinFixBattle extends WinFixBattle {
  10131. isNoMakeWin = false;
  10132.  
  10133. getState(result) {
  10134. let beforeSumFactor = 0;
  10135. const beforeHeroes = result.battleData.defenders[0];
  10136. for (let heroId in beforeHeroes) {
  10137. const hero = beforeHeroes[heroId];
  10138. const state = hero.state;
  10139. let factor = 1;
  10140. if (state) {
  10141. const hp = state.hp / (hero?.hp || 1);
  10142. const energy = state.energy / 1e3;
  10143. factor = hp + energy / 20;
  10144. }
  10145. beforeSumFactor += factor;
  10146. }
  10147.  
  10148. let afterSumFactor = 0;
  10149. const afterHeroes = result.progress[0].defenders.heroes;
  10150. for (let heroId in afterHeroes) {
  10151. const hero = afterHeroes[heroId];
  10152. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10153. const energy = hero.energy / 1e3;
  10154. const factor = hp + energy / 20;
  10155. afterSumFactor += factor;
  10156. }
  10157. return 100 - Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10158. }
  10159.  
  10160. setNoMakeWin(value) {
  10161. this.isNoMakeWin = value;
  10162. }
  10163.  
  10164. checkResult() {
  10165. const state = this.getState(this.lastResult);
  10166. console.log(state);
  10167.  
  10168. if (state > this.bestResult.value) {
  10169. if (!(this.isNoMakeWin && this.lastBattleResult.win)) {
  10170. this.bestResult = {
  10171. count: this.count,
  10172. timer: this.lastTimer,
  10173. value: state,
  10174. result: structuredClone(this.lastBattleResult),
  10175. progress: structuredClone(this.lastBattleProgress),
  10176. battleTimer: this.lastResult.battleTimer,
  10177. };
  10178. }
  10179. }
  10180. }
  10181. }
  10182.  
  10183. this.HWHClasses.BestOrWinFixBattle = BestOrWinFixBattle;
  10184.  
  10185. class BossFixBattle extends FixBattle {
  10186. showResult() {
  10187. super.showResult();
  10188. //setTimeout(() => {
  10189. const best = this.bestResult;
  10190. const maxDmg = best.value.toLocaleString();
  10191. const avgTime = this.avgTime.toLocaleString();
  10192. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${maxDmg}<br/>${avgTime}ms`;
  10193. setProgress(msg, false, this.stopFix.bind(this));
  10194. //}, 0);
  10195. }
  10196. }
  10197.  
  10198. this.HWHClasses.BossFixBattle = BossFixBattle;
  10199.  
  10200. class DungeonFixBattle extends FixBattle {
  10201. init() {
  10202. super.init();
  10203. this.isTimeout = false;
  10204. }
  10205.  
  10206. setState() {
  10207. const result = this.lastResult;
  10208. let beforeSumFactor = 0;
  10209. const beforeHeroes = result.battleData.attackers;
  10210. for (let heroId in beforeHeroes) {
  10211. const hero = beforeHeroes[heroId];
  10212. const state = hero.state;
  10213. let factor = 1;
  10214. if (state) {
  10215. const hp = state.hp / (hero?.hp || 1);
  10216. const energy = state.energy / 1e3;
  10217. factor = hp + energy / 20;
  10218. }
  10219. beforeSumFactor += factor;
  10220. }
  10221.  
  10222. let afterSumFactor = 0;
  10223. const afterHeroes = result.progress[0].attackers.heroes;
  10224. for (let heroId in afterHeroes) {
  10225. const hero = afterHeroes[heroId];
  10226. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10227. const energy = hero.energy / 1e3;
  10228. const factor = hp + energy / 20;
  10229. afterSumFactor += factor;
  10230. }
  10231. this.lastState = Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10232. }
  10233.  
  10234. checkResult() {
  10235. this.setState();
  10236. if (this.lastResult.result.win && this.lastState > this.bestResult.value) {
  10237. this.bestResult = {
  10238. count: this.count,
  10239. timer: this.lastTimer,
  10240. value: this.lastState,
  10241. result: this.lastResult.result,
  10242. progress: this.lastResult.progress,
  10243. };
  10244. }
  10245. }
  10246.  
  10247. showResult() {
  10248. console.log(
  10249. this.count,
  10250. this.avgTime.toFixed(2),
  10251. (this.endTime - Date.now()) / 1000,
  10252. this.lastTimer.toFixed(2),
  10253. this.lastState.toLocaleString(),
  10254. this.bestResult.value.toLocaleString()
  10255. );
  10256. }
  10257. }
  10258.  
  10259. this.HWHClasses.DungeonFixBattle = DungeonFixBattle;
  10260.  
  10261. const masterWsMixin = {
  10262. wsStart() {
  10263. const socket = new WebSocket(this.url);
  10264.  
  10265. socket.onopen = () => {
  10266. console.log('Connected to server');
  10267.  
  10268. // Пример создания новой задачи
  10269. const newTask = {
  10270. type: 'newTask',
  10271. battle: this.battle,
  10272. endTime: this.endTime - 1e4,
  10273. maxCount: this.maxCount,
  10274. };
  10275. socket.send(JSON.stringify(newTask));
  10276. };
  10277.  
  10278. socket.onmessage = this.onmessage.bind(this);
  10279.  
  10280. socket.onclose = () => {
  10281. console.log('Disconnected from server');
  10282. };
  10283.  
  10284. this.ws = socket;
  10285. },
  10286.  
  10287. onmessage(event) {
  10288. const data = JSON.parse(event.data);
  10289. switch (data.type) {
  10290. case 'newTask': {
  10291. console.log('newTask:', data);
  10292. this.id = data.id;
  10293. this.countExecutor = data.count;
  10294. break;
  10295. }
  10296. case 'getSolTask': {
  10297. console.log('getSolTask:', data);
  10298. this.endFix(data.solutions);
  10299. break;
  10300. }
  10301. case 'resolveTask': {
  10302. console.log('resolveTask:', data);
  10303. if (data.id === this.id && data.solutions.length === this.countExecutor) {
  10304. this.worker.terminate();
  10305. this.endFix(data.solutions);
  10306. }
  10307. break;
  10308. }
  10309. default:
  10310. console.log('Unknown message type:', data.type);
  10311. }
  10312. },
  10313.  
  10314. getTask() {
  10315. this.ws.send(
  10316. JSON.stringify({
  10317. type: 'getSolTask',
  10318. id: this.id,
  10319. })
  10320. );
  10321. },
  10322. };
  10323.  
  10324. /*
  10325. mFix = new action.masterFixBattle(battle)
  10326. await mFix.start(Date.now() + 6e4, 1);
  10327. */
  10328. class masterFixBattle extends FixBattle {
  10329. constructor(battle, url = 'wss://localho.st:3000') {
  10330. super(battle, true);
  10331. this.url = url;
  10332. }
  10333.  
  10334. async start(endTime, maxCount) {
  10335. this.endTime = endTime;
  10336. this.maxCount = maxCount;
  10337. this.init();
  10338. this.wsStart();
  10339. return await new Promise((resolve) => {
  10340. this.resolve = resolve;
  10341. const timeout = this.endTime - Date.now();
  10342. this.timeout(this.getTask.bind(this), timeout);
  10343. });
  10344. }
  10345.  
  10346. async endFix(solutions) {
  10347. this.ws.close();
  10348. let maxCount = 0;
  10349. for (const solution of solutions) {
  10350. maxCount += solution.maxCount;
  10351. if (solution.value > this.bestResult.value) {
  10352. this.bestResult = solution;
  10353. }
  10354. }
  10355. this.count = maxCount;
  10356. super.endFix();
  10357. }
  10358. }
  10359.  
  10360. Object.assign(masterFixBattle.prototype, masterWsMixin);
  10361.  
  10362. this.HWHClasses.masterFixBattle = masterFixBattle;
  10363.  
  10364. class masterWinFixBattle extends WinFixBattle {
  10365. constructor(battle, url = 'wss://localho.st:3000') {
  10366. super(battle, true);
  10367. this.url = url;
  10368. }
  10369.  
  10370. async start(endTime, maxCount) {
  10371. this.endTime = endTime;
  10372. this.maxCount = maxCount;
  10373. this.init();
  10374. this.wsStart();
  10375. return await new Promise((resolve) => {
  10376. this.resolve = resolve;
  10377. const timeout = this.endTime - Date.now();
  10378. this.timeout(this.getTask.bind(this), timeout);
  10379. });
  10380. }
  10381.  
  10382. async endFix(solutions) {
  10383. this.ws.close();
  10384. let maxCount = 0;
  10385. for (const solution of solutions) {
  10386. maxCount += solution.maxCount;
  10387. if (solution.value > this.bestResult.value) {
  10388. this.bestResult = solution;
  10389. }
  10390. }
  10391. this.count = maxCount;
  10392. super.endFix();
  10393. }
  10394. }
  10395.  
  10396. Object.assign(masterWinFixBattle.prototype, masterWsMixin);
  10397.  
  10398. this.HWHClasses.masterWinFixBattle = masterWinFixBattle;
  10399.  
  10400. const slaveWsMixin = {
  10401. wsStop() {
  10402. this.ws.close();
  10403. },
  10404.  
  10405. wsStart() {
  10406. const socket = new WebSocket(this.url);
  10407.  
  10408. socket.onopen = () => {
  10409. console.log('Connected to server');
  10410. };
  10411. socket.onmessage = this.onmessage.bind(this);
  10412. socket.onclose = () => {
  10413. console.log('Disconnected from server');
  10414. };
  10415.  
  10416. this.ws = socket;
  10417. },
  10418.  
  10419. async onmessage(event) {
  10420. const data = JSON.parse(event.data);
  10421. switch (data.type) {
  10422. case 'newTask': {
  10423. console.log('newTask:', data.task);
  10424. const { battle, endTime, maxCount } = data.task;
  10425. this.battle = battle;
  10426. const id = data.task.id;
  10427. const solution = await this.start(endTime, maxCount);
  10428. this.ws.send(
  10429. JSON.stringify({
  10430. type: 'resolveTask',
  10431. id,
  10432. solution,
  10433. })
  10434. );
  10435. break;
  10436. }
  10437. default:
  10438. console.log('Unknown message type:', data.type);
  10439. }
  10440. },
  10441. };
  10442. /*
  10443. sFix = new action.slaveFixBattle();
  10444. sFix.wsStart()
  10445. */
  10446. class slaveFixBattle extends FixBattle {
  10447. constructor(url = 'wss://localho.st:3000') {
  10448. super(null, false);
  10449. this.isTimeout = false;
  10450. this.url = url;
  10451. }
  10452. }
  10453.  
  10454. Object.assign(slaveFixBattle.prototype, slaveWsMixin);
  10455.  
  10456. this.HWHClasses.slaveFixBattle = slaveFixBattle;
  10457.  
  10458. class slaveWinFixBattle extends WinFixBattle {
  10459. constructor(url = 'wss://localho.st:3000') {
  10460. super(null, false);
  10461. this.isTimeout = false;
  10462. this.url = url;
  10463. }
  10464. }
  10465.  
  10466. Object.assign(slaveWinFixBattle.prototype, slaveWsMixin);
  10467.  
  10468. this.HWHClasses.slaveWinFixBattle = slaveWinFixBattle;
  10469. /**
  10470. * Auto-repeat attack
  10471. *
  10472. * Автоповтор атаки
  10473. */
  10474. function testAutoBattle() {
  10475. const { executeAutoBattle } = HWHClasses;
  10476. return new Promise((resolve, reject) => {
  10477. const bossBattle = new executeAutoBattle(resolve, reject);
  10478. bossBattle.start(lastBattleArg, lastBattleInfo);
  10479. });
  10480. }
  10481.  
  10482. /**
  10483. * Auto-repeat attack
  10484. *
  10485. * Автоповтор атаки
  10486. */
  10487. function executeAutoBattle(resolve, reject) {
  10488. let battleArg = {};
  10489. let countBattle = 0;
  10490. let countError = 0;
  10491. let findCoeff = 0;
  10492. let dataNotEeceived = 0;
  10493. let stopAutoBattle = false;
  10494.  
  10495. let isSetWinTimer = false;
  10496. 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>';
  10497. 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>';
  10498. 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>';
  10499.  
  10500. this.start = function (battleArgs, battleInfo) {
  10501. battleArg = battleArgs;
  10502. if (nameFuncStartBattle == 'invasion_bossStart') {
  10503. startBattle();
  10504. return;
  10505. }
  10506. preCalcBattle(battleInfo);
  10507. }
  10508. /**
  10509. * Returns a promise for combat recalculation
  10510. *
  10511. * Возвращает промис для прерасчета боя
  10512. */
  10513. function getBattleInfo(battle) {
  10514. return new Promise(function (resolve) {
  10515. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10516. Calc(battle).then(e => {
  10517. e.coeff = calcCoeff(e, 'defenders');
  10518. resolve(e);
  10519. });
  10520. });
  10521. }
  10522. /**
  10523. * Battle recalculation
  10524. *
  10525. * Прерасчет боя
  10526. */
  10527. function preCalcBattle(battle) {
  10528. let actions = [];
  10529. const countTestBattle = getInput('countTestBattle');
  10530. for (let i = 0; i < countTestBattle; i++) {
  10531. actions.push(getBattleInfo(battle));
  10532. }
  10533. Promise.all(actions)
  10534. .then(resultPreCalcBattle);
  10535. }
  10536. /**
  10537. * Processing the results of the battle recalculation
  10538. *
  10539. * Обработка результатов прерасчета боя
  10540. */
  10541. async function resultPreCalcBattle(results) {
  10542. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  10543. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  10544. if (countWin > 0) {
  10545. setIsCancalBattle(false);
  10546. startBattle();
  10547. return;
  10548. }
  10549.  
  10550. let minCoeff = 100;
  10551. let maxCoeff = -100;
  10552. let avgCoeff = 0;
  10553. results.forEach(e => {
  10554. if (e.coeff < minCoeff) minCoeff = e.coeff;
  10555. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  10556. avgCoeff += e.coeff;
  10557. });
  10558. avgCoeff /= results.length;
  10559.  
  10560. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10561. nameFuncStartBattle == 'bossAttack') {
  10562. const result = await popup.confirm(
  10563. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  10564. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  10565. { msg: I18N('BTN_DO_IT'), result: true },
  10566. ])
  10567. if (result) {
  10568. setIsCancalBattle(false);
  10569. startBattle();
  10570. return;
  10571. }
  10572. setProgress(I18N('NOT_THIS_TIME'), true);
  10573. endAutoBattle('invasion_bossStart');
  10574. return;
  10575. }
  10576.  
  10577. const result = await popup.confirm(
  10578. I18N('VICTORY_IMPOSSIBLE') +
  10579. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  10580. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  10581. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  10582. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  10583. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  10584. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  10585. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  10586. ])
  10587. if (result) {
  10588. findCoeff = result;
  10589. setIsCancalBattle(false);
  10590. startBattle();
  10591. return;
  10592. }
  10593. setProgress(I18N('NOT_THIS_TIME'), true);
  10594. endAutoBattle(I18N('NOT_THIS_TIME'));
  10595. }
  10596.  
  10597. /**
  10598. * Calculation of the combat result coefficient
  10599. *
  10600. * Расчет коэфициента результата боя
  10601. */
  10602. function calcCoeff(result, packType) {
  10603. let beforeSumFactor = 0;
  10604. const beforePack = result.battleData[packType][0];
  10605. for (let heroId in beforePack) {
  10606. const hero = beforePack[heroId];
  10607. const state = hero.state;
  10608. let factor = 1;
  10609. if (state) {
  10610. const hp = state.hp / state.maxHp;
  10611. const energy = state.energy / 1e3;
  10612. factor = hp + energy / 20;
  10613. }
  10614. beforeSumFactor += factor;
  10615. }
  10616.  
  10617. let afterSumFactor = 0;
  10618. const afterPack = result.progress[0][packType].heroes;
  10619. for (let heroId in afterPack) {
  10620. const hero = afterPack[heroId];
  10621. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  10622. const hp = hero.hp / stateHp;
  10623. const energy = hero.energy / 1e3;
  10624. const factor = hp + energy / 20;
  10625. afterSumFactor += factor;
  10626. }
  10627. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  10628. return Math.round(resultCoeff * 1000) / 1000;
  10629. }
  10630. /**
  10631. * Start battle
  10632. *
  10633. * Начало боя
  10634. */
  10635. function startBattle() {
  10636. countBattle++;
  10637. const countMaxBattle = getInput('countAutoBattle');
  10638. // setProgress(countBattle + '/' + countMaxBattle);
  10639. if (countBattle > countMaxBattle) {
  10640. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  10641. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  10642. return;
  10643. }
  10644. if (stopAutoBattle) {
  10645. setProgress(I18N('STOPPED'), true);
  10646. endAutoBattle('STOPPED');
  10647. return;
  10648. }
  10649. send({calls: [{
  10650. name: nameFuncStartBattle,
  10651. args: battleArg,
  10652. ident: "body"
  10653. }]}, calcResultBattle);
  10654. }
  10655. /**
  10656. * Battle calculation
  10657. *
  10658. * Расчет боя
  10659. */
  10660. async function calcResultBattle(e) {
  10661. if (!e) {
  10662. console.log('данные не были получены');
  10663. if (dataNotEeceived < 10) {
  10664. dataNotEeceived++;
  10665. startBattle();
  10666. return;
  10667. }
  10668. endAutoBattle('Error', 'данные не были получены ' + dataNotEeceived + ' раз');
  10669. return;
  10670. }
  10671. if ('error' in e) {
  10672. if (e.error.description === 'too many tries') {
  10673. invasionTimer += 100;
  10674. countBattle--;
  10675. countError++;
  10676. console.log(`Errors: ${countError}`, e.error);
  10677. startBattle();
  10678. return;
  10679. }
  10680. const result = await popup.confirm(I18N('ERROR_DURING_THE_BATTLE') + '<br>' + e.error.description, [
  10681. { msg: I18N('BTN_OK'), result: false },
  10682. { msg: I18N('RELOAD_GAME'), result: true },
  10683. ]);
  10684. endAutoBattle('Error', e.error);
  10685. if (result) {
  10686. location.reload();
  10687. }
  10688. return;
  10689. }
  10690. let battle = e.results[0].result.response.battle
  10691. if (nameFuncStartBattle == 'towerStartBattle' ||
  10692. nameFuncStartBattle == 'bossAttack' ||
  10693. nameFuncStartBattle == 'invasion_bossStart') {
  10694. battle = e.results[0].result.response;
  10695. }
  10696. lastBattleInfo = battle;
  10697. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  10698. }
  10699. /**
  10700. * Processing the results of the battle
  10701. *
  10702. * Обработка результатов боя
  10703. */
  10704. async function resultBattle(e) {
  10705. const isWin = e.result.win;
  10706. if (isWin) {
  10707. endBattle(e, false);
  10708. return;
  10709. } else if (isChecked('tryFixIt_v2')) {
  10710. const { WinFixBattle } = HWHClasses;
  10711. const cloneBattle = structuredClone(e.battleData);
  10712. const bFix = new WinFixBattle(cloneBattle);
  10713. let attempts = Infinity;
  10714. if (nameFuncStartBattle == 'invasion_bossStart' && !isSetWinTimer) {
  10715. let winTimer = await popup.confirm(`Secret number:`, [
  10716. { result: false, isClose: true },
  10717. { msg: 'Go', isInput: true, default: '0' },
  10718. ]);
  10719. winTimer = Number.parseFloat(winTimer);
  10720. if (winTimer) {
  10721. attempts = 5;
  10722. bFix.setWinTimer(winTimer);
  10723. }
  10724. isSetWinTimer = true;
  10725. }
  10726. let endTime = Date.now() + 6e4;
  10727. if (nameFuncStartBattle == 'invasion_bossStart') {
  10728. endTime = Date.now() + 6e4 * 4;
  10729. bFix.setMaxTimer(120.3);
  10730. }
  10731. const result = await bFix.start(endTime, attempts);
  10732. console.log(result);
  10733. if (result.value) {
  10734. endBattle(result, false);
  10735. return;
  10736. }
  10737. }
  10738. const countMaxBattle = getInput('countAutoBattle');
  10739. if (findCoeff) {
  10740. const coeff = calcCoeff(e, 'defenders');
  10741. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  10742. if (coeff > findCoeff) {
  10743. endBattle(e, false);
  10744. return;
  10745. }
  10746. } else {
  10747. if (nameFuncStartBattle == 'invasion_bossStart') {
  10748. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10749. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10750. setProgress(`${svgBoss} ${bossLvl} ${svgJustice} ${justice} <br>${svgAttempt} ${countBattle}/${countMaxBattle}`, false, () => {
  10751. stopAutoBattle = true;
  10752. });
  10753. await new Promise((resolve) => setTimeout(resolve, 5000));
  10754. } else {
  10755. setProgress(`${countBattle}/${countMaxBattle}`);
  10756. }
  10757. }
  10758. if (nameFuncStartBattle == 'towerStartBattle' ||
  10759. nameFuncStartBattle == 'bossAttack' ||
  10760. nameFuncStartBattle == 'invasion_bossStart') {
  10761. startBattle();
  10762. return;
  10763. }
  10764. cancelEndBattle(e);
  10765. }
  10766. /**
  10767. * Cancel fight
  10768. *
  10769. * Отмена боя
  10770. */
  10771. function cancelEndBattle(r) {
  10772. const fixBattle = function (heroes) {
  10773. for (const ids in heroes) {
  10774. hero = heroes[ids];
  10775. hero.energy = random(1, 999);
  10776. if (hero.hp > 0) {
  10777. hero.hp = random(1, hero.hp);
  10778. }
  10779. }
  10780. }
  10781. fixBattle(r.progress[0].attackers.heroes);
  10782. fixBattle(r.progress[0].defenders.heroes);
  10783. endBattle(r, true);
  10784. }
  10785. /**
  10786. * End of the fight
  10787. *
  10788. * Завершение боя */
  10789. function endBattle(battleResult, isCancal) {
  10790. let calls = [{
  10791. name: nameFuncEndBattle,
  10792. args: {
  10793. result: battleResult.result,
  10794. progress: battleResult.progress
  10795. },
  10796. ident: "body"
  10797. }];
  10798.  
  10799. if (nameFuncStartBattle == 'invasion_bossStart') {
  10800. calls[0].args.id = lastBattleArg.id;
  10801. }
  10802.  
  10803. send(JSON.stringify({
  10804. calls
  10805. }), async e => {
  10806. console.log(e);
  10807. if (isCancal) {
  10808. startBattle();
  10809. return;
  10810. }
  10811.  
  10812. setProgress(`${I18N('SUCCESS')}!`, 5000)
  10813. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10814. nameFuncStartBattle == 'bossAttack') {
  10815. const countMaxBattle = getInput('countAutoBattle');
  10816. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10817. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10818. let winTimer = '';
  10819. if (nameFuncStartBattle == 'invasion_bossStart') {
  10820. winTimer = '<br>Secret number: ' + battleResult.progress[0].attackers.input[5];
  10821. }
  10822. const result = await popup.confirm(
  10823. I18N('BOSS_HAS_BEEN_DEF_TEXT', {
  10824. bossLvl: `${svgBoss} ${bossLvl} ${svgJustice} ${justice}`,
  10825. countBattle: svgAttempt + ' ' + countBattle,
  10826. countMaxBattle,
  10827. winTimer,
  10828. }),
  10829. [
  10830. { msg: I18N('BTN_OK'), result: 0 },
  10831. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  10832. { msg: I18N('RELOAD_GAME'), result: 2 },
  10833. ]
  10834. );
  10835. if (result) {
  10836. if (result == 1) {
  10837. cheats.refreshGame();
  10838. }
  10839. if (result == 2) {
  10840. location.reload();
  10841. }
  10842. }
  10843.  
  10844. }
  10845. endAutoBattle(`${I18N('SUCCESS')}!`)
  10846. });
  10847. }
  10848. /**
  10849. * Completing a task
  10850. *
  10851. * Завершение задачи
  10852. */
  10853. function endAutoBattle(reason, info) {
  10854. setIsCancalBattle(true);
  10855. console.log(reason, info);
  10856. resolve();
  10857. }
  10858. }
  10859.  
  10860. this.HWHClasses.executeAutoBattle = executeAutoBattle;
  10861.  
  10862. function testDailyQuests() {
  10863. const { dailyQuests } = HWHClasses;
  10864. return new Promise((resolve, reject) => {
  10865. const quests = new dailyQuests(resolve, reject);
  10866. quests.init(questsInfo);
  10867. quests.start();
  10868. });
  10869. }
  10870.  
  10871. /**
  10872. * Automatic completion of daily quests
  10873. *
  10874. * Автоматическое выполнение ежедневных квестов
  10875. */
  10876. class dailyQuests {
  10877. /**
  10878. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  10879. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10880. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10881. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  10882. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10883. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10884. */
  10885. callsList = ['userGetInfo', 'heroGetAll', 'titanGetAll', 'inventoryGet', 'questGetAll', 'bossGetAll', 'missionGetAll'];
  10886.  
  10887. dataQuests = {
  10888. 10001: {
  10889. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  10890. doItCall: () => {
  10891. const upgradeSkills = this.getUpgradeSkills();
  10892. return upgradeSkills.map(({ heroId, skill }, index) => ({
  10893. name: 'heroUpgradeSkill',
  10894. args: { heroId, skill },
  10895. ident: `heroUpgradeSkill_${index}`,
  10896. }));
  10897. },
  10898. isWeCanDo: () => {
  10899. const upgradeSkills = this.getUpgradeSkills();
  10900. let sumGold = 0;
  10901. for (const skill of upgradeSkills) {
  10902. sumGold += this.skillCost(skill.value);
  10903. if (!skill.heroId) {
  10904. return false;
  10905. }
  10906. }
  10907. return this.questInfo['userGetInfo'].gold > sumGold;
  10908. },
  10909. },
  10910. 10002: {
  10911. description: 'Пройди 10 миссий', // --------------
  10912. isWeCanDo: () => false,
  10913. },
  10914. 10003: {
  10915. description: 'Пройди 3 героические миссии', // ++++++++++++++++
  10916. isWeCanDo: () => {
  10917. const vipPoints = +this.questInfo.userGetInfo.vipPoints;
  10918. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10919. return (vipPoints > 100 || goldTicket) && this.getHeroicMissionId();
  10920. },
  10921. doItCall: () => {
  10922. const selectedMissionId = this.getHeroicMissionId();
  10923. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10924. const vipLevel = Math.max(...lib.data.level.vip.filter(l => l.vipPoints <= +this.questInfo.userGetInfo.vipPoints).map(l => l.level));
  10925. // Возвращаем массив команд для рейда
  10926. if (vipLevel >= 5 || goldTicket) {
  10927. return [{ name: 'missionRaid', args: { id: selectedMissionId, times: 3 }, ident: 'missionRaid_1' }];
  10928. } else {
  10929. return [
  10930. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_1' },
  10931. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_2' },
  10932. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_3' },
  10933. ];
  10934. }
  10935. },
  10936. },
  10937. 10004: {
  10938. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  10939. isWeCanDo: () => false,
  10940. },
  10941. 10006: {
  10942. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  10943. doItCall: () => [
  10944. {
  10945. name: 'refillableAlchemyUse',
  10946. args: { multi: false },
  10947. ident: 'refillableAlchemyUse',
  10948. },
  10949. ],
  10950. isWeCanDo: () => {
  10951. const starMoney = this.questInfo['userGetInfo'].starMoney;
  10952. return starMoney >= 20;
  10953. },
  10954. },
  10955. 10007: {
  10956. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  10957. doItCall: () => [{ name: 'gacha_open', args: { ident: 'heroGacha', free: true, pack: false }, ident: 'gacha_open' }],
  10958. isWeCanDo: () => {
  10959. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  10960. return soulCrystal > 0;
  10961. },
  10962. },
  10963. 10016: {
  10964. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  10965. doItCall: () => [{ name: 'clanSendDailyGifts', args: {}, ident: 'clanSendDailyGifts' }],
  10966. isWeCanDo: () => true,
  10967. },
  10968. 10018: {
  10969. description: 'Используй зелье опыта', // ++++++++++++++++
  10970. doItCall: () => {
  10971. const expHero = this.getExpHero();
  10972. return [
  10973. {
  10974. name: 'consumableUseHeroXp',
  10975. args: {
  10976. heroId: expHero.heroId,
  10977. libId: expHero.libId,
  10978. amount: 1,
  10979. },
  10980. ident: 'consumableUseHeroXp',
  10981. },
  10982. ];
  10983. },
  10984. isWeCanDo: () => {
  10985. const expHero = this.getExpHero();
  10986. return expHero.heroId && expHero.libId;
  10987. },
  10988. },
  10989. 10019: {
  10990. description: 'Открой 1 сундук в Башне',
  10991. doItFunc: testTower,
  10992. isWeCanDo: () => false,
  10993. },
  10994. 10020: {
  10995. description: 'Открой 3 сундука в Запределье', // Готово
  10996. doItCall: () => {
  10997. return this.getOutlandChest();
  10998. },
  10999. isWeCanDo: () => {
  11000. const outlandChest = this.getOutlandChest();
  11001. return outlandChest.length > 0;
  11002. },
  11003. },
  11004. 10021: {
  11005. description: 'Собери 75 Титанита в Подземелье Гильдии',
  11006. isWeCanDo: () => false,
  11007. },
  11008. 10022: {
  11009. description: 'Собери 150 Титанита в Подземелье Гильдии',
  11010. doItFunc: testDungeon,
  11011. isWeCanDo: () => false,
  11012. },
  11013. 10023: {
  11014. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  11015. doItCall: () => {
  11016. const heroId = this.getHeroIdTitanGift();
  11017. return [
  11018. { name: 'heroTitanGiftLevelUp', args: { heroId }, ident: 'heroTitanGiftLevelUp' },
  11019. { name: 'heroTitanGiftDrop', args: { heroId }, ident: 'heroTitanGiftDrop' },
  11020. ];
  11021. },
  11022. isWeCanDo: () => {
  11023. const heroId = this.getHeroIdTitanGift();
  11024. return heroId;
  11025. },
  11026. },
  11027. 10024: {
  11028. description: 'Повысь уровень любого артефакта один раз', // Готово
  11029. doItCall: () => {
  11030. const upArtifact = this.getUpgradeArtifact();
  11031. return [
  11032. {
  11033. name: 'heroArtifactLevelUp',
  11034. args: {
  11035. heroId: upArtifact.heroId,
  11036. slotId: upArtifact.slotId,
  11037. },
  11038. ident: `heroArtifactLevelUp`,
  11039. },
  11040. ];
  11041. },
  11042. isWeCanDo: () => {
  11043. const upgradeArtifact = this.getUpgradeArtifact();
  11044. return upgradeArtifact.heroId;
  11045. },
  11046. },
  11047. 10025: {
  11048. description: 'Начни 1 Экспедицию',
  11049. doItFunc: checkExpedition,
  11050. isWeCanDo: () => false,
  11051. },
  11052. 10026: {
  11053. description: 'Начни 4 Экспедиции', // --------------
  11054. doItFunc: checkExpedition,
  11055. isWeCanDo: () => false,
  11056. },
  11057. 10027: {
  11058. description: 'Победи в 1 бою Турнира Стихий',
  11059. doItFunc: testTitanArena,
  11060. isWeCanDo: () => false,
  11061. },
  11062. 10028: {
  11063. description: 'Повысь уровень любого артефакта титанов', // Готово
  11064. doItCall: () => {
  11065. const upTitanArtifact = this.getUpgradeTitanArtifact();
  11066. return [
  11067. {
  11068. name: 'titanArtifactLevelUp',
  11069. args: {
  11070. titanId: upTitanArtifact.titanId,
  11071. slotId: upTitanArtifact.slotId,
  11072. },
  11073. ident: `titanArtifactLevelUp`,
  11074. },
  11075. ];
  11076. },
  11077. isWeCanDo: () => {
  11078. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  11079. return upgradeTitanArtifact.titanId;
  11080. },
  11081. },
  11082. 10029: {
  11083. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  11084. doItCall: () => [{ name: 'titanArtifactChestOpen', args: { amount: 1, free: true }, ident: 'titanArtifactChestOpen' }],
  11085. isWeCanDo: () => {
  11086. return this.questInfo['inventoryGet']?.consumable[55] > 0;
  11087. },
  11088. },
  11089. 10030: {
  11090. description: 'Улучши облик любого героя 1 раз', // Готово
  11091. doItCall: () => {
  11092. const upSkin = this.getUpgradeSkin();
  11093. return [
  11094. {
  11095. name: 'heroSkinUpgrade',
  11096. args: {
  11097. heroId: upSkin.heroId,
  11098. skinId: upSkin.skinId,
  11099. },
  11100. ident: `heroSkinUpgrade`,
  11101. },
  11102. ];
  11103. },
  11104. isWeCanDo: () => {
  11105. const upgradeSkin = this.getUpgradeSkin();
  11106. return upgradeSkin.heroId;
  11107. },
  11108. },
  11109. 10031: {
  11110. description: 'Победи в 6 боях Турнира Стихий', // --------------
  11111. doItFunc: testTitanArena,
  11112. isWeCanDo: () => false,
  11113. },
  11114. 10043: {
  11115. description: 'Начни или присоеденись к Приключению', // --------------
  11116. isWeCanDo: () => false,
  11117. },
  11118. 10044: {
  11119. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  11120. doItCall: () => [{ name: 'pet_chestOpen', args: { amount: 1, paid: false }, ident: 'pet_chestOpen' }],
  11121. isWeCanDo: () => {
  11122. return this.questInfo['inventoryGet']?.consumable[90] > 0;
  11123. },
  11124. },
  11125. 10046: {
  11126. /**
  11127. * TODO: Watch Adventure
  11128. * TODO: Смотреть приключение
  11129. */
  11130. description: 'Открой 3 сундука в Приключениях',
  11131. isWeCanDo: () => false,
  11132. },
  11133. 10047: {
  11134. description: 'Набери 150 очков активности в Гильдии', // Готово
  11135. doItCall: () => {
  11136. const enchantRune = this.getEnchantRune();
  11137. return [
  11138. {
  11139. name: 'heroEnchantRune',
  11140. args: {
  11141. heroId: enchantRune.heroId,
  11142. tier: enchantRune.tier,
  11143. items: {
  11144. consumable: { [enchantRune.itemId]: 1 },
  11145. },
  11146. },
  11147. ident: `heroEnchantRune`,
  11148. },
  11149. ];
  11150. },
  11151. isWeCanDo: () => {
  11152. const userInfo = this.questInfo['userGetInfo'];
  11153. const enchantRune = this.getEnchantRune();
  11154. return enchantRune.heroId && userInfo.gold > 1e3;
  11155. },
  11156. },
  11157. };
  11158.  
  11159. constructor(resolve, reject, questInfo) {
  11160. this.resolve = resolve;
  11161. this.reject = reject;
  11162. }
  11163.  
  11164. init(questInfo) {
  11165. this.questInfo = questInfo;
  11166. this.isAuto = false;
  11167. }
  11168.  
  11169. async autoInit(isAuto) {
  11170. this.isAuto = isAuto || false;
  11171. const quests = {};
  11172. const calls = this.callsList.map((name) => ({
  11173. name,
  11174. args: {},
  11175. ident: name,
  11176. }));
  11177. const result = await Send(JSON.stringify({ calls })).then((e) => e.results);
  11178. for (const call of result) {
  11179. quests[call.ident] = call.result.response;
  11180. }
  11181. this.questInfo = quests;
  11182. }
  11183.  
  11184. async start() {
  11185. const weCanDo = [];
  11186. const selectedActions = getSaveVal('selectedActions', {});
  11187. for (let quest of this.questInfo['questGetAll']) {
  11188. if (quest.id in this.dataQuests && quest.state == 1) {
  11189. if (!selectedActions[quest.id]) {
  11190. selectedActions[quest.id] = {
  11191. checked: false,
  11192. };
  11193. }
  11194.  
  11195. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  11196. if (!isWeCanDo.call(this)) {
  11197. continue;
  11198. }
  11199.  
  11200. weCanDo.push({
  11201. name: quest.id,
  11202. label: I18N(`QUEST_${quest.id}`),
  11203. checked: selectedActions[quest.id].checked,
  11204. });
  11205. }
  11206. }
  11207.  
  11208. if (!weCanDo.length) {
  11209. this.end(I18N('NOTHING_TO_DO'));
  11210. return;
  11211. }
  11212.  
  11213. console.log(weCanDo);
  11214. let taskList = [];
  11215. if (this.isAuto) {
  11216. taskList = weCanDo;
  11217. } else {
  11218. const answer = await popup.confirm(
  11219. `${I18N('YOU_CAN_COMPLETE')}:`,
  11220. [
  11221. { msg: I18N('BTN_DO_IT'), result: true },
  11222. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11223. ],
  11224. weCanDo
  11225. );
  11226. if (!answer) {
  11227. this.end('');
  11228. return;
  11229. }
  11230. taskList = popup.getCheckBoxes();
  11231. taskList.forEach((e) => {
  11232. selectedActions[e.name].checked = e.checked;
  11233. });
  11234. setSaveVal('selectedActions', selectedActions);
  11235. }
  11236.  
  11237. const calls = [];
  11238. let countChecked = 0;
  11239. for (const task of taskList) {
  11240. if (task.checked) {
  11241. countChecked++;
  11242. const quest = this.dataQuests[task.name];
  11243. console.log(quest.description);
  11244.  
  11245. if (quest.doItCall) {
  11246. const doItCall = quest.doItCall.call(this);
  11247. calls.push(...doItCall);
  11248. }
  11249. }
  11250. }
  11251.  
  11252. if (!countChecked) {
  11253. this.end(I18N('NOT_QUEST_COMPLETED'));
  11254. return;
  11255. }
  11256.  
  11257. const result = await Send(JSON.stringify({ calls }));
  11258. if (result.error) {
  11259. console.error(result.error, result.error.call);
  11260. }
  11261. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  11262. }
  11263.  
  11264. errorHandling(error) {
  11265. //console.error(error);
  11266. let errorInfo = error.toString() + '\n';
  11267. try {
  11268. const errorStack = error.stack.split('\n');
  11269. const endStack = errorStack.map((e) => e.split('@')[0]).indexOf('testDoYourBest');
  11270. errorInfo += errorStack.slice(0, endStack).join('\n');
  11271. } catch (e) {
  11272. errorInfo += error.stack;
  11273. }
  11274. copyText(errorInfo);
  11275. }
  11276.  
  11277. skillCost(lvl) {
  11278. return 573 * lvl ** 0.9 + lvl ** 2.379;
  11279. }
  11280.  
  11281. getUpgradeSkills() {
  11282. const heroes = Object.values(this.questInfo['heroGetAll']);
  11283. const upgradeSkills = [
  11284. { heroId: 0, slotId: 0, value: 130 },
  11285. { heroId: 0, slotId: 0, value: 130 },
  11286. { heroId: 0, slotId: 0, value: 130 },
  11287. ];
  11288. const skillLib = lib.getData('skill');
  11289. /**
  11290. * color - 1 (белый) открывает 1 навык
  11291. * color - 2 (зеленый) открывает 2 навык
  11292. * color - 4 (синий) открывает 3 навык
  11293. * color - 7 (фиолетовый) открывает 4 навык
  11294. */
  11295. const colors = [1, 2, 4, 7];
  11296. for (const hero of heroes) {
  11297. const level = hero.level;
  11298. const color = hero.color;
  11299. for (let skillId in hero.skills) {
  11300. const tier = skillLib[skillId].tier;
  11301. const sVal = hero.skills[skillId];
  11302. if (color < colors[tier] || tier < 1 || tier > 4) {
  11303. continue;
  11304. }
  11305. for (let upSkill of upgradeSkills) {
  11306. if (sVal < upSkill.value && sVal < level) {
  11307. upSkill.value = sVal;
  11308. upSkill.heroId = hero.id;
  11309. upSkill.skill = tier;
  11310. break;
  11311. }
  11312. }
  11313. }
  11314. }
  11315. return upgradeSkills;
  11316. }
  11317.  
  11318. getUpgradeArtifact() {
  11319. const heroes = Object.values(this.questInfo['heroGetAll']);
  11320. const inventory = this.questInfo['inventoryGet'];
  11321. const upArt = { heroId: 0, slotId: 0, level: 100 };
  11322.  
  11323. const heroLib = lib.getData('hero');
  11324. const artifactLib = lib.getData('artifact');
  11325.  
  11326. for (const hero of heroes) {
  11327. const heroInfo = heroLib[hero.id];
  11328. const level = hero.level;
  11329. if (level < 20) {
  11330. continue;
  11331. }
  11332.  
  11333. for (let slotId in hero.artifacts) {
  11334. const art = hero.artifacts[slotId];
  11335. /* Текущая звезданость арта */
  11336. const star = art.star;
  11337. if (!star) {
  11338. continue;
  11339. }
  11340. /* Текущий уровень арта */
  11341. const level = art.level;
  11342. if (level >= 100) {
  11343. continue;
  11344. }
  11345. /* Идентификатор арта в библиотеке */
  11346. const artifactId = heroInfo.artifacts[slotId];
  11347. const artInfo = artifactLib.id[artifactId];
  11348. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  11349.  
  11350. const costCurrency = Object.keys(costNextLevel).pop();
  11351. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11352. const costId = costValues[0];
  11353. const costValue = +costValues[1];
  11354.  
  11355. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11356. if (level < upArt.level && inventory[costCurrency][costId] >= costValue) {
  11357. upArt.level = level;
  11358. upArt.heroId = hero.id;
  11359. upArt.slotId = slotId;
  11360. upArt.costCurrency = costCurrency;
  11361. upArt.costId = costId;
  11362. upArt.costValue = costValue;
  11363. }
  11364. }
  11365. }
  11366. return upArt;
  11367. }
  11368.  
  11369. getUpgradeSkin() {
  11370. const heroes = Object.values(this.questInfo['heroGetAll']);
  11371. const inventory = this.questInfo['inventoryGet'];
  11372. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  11373.  
  11374. const skinLib = lib.getData('skin');
  11375.  
  11376. for (const hero of heroes) {
  11377. const level = hero.level;
  11378. if (level < 20) {
  11379. continue;
  11380. }
  11381.  
  11382. for (let skinId in hero.skins) {
  11383. /* Текущий уровень скина */
  11384. const level = hero.skins[skinId];
  11385. if (level >= 60) {
  11386. continue;
  11387. }
  11388. /* Идентификатор скина в библиотеке */
  11389. const skinInfo = skinLib[skinId];
  11390. if (!skinInfo.statData.levels?.[level + 1]) {
  11391. continue;
  11392. }
  11393. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  11394.  
  11395. const costCurrency = Object.keys(costNextLevel).pop();
  11396. const costCurrencyId = Object.keys(costNextLevel[costCurrency]).pop();
  11397. const costValue = +costNextLevel[costCurrency][costCurrencyId];
  11398.  
  11399. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11400. if (level < upSkin.level && costValue < upSkin.cost && inventory[costCurrency][costCurrencyId] >= costValue) {
  11401. upSkin.cost = costValue;
  11402. upSkin.level = level;
  11403. upSkin.heroId = hero.id;
  11404. upSkin.skinId = skinId;
  11405. upSkin.costCurrency = costCurrency;
  11406. upSkin.costCurrencyId = costCurrencyId;
  11407. }
  11408. }
  11409. }
  11410. return upSkin;
  11411. }
  11412.  
  11413. getUpgradeTitanArtifact() {
  11414. const titans = Object.values(this.questInfo['titanGetAll']);
  11415. const inventory = this.questInfo['inventoryGet'];
  11416. const userInfo = this.questInfo['userGetInfo'];
  11417. const upArt = { titanId: 0, slotId: 0, level: 120 };
  11418.  
  11419. const titanLib = lib.getData('titan');
  11420. const artTitanLib = lib.getData('titanArtifact');
  11421.  
  11422. for (const titan of titans) {
  11423. const titanInfo = titanLib[titan.id];
  11424. // const level = titan.level
  11425. // if (level < 20) {
  11426. // continue;
  11427. // }
  11428.  
  11429. for (let slotId in titan.artifacts) {
  11430. const art = titan.artifacts[slotId];
  11431. /* Текущая звезданость арта */
  11432. const star = art.star;
  11433. if (!star) {
  11434. continue;
  11435. }
  11436. /* Текущий уровень арта */
  11437. const level = art.level;
  11438. if (level >= 120) {
  11439. continue;
  11440. }
  11441. /* Идентификатор арта в библиотеке */
  11442. const artifactId = titanInfo.artifacts[slotId];
  11443. const artInfo = artTitanLib.id[artifactId];
  11444. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  11445.  
  11446. const costCurrency = Object.keys(costNextLevel).pop();
  11447. let costValue = 0;
  11448. let currentValue = 0;
  11449. if (costCurrency == 'gold') {
  11450. costValue = costNextLevel[costCurrency];
  11451. currentValue = userInfo.gold;
  11452. } else {
  11453. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11454. const costId = costValues[0];
  11455. costValue = +costValues[1];
  11456. currentValue = inventory[costCurrency][costId];
  11457. }
  11458.  
  11459. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11460. if (level < upArt.level && currentValue >= costValue) {
  11461. upArt.level = level;
  11462. upArt.titanId = titan.id;
  11463. upArt.slotId = slotId;
  11464. break;
  11465. }
  11466. }
  11467. }
  11468. return upArt;
  11469. }
  11470.  
  11471. getEnchantRune() {
  11472. const heroes = Object.values(this.questInfo['heroGetAll']);
  11473. const inventory = this.questInfo['inventoryGet'];
  11474. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  11475. for (let i = 1; i <= 4; i++) {
  11476. if (inventory.consumable[i] > 0) {
  11477. enchRune.itemId = i;
  11478. break;
  11479. }
  11480. return enchRune;
  11481. }
  11482.  
  11483. const runeLib = lib.getData('rune');
  11484. const runeLvls = Object.values(runeLib.level);
  11485. /**
  11486. * color - 4 (синий) открывает 1 и 2 символ
  11487. * color - 7 (фиолетовый) открывает 3 символ
  11488. * color - 8 (фиолетовый +1) открывает 4 символ
  11489. * color - 9 (фиолетовый +2) открывает 5 символ
  11490. */
  11491. // TODO: кажется надо учесть уровень команды
  11492. const colors = [4, 4, 7, 8, 9];
  11493. for (const hero of heroes) {
  11494. const color = hero.color;
  11495.  
  11496. for (let runeTier in hero.runes) {
  11497. /* Проверка на доступность руны */
  11498. if (color < colors[runeTier]) {
  11499. continue;
  11500. }
  11501. /* Текущий опыт руны */
  11502. const exp = hero.runes[runeTier];
  11503. if (exp >= 43750) {
  11504. continue;
  11505. }
  11506.  
  11507. let level = 0;
  11508. if (exp) {
  11509. for (let lvl of runeLvls) {
  11510. if (exp >= lvl.enchantValue) {
  11511. level = lvl.level;
  11512. } else {
  11513. break;
  11514. }
  11515. }
  11516. }
  11517. /** Уровень героя необходимый для уровня руны */
  11518. const heroLevel = runeLib.level[level].heroLevel;
  11519. if (hero.level < heroLevel) {
  11520. continue;
  11521. }
  11522.  
  11523. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11524. if (exp < enchRune.exp) {
  11525. enchRune.exp = exp;
  11526. enchRune.heroId = hero.id;
  11527. enchRune.tier = runeTier;
  11528. break;
  11529. }
  11530. }
  11531. }
  11532. return enchRune;
  11533. }
  11534.  
  11535. getOutlandChest() {
  11536. const bosses = this.questInfo['bossGetAll'];
  11537.  
  11538. const calls = [];
  11539.  
  11540. for (let boss of bosses) {
  11541. if (boss.mayRaid) {
  11542. calls.push({
  11543. name: 'bossRaid',
  11544. args: {
  11545. bossId: boss.id,
  11546. },
  11547. ident: 'bossRaid_' + boss.id,
  11548. });
  11549. calls.push({
  11550. name: 'bossOpenChest',
  11551. args: {
  11552. bossId: boss.id,
  11553. amount: 1,
  11554. starmoney: 0,
  11555. },
  11556. ident: 'bossOpenChest_' + boss.id,
  11557. });
  11558. } else if (boss.chestId == 1) {
  11559. calls.push({
  11560. name: 'bossOpenChest',
  11561. args: {
  11562. bossId: boss.id,
  11563. amount: 1,
  11564. starmoney: 0,
  11565. },
  11566. ident: 'bossOpenChest_' + boss.id,
  11567. });
  11568. }
  11569. }
  11570.  
  11571. return calls;
  11572. }
  11573.  
  11574. getExpHero() {
  11575. const heroes = Object.values(this.questInfo['heroGetAll']);
  11576. const inventory = this.questInfo['inventoryGet'];
  11577. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  11578. /** зелья опыта (consumable 9, 10, 11, 12) */
  11579. for (let i = 9; i <= 12; i++) {
  11580. if (inventory.consumable[i]) {
  11581. expHero.libId = i;
  11582. break;
  11583. }
  11584. }
  11585.  
  11586. for (const hero of heroes) {
  11587. const exp = hero.xp;
  11588. if (exp < expHero.exp) {
  11589. expHero.heroId = hero.id;
  11590. }
  11591. }
  11592. return expHero;
  11593. }
  11594.  
  11595. getHeroIdTitanGift() {
  11596. const heroes = Object.values(this.questInfo['heroGetAll']);
  11597. const inventory = this.questInfo['inventoryGet'];
  11598. const user = this.questInfo['userGetInfo'];
  11599. const titanGiftLib = lib.getData('titanGift');
  11600. /** Искры */
  11601. const titanGift = inventory.consumable[24];
  11602. let heroId = 0;
  11603. let minLevel = 30;
  11604.  
  11605. if (titanGift < 250 || user.gold < 7000) {
  11606. return 0;
  11607. }
  11608.  
  11609. for (const hero of heroes) {
  11610. if (hero.titanGiftLevel >= 30) {
  11611. continue;
  11612. }
  11613.  
  11614. if (!hero.titanGiftLevel) {
  11615. return hero.id;
  11616. }
  11617.  
  11618. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  11619. if (minLevel > hero.titanGiftLevel && titanGift >= cost.consumable[24] && user.gold >= cost.gold) {
  11620. minLevel = hero.titanGiftLevel;
  11621. heroId = hero.id;
  11622. }
  11623. }
  11624.  
  11625. return heroId;
  11626. }
  11627.  
  11628. getHeroicMissionId() {
  11629. // Получаем доступные миссии с 3 звездами
  11630. const availableMissionsToRaid = Object.values(this.questInfo.missionGetAll)
  11631. .filter((mission) => mission.stars === 3)
  11632. .map((mission) => mission.id);
  11633.  
  11634. // Получаем героев для улучшения, у которых меньше 6 звезд
  11635. const heroesToUpgrade = Object.values(this.questInfo.heroGetAll)
  11636. .filter((hero) => hero.star < 6)
  11637. .sort((a, b) => b.power - a.power)
  11638. .map((hero) => hero.id);
  11639.  
  11640. // Получаем героические миссии, которые доступны для рейдов
  11641. const heroicMissions = Object.values(lib.data.mission).filter((mission) => mission.isHeroic && availableMissionsToRaid.includes(mission.id));
  11642.  
  11643. // Собираем дропы из героических миссий
  11644. const drops = heroicMissions.map((mission) => {
  11645. const lastWave = mission.normalMode.waves[mission.normalMode.waves.length - 1];
  11646. const allRewards = lastWave.enemies[lastWave.enemies.length - 1]
  11647. .drop.map((drop) => drop.reward);
  11648.  
  11649. const heroId = +Object.keys(allRewards.find((reward) => reward.fragmentHero).fragmentHero).pop();
  11650.  
  11651. return { id: mission.id, heroId };
  11652. });
  11653.  
  11654. // Определяем, какие дропы подходят для героев, которых нужно улучшить
  11655. const heroDrops = heroesToUpgrade.map((heroId) => drops.find((drop) => drop.heroId == heroId)).filter((drop) => drop);
  11656. const firstMission = heroDrops[0];
  11657. // Выбираем миссию для рейда
  11658. const selectedMissionId = firstMission ? firstMission.id : 1;
  11659.  
  11660. const stamina = this.questInfo.userGetInfo.refillable.find((x) => x.id == 1).amount;
  11661. const costMissions = 3 * lib.data.mission[selectedMissionId].normalMode.teamExp;
  11662. if (stamina < costMissions) {
  11663. console.log('Энергии не достаточно');
  11664. return 0;
  11665. }
  11666. return selectedMissionId;
  11667. }
  11668.  
  11669. end(status) {
  11670. setProgress(status, true);
  11671. this.resolve();
  11672. }
  11673. }
  11674.  
  11675. this.questRun = dailyQuests;
  11676. this.HWHClasses.dailyQuests = dailyQuests;
  11677.  
  11678. function testDoYourBest() {
  11679. const { doYourBest } = HWHClasses;
  11680. return new Promise((resolve, reject) => {
  11681. const doIt = new doYourBest(resolve, reject);
  11682. doIt.start();
  11683. });
  11684. }
  11685.  
  11686. /**
  11687. * Do everything button
  11688. *
  11689. * Кнопка сделать все
  11690. */
  11691. class doYourBest {
  11692.  
  11693. funcList = [
  11694. {
  11695. name: 'getOutland',
  11696. label: I18N('ASSEMBLE_OUTLAND'),
  11697. checked: false
  11698. },
  11699. {
  11700. name: 'testTower',
  11701. label: I18N('PASS_THE_TOWER'),
  11702. checked: false
  11703. },
  11704. {
  11705. name: 'checkExpedition',
  11706. label: I18N('CHECK_EXPEDITIONS'),
  11707. checked: false
  11708. },
  11709. {
  11710. name: 'testTitanArena',
  11711. label: I18N('COMPLETE_TOE'),
  11712. checked: false
  11713. },
  11714. {
  11715. name: 'mailGetAll',
  11716. label: I18N('COLLECT_MAIL'),
  11717. checked: false
  11718. },
  11719. {
  11720. name: 'collectAllStuff',
  11721. label: I18N('COLLECT_MISC'),
  11722. title: I18N('COLLECT_MISC_TITLE'),
  11723. checked: false
  11724. },
  11725. {
  11726. name: 'getDailyBonus',
  11727. label: I18N('DAILY_BONUS'),
  11728. checked: false
  11729. },
  11730. {
  11731. name: 'dailyQuests',
  11732. label: I18N('DO_DAILY_QUESTS'),
  11733. checked: false
  11734. },
  11735. {
  11736. name: 'rollAscension',
  11737. label: I18N('SEER_TITLE'),
  11738. checked: false
  11739. },
  11740. {
  11741. name: 'questAllFarm',
  11742. label: I18N('COLLECT_QUEST_REWARDS'),
  11743. checked: false
  11744. },
  11745. {
  11746. name: 'testDungeon',
  11747. label: I18N('COMPLETE_DUNGEON'),
  11748. checked: false
  11749. },
  11750. {
  11751. name: 'synchronization',
  11752. label: I18N('MAKE_A_SYNC'),
  11753. checked: false
  11754. },
  11755. {
  11756. name: 'reloadGame',
  11757. label: I18N('RELOAD_GAME'),
  11758. checked: false
  11759. },
  11760. ];
  11761.  
  11762. functions = {
  11763. getOutland,
  11764. testTower,
  11765. checkExpedition,
  11766. testTitanArena,
  11767. mailGetAll,
  11768. collectAllStuff: async () => {
  11769. await offerFarmAllReward();
  11770. 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"}]}');
  11771. },
  11772. dailyQuests: async function () {
  11773. const quests = new dailyQuests(() => { }, () => { });
  11774. await quests.autoInit(true);
  11775. await quests.start();
  11776. },
  11777. rollAscension,
  11778. getDailyBonus,
  11779. questAllFarm,
  11780. testDungeon,
  11781. synchronization: async () => {
  11782. cheats.refreshGame();
  11783. },
  11784. reloadGame: async () => {
  11785. location.reload();
  11786. },
  11787. }
  11788.  
  11789. constructor(resolve, reject, questInfo) {
  11790. this.resolve = resolve;
  11791. this.reject = reject;
  11792. this.questInfo = questInfo
  11793. }
  11794.  
  11795. async start() {
  11796. const selectedDoIt = getSaveVal('selectedDoIt', {});
  11797.  
  11798. this.funcList.forEach(task => {
  11799. if (!selectedDoIt[task.name]) {
  11800. selectedDoIt[task.name] = {
  11801. checked: task.checked
  11802. }
  11803. } else {
  11804. task.checked = selectedDoIt[task.name].checked
  11805. }
  11806. });
  11807.  
  11808. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  11809. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11810. { msg: I18N('BTN_GO'), result: true },
  11811. ], this.funcList);
  11812.  
  11813. if (!answer) {
  11814. this.end('');
  11815. return;
  11816. }
  11817.  
  11818. const taskList = popup.getCheckBoxes();
  11819. taskList.forEach(task => {
  11820. selectedDoIt[task.name].checked = task.checked;
  11821. });
  11822. setSaveVal('selectedDoIt', selectedDoIt);
  11823. for (const task of popup.getCheckBoxes()) {
  11824. if (task.checked) {
  11825. try {
  11826. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  11827. await this.functions[task.name]();
  11828. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  11829. } catch (error) {
  11830. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  11831. { msg: I18N('BTN_NO'), result: false },
  11832. { msg: I18N('BTN_YES'), result: true },
  11833. ])) {
  11834. this.errorHandling(error);
  11835. }
  11836. }
  11837. }
  11838. }
  11839. setTimeout((msg) => {
  11840. this.end(msg);
  11841. }, 2000, I18N('ALL_TASK_COMPLETED'));
  11842. return;
  11843. }
  11844.  
  11845. errorHandling(error) {
  11846. //console.error(error);
  11847. let errorInfo = error.toString() + '\n';
  11848. try {
  11849. const errorStack = error.stack.split('\n');
  11850. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  11851. errorInfo += errorStack.slice(0, endStack).join('\n');
  11852. } catch (e) {
  11853. errorInfo += error.stack;
  11854. }
  11855. copyText(errorInfo);
  11856. }
  11857.  
  11858. end(status) {
  11859. setProgress(status, true);
  11860. this.resolve();
  11861. }
  11862. }
  11863.  
  11864. this.HWHClasses.doYourBest = doYourBest;
  11865.  
  11866. /**
  11867. * Passing the adventure along the specified route
  11868. *
  11869. * Прохождение приключения по указанному маршруту
  11870. */
  11871. function testAdventure(type) {
  11872. const { executeAdventure } = HWHClasses;
  11873. return new Promise((resolve, reject) => {
  11874. const bossBattle = new executeAdventure(resolve, reject);
  11875. bossBattle.start(type);
  11876. });
  11877. }
  11878.  
  11879. /**
  11880. * Passing the adventure along the specified route
  11881. *
  11882. * Прохождение приключения по указанному маршруту
  11883. */
  11884. class executeAdventure {
  11885.  
  11886. type = 'default';
  11887.  
  11888. actions = {
  11889. default: {
  11890. getInfo: "adventure_getInfo",
  11891. startBattle: 'adventure_turnStartBattle',
  11892. endBattle: 'adventure_endBattle',
  11893. collectBuff: 'adventure_turnCollectBuff'
  11894. },
  11895. solo: {
  11896. getInfo: "adventureSolo_getInfo",
  11897. startBattle: 'adventureSolo_turnStartBattle',
  11898. endBattle: 'adventureSolo_endBattle',
  11899. collectBuff: 'adventureSolo_turnCollectBuff'
  11900. }
  11901. }
  11902.  
  11903. terminatеReason = I18N('UNKNOWN');
  11904. callAdventureInfo = {
  11905. name: "adventure_getInfo",
  11906. args: {},
  11907. ident: "adventure_getInfo"
  11908. }
  11909. callTeamGetAll = {
  11910. name: "teamGetAll",
  11911. args: {},
  11912. ident: "teamGetAll"
  11913. }
  11914. callTeamGetFavor = {
  11915. name: "teamGetFavor",
  11916. args: {},
  11917. ident: "teamGetFavor"
  11918. }
  11919. callStartBattle = {
  11920. name: "adventure_turnStartBattle",
  11921. args: {},
  11922. ident: "body"
  11923. }
  11924. callEndBattle = {
  11925. name: "adventure_endBattle",
  11926. args: {
  11927. result: {},
  11928. progress: {},
  11929. },
  11930. ident: "body"
  11931. }
  11932. callCollectBuff = {
  11933. name: "adventure_turnCollectBuff",
  11934. args: {},
  11935. ident: "body"
  11936. }
  11937.  
  11938. constructor(resolve, reject) {
  11939. this.resolve = resolve;
  11940. this.reject = reject;
  11941. }
  11942.  
  11943. async start(type) {
  11944. this.type = type || this.type;
  11945. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  11946. const data = await Send(JSON.stringify({
  11947. calls: [
  11948. this.callAdventureInfo,
  11949. this.callTeamGetAll,
  11950. this.callTeamGetFavor
  11951. ]
  11952. }));
  11953. return this.checkAdventureInfo(data.results);
  11954. }
  11955.  
  11956. async getPath() {
  11957. const oldVal = getSaveVal('adventurePath', '');
  11958. const keyPath = `adventurePath:${this.mapIdent}`;
  11959. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  11960. {
  11961. msg: I18N('START_ADVENTURE'),
  11962. placeholder: '1,2,3,4,5,6',
  11963. isInput: true,
  11964. default: getSaveVal(keyPath, oldVal)
  11965. },
  11966. {
  11967. msg: I18N('BTN_CANCEL'),
  11968. result: false,
  11969. isCancel: true
  11970. },
  11971. ]);
  11972. if (!answer) {
  11973. this.terminatеReason = I18N('BTN_CANCELED');
  11974. return false;
  11975. }
  11976.  
  11977. let path = answer.split(',');
  11978. if (path.length < 2) {
  11979. path = answer.split('-');
  11980. }
  11981. if (path.length < 2) {
  11982. this.terminatеReason = I18N('MUST_TWO_POINTS');
  11983. return false;
  11984. }
  11985.  
  11986. for (let p in path) {
  11987. path[p] = +path[p].trim()
  11988. if (Number.isNaN(path[p])) {
  11989. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  11990. return false;
  11991. }
  11992. }
  11993.  
  11994. if (!this.checkPath(path)) {
  11995. return false;
  11996. }
  11997. setSaveVal(keyPath, answer);
  11998. return path;
  11999. }
  12000.  
  12001. checkPath(path) {
  12002. for (let i = 0; i < path.length - 1; i++) {
  12003. const currentPoint = path[i];
  12004. const nextPoint = path[i + 1];
  12005.  
  12006. const isValidPath = this.paths.some(p =>
  12007. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  12008. (p.from_id === nextPoint && p.to_id === currentPoint)
  12009. );
  12010.  
  12011. if (!isValidPath) {
  12012. this.terminatеReason = I18N('INCORRECT_WAY', {
  12013. from: currentPoint,
  12014. to: nextPoint,
  12015. });
  12016. return false;
  12017. }
  12018. }
  12019.  
  12020. return true;
  12021. }
  12022.  
  12023. async checkAdventureInfo(data) {
  12024. this.advInfo = data[0].result.response;
  12025. if (!this.advInfo) {
  12026. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  12027. return this.end();
  12028. }
  12029. const heroesTeam = data[1].result.response.adventure_hero;
  12030. const favor = data[2]?.result.response.adventure_hero;
  12031. const heroes = heroesTeam.slice(0, 5);
  12032. const pet = heroesTeam[5];
  12033. this.args = {
  12034. pet,
  12035. heroes,
  12036. favor,
  12037. path: [],
  12038. broadcast: false
  12039. }
  12040. const advUserInfo = this.advInfo.users[userInfo.id];
  12041. this.turnsLeft = advUserInfo.turnsLeft;
  12042. this.currentNode = advUserInfo.currentNode;
  12043. this.nodes = this.advInfo.nodes;
  12044. this.paths = this.advInfo.paths;
  12045. this.mapIdent = this.advInfo.mapIdent;
  12046.  
  12047. this.path = await this.getPath();
  12048. if (!this.path) {
  12049. return this.end();
  12050. }
  12051.  
  12052. if (this.currentNode == 1 && this.path[0] != 1) {
  12053. this.path.unshift(1);
  12054. }
  12055.  
  12056. return this.loop();
  12057. }
  12058.  
  12059. async loop() {
  12060. const position = this.path.indexOf(+this.currentNode);
  12061. if (!(~position)) {
  12062. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  12063. return this.end();
  12064. }
  12065. this.path = this.path.slice(position);
  12066. if ((this.path.length - 1) > this.turnsLeft &&
  12067. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  12068. { msg: I18N('YES_CONTINUE'), result: false },
  12069. { msg: I18N('BTN_NO'), result: true },
  12070. ])) {
  12071. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  12072. return this.end();
  12073. }
  12074. const toPath = [];
  12075. for (const nodeId of this.path) {
  12076. if (!this.turnsLeft) {
  12077. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  12078. return this.end();
  12079. }
  12080. toPath.push(nodeId);
  12081. console.log(toPath);
  12082. if (toPath.length > 1) {
  12083. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  12084. }
  12085. if (nodeId == this.currentNode) {
  12086. continue;
  12087. }
  12088.  
  12089. const nodeInfo = this.getNodeInfo(nodeId);
  12090. if (nodeInfo.type == 'TYPE_COMBAT') {
  12091. if (nodeInfo.state == 'empty') {
  12092. this.turnsLeft--;
  12093. continue;
  12094. }
  12095.  
  12096. /**
  12097. * Disable regular battle cancellation
  12098. *
  12099. * Отключаем штатную отменую боя
  12100. */
  12101. setIsCancalBattle(false);
  12102. if (await this.battle(toPath)) {
  12103. this.turnsLeft--;
  12104. toPath.splice(0, toPath.indexOf(nodeId));
  12105. nodeInfo.state = 'empty';
  12106. setIsCancalBattle(true);
  12107. continue;
  12108. }
  12109. setIsCancalBattle(true);
  12110. return this.end()
  12111. }
  12112.  
  12113. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  12114. const buff = this.checkBuff(nodeInfo);
  12115. if (buff == null) {
  12116. continue;
  12117. }
  12118.  
  12119. if (await this.collectBuff(buff, toPath)) {
  12120. this.turnsLeft--;
  12121. toPath.splice(0, toPath.indexOf(nodeId));
  12122. continue;
  12123. }
  12124. this.terminatеReason = I18N('BUFF_GET_ERROR');
  12125. return this.end();
  12126. }
  12127. }
  12128. this.terminatеReason = I18N('SUCCESS');
  12129. return this.end();
  12130. }
  12131.  
  12132. /**
  12133. * Carrying out a fight
  12134. *
  12135. * Проведение боя
  12136. */
  12137. async battle(path, preCalc = true) {
  12138. const data = await this.startBattle(path);
  12139. try {
  12140. const battle = data.results[0].result.response.battle;
  12141. const result = await Calc(battle);
  12142. if (result.result.win) {
  12143. const info = await this.endBattle(result);
  12144. if (info.results[0].result.response?.error) {
  12145. this.terminatеReason = I18N('BATTLE_END_ERROR');
  12146. return false;
  12147. }
  12148. } else {
  12149. await this.cancelBattle(result);
  12150.  
  12151. if (preCalc && await this.preCalcBattle(battle)) {
  12152. path = path.slice(-2);
  12153. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  12154. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  12155. const result = await this.battle(path, false);
  12156. if (result) {
  12157. setProgress(I18N('VICTORY'));
  12158. return true;
  12159. }
  12160. }
  12161. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  12162. return false;
  12163. }
  12164. return false;
  12165. }
  12166. } catch (error) {
  12167. console.error(error);
  12168. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  12169. { msg: I18N('BTN_NO'), result: false },
  12170. { msg: I18N('BTN_YES'), result: true },
  12171. ])) {
  12172. this.errorHandling(error, data);
  12173. }
  12174. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  12175. return false;
  12176. }
  12177. return true;
  12178. }
  12179.  
  12180. /**
  12181. * Recalculate battles
  12182. *
  12183. * Прерасчтет битвы
  12184. */
  12185. async preCalcBattle(battle) {
  12186. const countTestBattle = getInput('countTestBattle');
  12187. for (let i = 0; i < countTestBattle; i++) {
  12188. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  12189. const result = await Calc(battle);
  12190. if (result.result.win) {
  12191. console.log(i, countTestBattle);
  12192. return true;
  12193. }
  12194. }
  12195. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  12196. return false;
  12197. }
  12198.  
  12199. /**
  12200. * Starts a fight
  12201. *
  12202. * Начинает бой
  12203. */
  12204. startBattle(path) {
  12205. this.args.path = path;
  12206. this.callStartBattle.name = this.actions[this.type].startBattle;
  12207. this.callStartBattle.args = this.args
  12208. const calls = [this.callStartBattle];
  12209. return Send(JSON.stringify({ calls }));
  12210. }
  12211.  
  12212. cancelBattle(battle) {
  12213. const fixBattle = function (heroes) {
  12214. for (const ids in heroes) {
  12215. const hero = heroes[ids];
  12216. hero.energy = random(1, 999);
  12217. if (hero.hp > 0) {
  12218. hero.hp = random(1, hero.hp);
  12219. }
  12220. }
  12221. }
  12222. fixBattle(battle.progress[0].attackers.heroes);
  12223. fixBattle(battle.progress[0].defenders.heroes);
  12224. return this.endBattle(battle);
  12225. }
  12226.  
  12227. /**
  12228. * Ends the fight
  12229. *
  12230. * Заканчивает бой
  12231. */
  12232. endBattle(battle) {
  12233. this.callEndBattle.name = this.actions[this.type].endBattle;
  12234. this.callEndBattle.args.result = battle.result
  12235. this.callEndBattle.args.progress = battle.progress
  12236. const calls = [this.callEndBattle];
  12237. return Send(JSON.stringify({ calls }));
  12238. }
  12239.  
  12240. /**
  12241. * Checks if you can get a buff
  12242. *
  12243. * Проверяет можно ли получить баф
  12244. */
  12245. checkBuff(nodeInfo) {
  12246. let id = null;
  12247. let value = 0;
  12248. for (const buffId in nodeInfo.buffs) {
  12249. const buff = nodeInfo.buffs[buffId];
  12250. if (buff.owner == null && buff.value > value) {
  12251. id = buffId;
  12252. value = buff.value;
  12253. }
  12254. }
  12255. nodeInfo.buffs[id].owner = 'Я';
  12256. return id;
  12257. }
  12258.  
  12259. /**
  12260. * Collects a buff
  12261. *
  12262. * Собирает баф
  12263. */
  12264. async collectBuff(buff, path) {
  12265. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  12266. this.callCollectBuff.args = { buff, path };
  12267. const calls = [this.callCollectBuff];
  12268. return Send(JSON.stringify({ calls }));
  12269. }
  12270.  
  12271. getNodeInfo(nodeId) {
  12272. return this.nodes.find(node => node.id == nodeId);
  12273. }
  12274.  
  12275. errorHandling(error, data) {
  12276. //console.error(error);
  12277. let errorInfo = error.toString() + '\n';
  12278. try {
  12279. const errorStack = error.stack.split('\n');
  12280. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  12281. errorInfo += errorStack.slice(0, endStack).join('\n');
  12282. } catch (e) {
  12283. errorInfo += error.stack;
  12284. }
  12285. if (data) {
  12286. errorInfo += '\nData: ' + JSON.stringify(data);
  12287. }
  12288. copyText(errorInfo);
  12289. }
  12290.  
  12291. end() {
  12292. setIsCancalBattle(true);
  12293. setProgress(this.terminatеReason, true);
  12294. console.log(this.terminatеReason);
  12295. this.resolve();
  12296. }
  12297. }
  12298.  
  12299. this.HWHClasses.executeAdventure = executeAdventure;
  12300.  
  12301. /**
  12302. * Passage of brawls
  12303. *
  12304. * Прохождение потасовок
  12305. */
  12306. function testBrawls(isAuto) {
  12307. const { executeBrawls } = HWHClasses;
  12308. return new Promise((resolve, reject) => {
  12309. const brawls = new executeBrawls(resolve, reject);
  12310. brawls.start(brawlsPack, isAuto);
  12311. });
  12312. }
  12313. /**
  12314. * Passage of brawls
  12315. *
  12316. * Прохождение потасовок
  12317. */
  12318. class executeBrawls {
  12319. callBrawlQuestGetInfo = {
  12320. name: "brawl_questGetInfo",
  12321. args: {},
  12322. ident: "brawl_questGetInfo"
  12323. }
  12324. callBrawlFindEnemies = {
  12325. name: "brawl_findEnemies",
  12326. args: {},
  12327. ident: "brawl_findEnemies"
  12328. }
  12329. callBrawlQuestFarm = {
  12330. name: "brawl_questFarm",
  12331. args: {},
  12332. ident: "brawl_questFarm"
  12333. }
  12334. callUserGetInfo = {
  12335. name: "userGetInfo",
  12336. args: {},
  12337. ident: "userGetInfo"
  12338. }
  12339. callTeamGetMaxUpgrade = {
  12340. name: "teamGetMaxUpgrade",
  12341. args: {},
  12342. ident: "teamGetMaxUpgrade"
  12343. }
  12344. callBrawlGetInfo = {
  12345. name: "brawl_getInfo",
  12346. args: {},
  12347. ident: "brawl_getInfo"
  12348. }
  12349.  
  12350. stats = {
  12351. win: 0,
  12352. loss: 0,
  12353. count: 0,
  12354. }
  12355.  
  12356. stage = {
  12357. '3': 1,
  12358. '7': 2,
  12359. '12': 3,
  12360. }
  12361.  
  12362. attempts = 0;
  12363.  
  12364. constructor(resolve, reject) {
  12365. this.resolve = resolve;
  12366. this.reject = reject;
  12367.  
  12368. const allHeroIds = Object.keys(lib.getData('hero'));
  12369. this.callTeamGetMaxUpgrade.args.units = {
  12370. hero: allHeroIds.filter((id) => +id < 1000),
  12371. titan: allHeroIds.filter((id) => +id >= 4000 && +id < 4100),
  12372. pet: allHeroIds.filter((id) => +id >= 6000 && +id < 6100),
  12373. };
  12374. }
  12375.  
  12376. async start(args, isAuto) {
  12377. this.isAuto = isAuto;
  12378. this.args = args;
  12379. setIsCancalBattle(false);
  12380. this.brawlInfo = await this.getBrawlInfo();
  12381. this.attempts = this.brawlInfo.attempts;
  12382.  
  12383. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12384. this.end(I18N('DONT_HAVE_LIVES'));
  12385. return;
  12386. }
  12387.  
  12388. while (1) {
  12389. if (!isBrawlsAutoStart) {
  12390. this.end(I18N('BTN_CANCELED'));
  12391. return;
  12392. }
  12393.  
  12394. const maxStage = this.brawlInfo.questInfo.stage;
  12395. const stage = this.stage[maxStage];
  12396. const progress = this.brawlInfo.questInfo.progress;
  12397.  
  12398. setProgress(
  12399. `${I18N('STAGE')} ${stage}: ${progress}/${maxStage}<br>${I18N('FIGHTS')}: ${this.stats.count}<br>${I18N('WINS')}: ${
  12400. this.stats.win
  12401. }<br>${I18N('LOSSES')}: ${this.stats.loss}<br>${I18N('LIVES')}: ${this.attempts}<br>${I18N('STOP')}`,
  12402. false,
  12403. function () {
  12404. isBrawlsAutoStart = false;
  12405. }
  12406. );
  12407.  
  12408. if (this.brawlInfo.questInfo.canFarm) {
  12409. const result = await this.questFarm();
  12410. console.log(result);
  12411. }
  12412.  
  12413. if (!this.continueAttack && this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  12414. if (
  12415. await popup.confirm(I18N('BRAWL_DAILY_TASK_COMPLETED'), [
  12416. { msg: I18N('BTN_NO'), result: true },
  12417. { msg: I18N('BTN_YES'), result: false },
  12418. ])
  12419. ) {
  12420. this.end(I18N('SUCCESS'));
  12421. return;
  12422. } else {
  12423. this.continueAttack = true;
  12424. }
  12425. }
  12426.  
  12427. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12428. this.end(I18N('DONT_HAVE_LIVES'));
  12429. return;
  12430. }
  12431.  
  12432. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  12433.  
  12434. // Автоматический подбор пачки
  12435. if (this.isAuto) {
  12436. if (this.mandatoryId <= 4000 && this.mandatoryId != 13) {
  12437. this.end(I18N('BRAWL_AUTO_PACK_NOT_CUR_HERO'));
  12438. return;
  12439. }
  12440. if (this.mandatoryId >= 4000 && this.mandatoryId < 4100) {
  12441. this.args = await this.updateTitanPack(enemie.heroes);
  12442. } else if (this.mandatoryId < 4000 && this.mandatoryId == 13) {
  12443. this.args = await this.updateHeroesPack(enemie.heroes);
  12444. }
  12445. }
  12446.  
  12447. const result = await this.battle(enemie.userId);
  12448. this.brawlInfo = {
  12449. questInfo: result[1].result.response,
  12450. findEnemies: result[2].result.response,
  12451. };
  12452. }
  12453. }
  12454.  
  12455. async updateTitanPack(enemieHeroes) {
  12456. const packs = [
  12457. [4033, 4040, 4041, 4042, 4043],
  12458. [4032, 4040, 4041, 4042, 4043],
  12459. [4031, 4040, 4041, 4042, 4043],
  12460. [4030, 4040, 4041, 4042, 4043],
  12461. [4032, 4033, 4040, 4042, 4043],
  12462. [4030, 4033, 4041, 4042, 4043],
  12463. [4031, 4033, 4040, 4042, 4043],
  12464. [4032, 4033, 4040, 4041, 4043],
  12465. [4023, 4040, 4041, 4042, 4043],
  12466. [4030, 4033, 4040, 4042, 4043],
  12467. [4031, 4033, 4040, 4041, 4043],
  12468. [4022, 4040, 4041, 4042, 4043],
  12469. [4030, 4033, 4040, 4041, 4043],
  12470. [4021, 4040, 4041, 4042, 4043],
  12471. [4020, 4040, 4041, 4042, 4043],
  12472. [4023, 4033, 4040, 4042, 4043],
  12473. [4030, 4032, 4033, 4042, 4043],
  12474. [4023, 4033, 4040, 4041, 4043],
  12475. [4031, 4032, 4033, 4040, 4043],
  12476. [4030, 4032, 4033, 4041, 4043],
  12477. [4030, 4031, 4033, 4042, 4043],
  12478. [4013, 4040, 4041, 4042, 4043],
  12479. [4030, 4032, 4033, 4040, 4043],
  12480. [4030, 4031, 4033, 4041, 4043],
  12481. [4012, 4040, 4041, 4042, 4043],
  12482. [4030, 4031, 4033, 4040, 4043],
  12483. [4011, 4040, 4041, 4042, 4043],
  12484. [4010, 4040, 4041, 4042, 4043],
  12485. [4023, 4032, 4033, 4042, 4043],
  12486. [4022, 4032, 4033, 4042, 4043],
  12487. [4023, 4032, 4033, 4041, 4043],
  12488. [4021, 4032, 4033, 4042, 4043],
  12489. [4022, 4032, 4033, 4041, 4043],
  12490. [4023, 4030, 4033, 4042, 4043],
  12491. [4023, 4032, 4033, 4040, 4043],
  12492. [4013, 4033, 4040, 4042, 4043],
  12493. [4020, 4032, 4033, 4042, 4043],
  12494. [4021, 4032, 4033, 4041, 4043],
  12495. [4022, 4030, 4033, 4042, 4043],
  12496. [4022, 4032, 4033, 4040, 4043],
  12497. [4023, 4030, 4033, 4041, 4043],
  12498. [4023, 4031, 4033, 4040, 4043],
  12499. [4013, 4033, 4040, 4041, 4043],
  12500. [4020, 4031, 4033, 4042, 4043],
  12501. [4020, 4032, 4033, 4041, 4043],
  12502. [4021, 4030, 4033, 4042, 4043],
  12503. [4021, 4032, 4033, 4040, 4043],
  12504. [4022, 4030, 4033, 4041, 4043],
  12505. [4022, 4031, 4033, 4040, 4043],
  12506. [4023, 4030, 4033, 4040, 4043],
  12507. [4030, 4031, 4032, 4033, 4043],
  12508. [4003, 4040, 4041, 4042, 4043],
  12509. [4020, 4030, 4033, 4042, 4043],
  12510. [4020, 4031, 4033, 4041, 4043],
  12511. [4020, 4032, 4033, 4040, 4043],
  12512. [4021, 4030, 4033, 4041, 4043],
  12513. [4021, 4031, 4033, 4040, 4043],
  12514. [4022, 4030, 4033, 4040, 4043],
  12515. [4030, 4031, 4032, 4033, 4042],
  12516. [4002, 4040, 4041, 4042, 4043],
  12517. [4020, 4030, 4033, 4041, 4043],
  12518. [4020, 4031, 4033, 4040, 4043],
  12519. [4021, 4030, 4033, 4040, 4043],
  12520. [4030, 4031, 4032, 4033, 4041],
  12521. [4001, 4040, 4041, 4042, 4043],
  12522. [4030, 4031, 4032, 4033, 4040],
  12523. [4000, 4040, 4041, 4042, 4043],
  12524. [4013, 4032, 4033, 4042, 4043],
  12525. [4012, 4032, 4033, 4042, 4043],
  12526. [4013, 4032, 4033, 4041, 4043],
  12527. [4023, 4031, 4032, 4033, 4043],
  12528. [4011, 4032, 4033, 4042, 4043],
  12529. [4012, 4032, 4033, 4041, 4043],
  12530. [4013, 4030, 4033, 4042, 4043],
  12531. [4013, 4032, 4033, 4040, 4043],
  12532. [4023, 4030, 4032, 4033, 4043],
  12533. [4003, 4033, 4040, 4042, 4043],
  12534. [4013, 4023, 4040, 4042, 4043],
  12535. [4010, 4032, 4033, 4042, 4043],
  12536. [4011, 4032, 4033, 4041, 4043],
  12537. [4012, 4030, 4033, 4042, 4043],
  12538. [4012, 4032, 4033, 4040, 4043],
  12539. [4013, 4030, 4033, 4041, 4043],
  12540. [4013, 4031, 4033, 4040, 4043],
  12541. [4023, 4030, 4031, 4033, 4043],
  12542. [4003, 4033, 4040, 4041, 4043],
  12543. [4013, 4023, 4040, 4041, 4043],
  12544. [4010, 4031, 4033, 4042, 4043],
  12545. [4010, 4032, 4033, 4041, 4043],
  12546. [4011, 4030, 4033, 4042, 4043],
  12547. [4011, 4032, 4033, 4040, 4043],
  12548. [4012, 4030, 4033, 4041, 4043],
  12549. [4012, 4031, 4033, 4040, 4043],
  12550. [4013, 4030, 4033, 4040, 4043],
  12551. [4010, 4030, 4033, 4042, 4043],
  12552. [4010, 4031, 4033, 4041, 4043],
  12553. [4010, 4032, 4033, 4040, 4043],
  12554. [4011, 4030, 4033, 4041, 4043],
  12555. [4011, 4031, 4033, 4040, 4043],
  12556. [4012, 4030, 4033, 4040, 4043],
  12557. [4010, 4030, 4033, 4041, 4043],
  12558. [4010, 4031, 4033, 4040, 4043],
  12559. [4011, 4030, 4033, 4040, 4043],
  12560. [4003, 4032, 4033, 4042, 4043],
  12561. [4002, 4032, 4033, 4042, 4043],
  12562. [4003, 4032, 4033, 4041, 4043],
  12563. [4013, 4031, 4032, 4033, 4043],
  12564. [4001, 4032, 4033, 4042, 4043],
  12565. [4002, 4032, 4033, 4041, 4043],
  12566. [4003, 4030, 4033, 4042, 4043],
  12567. [4003, 4032, 4033, 4040, 4043],
  12568. [4013, 4030, 4032, 4033, 4043],
  12569. [4003, 4023, 4040, 4042, 4043],
  12570. [4000, 4032, 4033, 4042, 4043],
  12571. [4001, 4032, 4033, 4041, 4043],
  12572. [4002, 4030, 4033, 4042, 4043],
  12573. [4002, 4032, 4033, 4040, 4043],
  12574. [4003, 4030, 4033, 4041, 4043],
  12575. [4003, 4031, 4033, 4040, 4043],
  12576. [4020, 4022, 4023, 4042, 4043],
  12577. [4013, 4030, 4031, 4033, 4043],
  12578. [4003, 4023, 4040, 4041, 4043],
  12579. [4000, 4031, 4033, 4042, 4043],
  12580. [4000, 4032, 4033, 4041, 4043],
  12581. [4001, 4030, 4033, 4042, 4043],
  12582. [4001, 4032, 4033, 4040, 4043],
  12583. [4002, 4030, 4033, 4041, 4043],
  12584. [4002, 4031, 4033, 4040, 4043],
  12585. [4003, 4030, 4033, 4040, 4043],
  12586. [4021, 4022, 4023, 4040, 4043],
  12587. [4020, 4022, 4023, 4041, 4043],
  12588. [4020, 4021, 4023, 4042, 4043],
  12589. [4023, 4030, 4031, 4032, 4033],
  12590. [4000, 4030, 4033, 4042, 4043],
  12591. [4000, 4031, 4033, 4041, 4043],
  12592. [4000, 4032, 4033, 4040, 4043],
  12593. [4001, 4030, 4033, 4041, 4043],
  12594. [4001, 4031, 4033, 4040, 4043],
  12595. [4002, 4030, 4033, 4040, 4043],
  12596. [4020, 4022, 4023, 4040, 4043],
  12597. [4020, 4021, 4023, 4041, 4043],
  12598. [4022, 4030, 4031, 4032, 4033],
  12599. [4000, 4030, 4033, 4041, 4043],
  12600. [4000, 4031, 4033, 4040, 4043],
  12601. [4001, 4030, 4033, 4040, 4043],
  12602. [4020, 4021, 4023, 4040, 4043],
  12603. [4021, 4030, 4031, 4032, 4033],
  12604. [4020, 4030, 4031, 4032, 4033],
  12605. [4003, 4031, 4032, 4033, 4043],
  12606. [4020, 4022, 4023, 4033, 4043],
  12607. [4003, 4030, 4032, 4033, 4043],
  12608. [4003, 4013, 4040, 4042, 4043],
  12609. [4020, 4021, 4023, 4033, 4043],
  12610. [4003, 4030, 4031, 4033, 4043],
  12611. [4003, 4013, 4040, 4041, 4043],
  12612. [4013, 4030, 4031, 4032, 4033],
  12613. [4012, 4030, 4031, 4032, 4033],
  12614. [4011, 4030, 4031, 4032, 4033],
  12615. [4010, 4030, 4031, 4032, 4033],
  12616. [4013, 4023, 4031, 4032, 4033],
  12617. [4013, 4023, 4030, 4032, 4033],
  12618. [4020, 4022, 4023, 4032, 4033],
  12619. [4013, 4023, 4030, 4031, 4033],
  12620. [4021, 4022, 4023, 4030, 4033],
  12621. [4020, 4022, 4023, 4031, 4033],
  12622. [4020, 4021, 4023, 4032, 4033],
  12623. [4020, 4021, 4022, 4023, 4043],
  12624. [4003, 4030, 4031, 4032, 4033],
  12625. [4020, 4022, 4023, 4030, 4033],
  12626. [4020, 4021, 4023, 4031, 4033],
  12627. [4020, 4021, 4022, 4023, 4042],
  12628. [4002, 4030, 4031, 4032, 4033],
  12629. [4020, 4021, 4023, 4030, 4033],
  12630. [4020, 4021, 4022, 4023, 4041],
  12631. [4001, 4030, 4031, 4032, 4033],
  12632. [4020, 4021, 4022, 4023, 4040],
  12633. [4000, 4030, 4031, 4032, 4033],
  12634. [4003, 4023, 4031, 4032, 4033],
  12635. [4013, 4020, 4022, 4023, 4043],
  12636. [4003, 4023, 4030, 4032, 4033],
  12637. [4010, 4012, 4013, 4042, 4043],
  12638. [4013, 4020, 4021, 4023, 4043],
  12639. [4003, 4023, 4030, 4031, 4033],
  12640. [4011, 4012, 4013, 4040, 4043],
  12641. [4010, 4012, 4013, 4041, 4043],
  12642. [4010, 4011, 4013, 4042, 4043],
  12643. [4020, 4021, 4022, 4023, 4033],
  12644. [4010, 4012, 4013, 4040, 4043],
  12645. [4010, 4011, 4013, 4041, 4043],
  12646. [4020, 4021, 4022, 4023, 4032],
  12647. [4010, 4011, 4013, 4040, 4043],
  12648. [4020, 4021, 4022, 4023, 4031],
  12649. [4020, 4021, 4022, 4023, 4030],
  12650. [4003, 4013, 4031, 4032, 4033],
  12651. [4010, 4012, 4013, 4033, 4043],
  12652. [4003, 4020, 4022, 4023, 4043],
  12653. [4013, 4020, 4022, 4023, 4033],
  12654. [4003, 4013, 4030, 4032, 4033],
  12655. [4010, 4011, 4013, 4033, 4043],
  12656. [4003, 4020, 4021, 4023, 4043],
  12657. [4013, 4020, 4021, 4023, 4033],
  12658. [4003, 4013, 4030, 4031, 4033],
  12659. [4010, 4012, 4013, 4023, 4043],
  12660. [4003, 4020, 4022, 4023, 4033],
  12661. [4010, 4012, 4013, 4032, 4033],
  12662. [4010, 4011, 4013, 4023, 4043],
  12663. [4003, 4020, 4021, 4023, 4033],
  12664. [4011, 4012, 4013, 4030, 4033],
  12665. [4010, 4012, 4013, 4031, 4033],
  12666. [4010, 4011, 4013, 4032, 4033],
  12667. [4013, 4020, 4021, 4022, 4023],
  12668. [4010, 4012, 4013, 4030, 4033],
  12669. [4010, 4011, 4013, 4031, 4033],
  12670. [4012, 4020, 4021, 4022, 4023],
  12671. [4010, 4011, 4013, 4030, 4033],
  12672. [4011, 4020, 4021, 4022, 4023],
  12673. [4010, 4020, 4021, 4022, 4023],
  12674. [4010, 4012, 4013, 4023, 4033],
  12675. [4000, 4002, 4003, 4042, 4043],
  12676. [4010, 4011, 4013, 4023, 4033],
  12677. [4001, 4002, 4003, 4040, 4043],
  12678. [4000, 4002, 4003, 4041, 4043],
  12679. [4000, 4001, 4003, 4042, 4043],
  12680. [4010, 4011, 4012, 4013, 4043],
  12681. [4003, 4020, 4021, 4022, 4023],
  12682. [4000, 4002, 4003, 4040, 4043],
  12683. [4000, 4001, 4003, 4041, 4043],
  12684. [4010, 4011, 4012, 4013, 4042],
  12685. [4002, 4020, 4021, 4022, 4023],
  12686. [4000, 4001, 4003, 4040, 4043],
  12687. [4010, 4011, 4012, 4013, 4041],
  12688. [4001, 4020, 4021, 4022, 4023],
  12689. [4010, 4011, 4012, 4013, 4040],
  12690. [4000, 4020, 4021, 4022, 4023],
  12691. [4001, 4002, 4003, 4033, 4043],
  12692. [4000, 4002, 4003, 4033, 4043],
  12693. [4003, 4010, 4012, 4013, 4043],
  12694. [4003, 4013, 4020, 4022, 4023],
  12695. [4000, 4001, 4003, 4033, 4043],
  12696. [4003, 4010, 4011, 4013, 4043],
  12697. [4003, 4013, 4020, 4021, 4023],
  12698. [4010, 4011, 4012, 4013, 4033],
  12699. [4010, 4011, 4012, 4013, 4032],
  12700. [4010, 4011, 4012, 4013, 4031],
  12701. [4010, 4011, 4012, 4013, 4030],
  12702. [4001, 4002, 4003, 4023, 4043],
  12703. [4000, 4002, 4003, 4023, 4043],
  12704. [4003, 4010, 4012, 4013, 4033],
  12705. [4000, 4002, 4003, 4032, 4033],
  12706. [4000, 4001, 4003, 4023, 4043],
  12707. [4003, 4010, 4011, 4013, 4033],
  12708. [4001, 4002, 4003, 4030, 4033],
  12709. [4000, 4002, 4003, 4031, 4033],
  12710. [4000, 4001, 4003, 4032, 4033],
  12711. [4010, 4011, 4012, 4013, 4023],
  12712. [4000, 4002, 4003, 4030, 4033],
  12713. [4000, 4001, 4003, 4031, 4033],
  12714. [4010, 4011, 4012, 4013, 4022],
  12715. [4000, 4001, 4003, 4030, 4033],
  12716. [4010, 4011, 4012, 4013, 4021],
  12717. [4010, 4011, 4012, 4013, 4020],
  12718. [4001, 4002, 4003, 4013, 4043],
  12719. [4001, 4002, 4003, 4023, 4033],
  12720. [4000, 4002, 4003, 4013, 4043],
  12721. [4000, 4002, 4003, 4023, 4033],
  12722. [4003, 4010, 4012, 4013, 4023],
  12723. [4000, 4001, 4003, 4013, 4043],
  12724. [4000, 4001, 4003, 4023, 4033],
  12725. [4003, 4010, 4011, 4013, 4023],
  12726. [4001, 4002, 4003, 4013, 4033],
  12727. [4000, 4002, 4003, 4013, 4033],
  12728. [4000, 4001, 4003, 4013, 4033],
  12729. [4000, 4001, 4002, 4003, 4043],
  12730. [4003, 4010, 4011, 4012, 4013],
  12731. [4000, 4001, 4002, 4003, 4042],
  12732. [4002, 4010, 4011, 4012, 4013],
  12733. [4000, 4001, 4002, 4003, 4041],
  12734. [4001, 4010, 4011, 4012, 4013],
  12735. [4000, 4001, 4002, 4003, 4040],
  12736. [4000, 4010, 4011, 4012, 4013],
  12737. [4001, 4002, 4003, 4013, 4023],
  12738. [4000, 4002, 4003, 4013, 4023],
  12739. [4000, 4001, 4003, 4013, 4023],
  12740. [4000, 4001, 4002, 4003, 4033],
  12741. [4000, 4001, 4002, 4003, 4032],
  12742. [4000, 4001, 4002, 4003, 4031],
  12743. [4000, 4001, 4002, 4003, 4030],
  12744. [4000, 4001, 4002, 4003, 4023],
  12745. [4000, 4001, 4002, 4003, 4022],
  12746. [4000, 4001, 4002, 4003, 4021],
  12747. [4000, 4001, 4002, 4003, 4020],
  12748. [4000, 4001, 4002, 4003, 4013],
  12749. [4000, 4001, 4002, 4003, 4012],
  12750. [4000, 4001, 4002, 4003, 4011],
  12751. [4000, 4001, 4002, 4003, 4010],
  12752. ].filter((p) => p.includes(this.mandatoryId));
  12753.  
  12754. const bestPack = {
  12755. pack: packs[0],
  12756. winRate: 0,
  12757. countBattle: 0,
  12758. id: 0,
  12759. };
  12760.  
  12761. for (const id in packs) {
  12762. const pack = packs[id];
  12763. const attackers = this.maxUpgrade.filter((e) => pack.includes(e.id)).reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  12764. const battle = {
  12765. attackers,
  12766. defenders: [enemieHeroes],
  12767. type: 'brawl_titan',
  12768. };
  12769. const isRandom = this.isRandomBattle(battle);
  12770. const stat = {
  12771. count: 0,
  12772. win: 0,
  12773. winRate: 0,
  12774. };
  12775. for (let i = 1; i <= 20; i++) {
  12776. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12777. const result = await Calc(battle);
  12778. stat.win += result.result.win;
  12779. stat.count += 1;
  12780. stat.winRate = stat.win / stat.count;
  12781. if (!isRandom || (i >= 2 && stat.winRate < 0.65) || (i >= 10 && stat.winRate == 1)) {
  12782. break;
  12783. }
  12784. }
  12785.  
  12786. if (!isRandom && stat.win) {
  12787. return {
  12788. favor: {},
  12789. heroes: pack,
  12790. };
  12791. }
  12792. if (stat.winRate > 0.85) {
  12793. return {
  12794. favor: {},
  12795. heroes: pack,
  12796. };
  12797. }
  12798. if (stat.winRate > bestPack.winRate) {
  12799. bestPack.countBattle = stat.count;
  12800. bestPack.winRate = stat.winRate;
  12801. bestPack.pack = pack;
  12802. bestPack.id = id;
  12803. }
  12804. }
  12805.  
  12806. //console.log(bestPack.id, bestPack.pack, bestPack.winRate, bestPack.countBattle);
  12807. return {
  12808. favor: {},
  12809. heroes: bestPack.pack,
  12810. };
  12811. }
  12812.  
  12813. isRandomPack(pack) {
  12814. const ids = Object.keys(pack);
  12815. return ids.includes('4023') || ids.includes('4021');
  12816. }
  12817.  
  12818. isRandomBattle(battle) {
  12819. return this.isRandomPack(battle.attackers) || this.isRandomPack(battle.defenders[0]);
  12820. }
  12821.  
  12822. async updateHeroesPack(enemieHeroes) {
  12823. 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}}}];
  12824.  
  12825. const bestPack = {
  12826. pack: packs[0],
  12827. countWin: 0,
  12828. }
  12829.  
  12830. for (const pack of packs) {
  12831. const attackers = pack.attackers;
  12832. const battle = {
  12833. attackers,
  12834. defenders: [enemieHeroes],
  12835. type: 'brawl',
  12836. };
  12837.  
  12838. let countWinBattles = 0;
  12839. let countTestBattle = 10;
  12840. for (let i = 0; i < countTestBattle; i++) {
  12841. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12842. const result = await Calc(battle);
  12843. if (result.result.win) {
  12844. countWinBattles++;
  12845. }
  12846. if (countWinBattles > 7) {
  12847. console.log(pack)
  12848. return pack.args;
  12849. }
  12850. }
  12851. if (countWinBattles > bestPack.countWin) {
  12852. bestPack.countWin = countWinBattles;
  12853. bestPack.pack = pack.args;
  12854. }
  12855. }
  12856.  
  12857. console.log(bestPack);
  12858. return bestPack.pack;
  12859. }
  12860.  
  12861. async questFarm() {
  12862. const calls = [this.callBrawlQuestFarm];
  12863. const result = await Send(JSON.stringify({ calls }));
  12864. return result.results[0].result.response;
  12865. }
  12866.  
  12867. async getBrawlInfo() {
  12868. const data = await Send(JSON.stringify({
  12869. calls: [
  12870. this.callUserGetInfo,
  12871. this.callBrawlQuestGetInfo,
  12872. this.callBrawlFindEnemies,
  12873. this.callTeamGetMaxUpgrade,
  12874. this.callBrawlGetInfo,
  12875. ]
  12876. }));
  12877.  
  12878. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  12879.  
  12880. const maxUpgrade = data.results[3].result.response;
  12881. const maxHero = Object.values(maxUpgrade.hero);
  12882. const maxTitan = Object.values(maxUpgrade.titan);
  12883. const maxPet = Object.values(maxUpgrade.pet);
  12884. this.maxUpgrade = [...maxHero, ...maxPet, ...maxTitan];
  12885.  
  12886. this.info = data.results[4].result.response;
  12887. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  12888. return {
  12889. attempts: attempts.amount,
  12890. questInfo: data.results[1].result.response,
  12891. findEnemies: data.results[2].result.response,
  12892. }
  12893. }
  12894.  
  12895. /**
  12896. * Carrying out a fight
  12897. *
  12898. * Проведение боя
  12899. */
  12900. async battle(userId) {
  12901. this.stats.count++;
  12902. const battle = await this.startBattle(userId, this.args);
  12903. const result = await Calc(battle);
  12904. console.log(result.result);
  12905. if (result.result.win) {
  12906. this.stats.win++;
  12907. } else {
  12908. this.stats.loss++;
  12909. if (!this.info.boughtEndlessLivesToday) {
  12910. this.attempts--;
  12911. }
  12912. }
  12913. return await this.endBattle(result);
  12914. // return await this.cancelBattle(result);
  12915. }
  12916.  
  12917. /**
  12918. * Starts a fight
  12919. *
  12920. * Начинает бой
  12921. */
  12922. async startBattle(userId, args) {
  12923. const call = {
  12924. name: "brawl_startBattle",
  12925. args,
  12926. ident: "brawl_startBattle"
  12927. }
  12928. call.args.userId = userId;
  12929. const calls = [call];
  12930. const result = await Send(JSON.stringify({ calls }));
  12931. return result.results[0].result.response;
  12932. }
  12933.  
  12934. cancelBattle(battle) {
  12935. const fixBattle = function (heroes) {
  12936. for (const ids in heroes) {
  12937. const hero = heroes[ids];
  12938. hero.energy = random(1, 999);
  12939. if (hero.hp > 0) {
  12940. hero.hp = random(1, hero.hp);
  12941. }
  12942. }
  12943. }
  12944. fixBattle(battle.progress[0].attackers.heroes);
  12945. fixBattle(battle.progress[0].defenders.heroes);
  12946. return this.endBattle(battle);
  12947. }
  12948.  
  12949. /**
  12950. * Ends the fight
  12951. *
  12952. * Заканчивает бой
  12953. */
  12954. async endBattle(battle) {
  12955. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  12956. const calls = [{
  12957. name: "brawl_endBattle",
  12958. args: {
  12959. result: battle.result,
  12960. progress: battle.progress
  12961. },
  12962. ident: "brawl_endBattle"
  12963. },
  12964. this.callBrawlQuestGetInfo,
  12965. this.callBrawlFindEnemies,
  12966. ];
  12967. const result = await Send(JSON.stringify({ calls }));
  12968. return result.results;
  12969. }
  12970.  
  12971. end(endReason) {
  12972. setIsCancalBattle(true);
  12973. isBrawlsAutoStart = false;
  12974. setProgress(endReason, true);
  12975. console.log(endReason);
  12976. this.resolve();
  12977. }
  12978. }
  12979.  
  12980. this.HWHClasses.executeBrawls = executeBrawls;
  12981.  
  12982. })();
  12983.  
  12984. /**
  12985. * TODO:
  12986. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  12987. * Добивание на арене титанов
  12988. * Закрытие окошек по Esc +-
  12989. * Починить работу скрипта на уровне команды ниже 10 +-
  12990. * Написать номальную синхронизацию
  12991. * Запрет сбора квестов и отправки экспеиций в промежуток между локальным обновлением и глобальным обновлением дня
  12992. * Улучшение боев
  12993. */