Greasy Fork is available in English.

HeroWarsHelper

Automation of actions for the game Hero Wars

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @name:ru HeroWarsHelper
  5. // @namespace HeroWarsHelper
  6. // @version 2.330
  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: false,
  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. rewardsAndMailFarm: {
  1466. name: I18N('REWARDS_AND_MAIL'),
  1467. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1468. onClick: function () {
  1469. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1470. },
  1471. },
  1472. goToClanWar: {
  1473. name: I18N('GUILD_WAR'),
  1474. title: I18N('GUILD_WAR_TITLE'),
  1475. onClick: cheats.goClanWar,
  1476. dot: true,
  1477. },
  1478. dailyQuests: {
  1479. name: I18N('DAILY_QUESTS'),
  1480. title: I18N('DAILY_QUESTS_TITLE'),
  1481. onClick: async function () {
  1482. const quests = new dailyQuests(
  1483. () => {},
  1484. () => {}
  1485. );
  1486. await quests.autoInit();
  1487. quests.start();
  1488. },
  1489. },
  1490. newDay: {
  1491. name: I18N('SYNC'),
  1492. title: I18N('SYNC_TITLE'),
  1493. onClick: function () {
  1494. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1495. },
  1496. },
  1497. // Архидемон
  1498. bossRatingEventDemon: {
  1499. name: I18N('ARCHDEMON'),
  1500. title: I18N('ARCHDEMON_TITLE'),
  1501. onClick: function () {
  1502. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1503. },
  1504. hide: false,
  1505. color: 'red',
  1506. },
  1507. // Горнило душ
  1508. bossRatingEventSouls: {
  1509. name: I18N('FURNACE_OF_SOULS'),
  1510. title: I18N('ARCHDEMON_TITLE'),
  1511. onClick: function () {
  1512. confShow(`${I18N('RUN_SCRIPT')} ${I18N('FURNACE_OF_SOULS')}?`, bossRatingEventSouls);
  1513. },
  1514. hide: true,
  1515. color: 'red',
  1516. },
  1517. };
  1518. /**
  1519. * Display buttons
  1520. *
  1521. * Вывести кнопочки
  1522. */
  1523. function addControlButtons() {
  1524. for (let name in buttons) {
  1525. button = buttons[name];
  1526. if (button.hide) {
  1527. continue;
  1528. }
  1529. if (button.isCombine) {
  1530. button['button'] = scriptMenu.addCombinedButton(button.combineList);
  1531. continue;
  1532. }
  1533. button['button'] = scriptMenu.addButton(button);
  1534. }
  1535. }
  1536. /**
  1537. * Adds links
  1538. *
  1539. * Добавляет ссылки
  1540. */
  1541. function addBottomUrls() {
  1542. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1543. }
  1544. /**
  1545. * Stop repetition of the mission
  1546. *
  1547. * Остановить повтор миссии
  1548. */
  1549. let isStopSendMission = false;
  1550. /**
  1551. * There is a repetition of the mission
  1552. *
  1553. * Идет повтор миссии
  1554. */
  1555. let isSendsMission = false;
  1556. /**
  1557. * Data on the past mission
  1558. *
  1559. * Данные о прошедшей мисии
  1560. */
  1561. let lastMissionStart = {}
  1562. /**
  1563. * Start time of the last battle in the company
  1564. *
  1565. * Время начала последнего боя в кампании
  1566. */
  1567. let lastMissionBattleStart = 0;
  1568. /**
  1569. * Data for calculating the last battle with the boss
  1570. *
  1571. * Данные для расчете последнего боя с боссом
  1572. */
  1573. let lastBossBattle = null;
  1574. /**
  1575. * Information about the last battle
  1576. *
  1577. * Данные о прошедшей битве
  1578. */
  1579. let lastBattleArg = {}
  1580. let lastBossBattleStart = null;
  1581. this.addBattleTimer = 4;
  1582. this.invasionTimer = 2500;
  1583. const invasionInfo = {
  1584. id: 225,
  1585. buff: 0,
  1586. bossLvl: 130,
  1587. };
  1588. const invasionDataPacks = {
  1589. 130: { buff: 0, pet: 6005, heroes: [9, 62, 10, 1, 66], favor: { 9: 6006 } },
  1590. 140: { buff: 0, pet: 6005, heroes: [9, 62, 10, 1, 66], favor: {} },
  1591. 150: { buff: 0, pet: 6005, heroes: [9, 62, 10, 1, 66], favor: {} },
  1592. 160: { buff: 0, pet: 6005, heroes: [64, 66, 13, 9, 4], favor: { 4: 6006, 9: 6004, 13: 6003, 64: 6005, 66: 6002 } },
  1593. 170: { buff: 0, pet: 6005, heroes: [9, 62, 10, 1, 66], favor: { 1: 6006, 9: 6005, 10: 6008, 62: 6003, 66: 6002 } },
  1594. 180: { buff: 0, pet: 6006, heroes: [62, 10, 2, 4, 66], favor: { 2: 6005, 4: 6001, 10: 6006, 62: 6003 } },
  1595. 190: { buff: 40, pet: 6005, heroes: [9, 2, 43, 45, 66], favor: { 9: 6005, 45: 6002, 66: 6006 } },
  1596. 200: { buff: 20, pet: 6005, heroes: [9, 62, 1, 48, 66], favor: { 9: 6007, 62: 6003 } },
  1597. 210: { buff: 10, pet: 6008, heroes: [9, 10, 4, 32, 66], favor: { 9: 6005, 10: 6003, 32: 6007, 66: 6006 } },
  1598. 220: { buff: 20, pet: 6004, heroes: [9, 1, 48, 43, 66], favor: { 9: 6005, 43: 6006, 48: 6000, 66: 6002 } },
  1599. 230: { buff: 45, pet: 6001, heroes: [9, 7, 40, 43, 66], favor: { 7: 6006, 9: 6005, 40: 6004, 43: 6006, 66: 6006 } },
  1600. 240: { buff: 50, pet: 6009, heroes: [9, 40, 43, 51, 66], favor: { 9: 6005, 40: 6004, 43: 6002, 66: 6007 } },
  1601. 250: { buff: 70, pet: 6005, heroes: [9, 10, 13, 43, 66], favor: { 9: 6005, 10: 6002, 13: 6002, 43: 6006, 66: 6006 } },
  1602. 260: { buff: 80, pet: 6008, heroes: [9, 40, 43, 4, 66], favor: { 4: 6001, 9: 6006, 43: 6006 } },
  1603. 270: { buff: 115, pet: 6001, heroes: [9, 13, 43, 51, 66], favor: { 9: 6006, 43: 6006, 51: 6001 } },
  1604. 280: { buff: 80, pet: 6008, heroes: [9, 13, 43, 56, 66], favor: { 9: 6004, 13: 6006, 43: 6006, 66: 6006 } },
  1605. 290: { buff: 60, pet: 6005, heroes: [9, 10, 43, 56, 66], favor: { 9: 6005, 10: 6002, 43: 6006 } },
  1606. 300: { buff: 75, pet: 6006, heroes: [9, 62, 1, 45, 66], favor: { 1: 6006, 9: 6005, 45: 6002, 66: 6007 } },
  1607. };
  1608. /**
  1609. * The name of the function of the beginning of the battle
  1610. *
  1611. * Имя функции начала боя
  1612. */
  1613. let nameFuncStartBattle = '';
  1614. /**
  1615. * The name of the function of the end of the battle
  1616. *
  1617. * Имя функции конца боя
  1618. */
  1619. let nameFuncEndBattle = '';
  1620. /**
  1621. * Data for calculating the last battle
  1622. *
  1623. * Данные для расчета последнего боя
  1624. */
  1625. let lastBattleInfo = null;
  1626. /**
  1627. * The ability to cancel the battle
  1628. *
  1629. * Возможность отменить бой
  1630. */
  1631. let isCancalBattle = true;
  1632.  
  1633. function setIsCancalBattle(value) {
  1634. isCancalBattle = value;
  1635. }
  1636.  
  1637. /**
  1638. * Certificator of the last open nesting doll
  1639. *
  1640. * Идетификатор последней открытой матрешки
  1641. */
  1642. let lastRussianDollId = null;
  1643. /**
  1644. * Cancel the training guide
  1645. *
  1646. * Отменить обучающее руководство
  1647. */
  1648. this.isCanceledTutorial = false;
  1649.  
  1650. /**
  1651. * Data from the last question of the quiz
  1652. *
  1653. * Данные последнего вопроса викторины
  1654. */
  1655. let lastQuestion = null;
  1656. /**
  1657. * Answer to the last question of the quiz
  1658. *
  1659. * Ответ на последний вопрос викторины
  1660. */
  1661. let lastAnswer = null;
  1662. /**
  1663. * Flag for opening keys or titan artifact spheres
  1664. *
  1665. * Флаг открытия ключей или сфер артефактов титанов
  1666. */
  1667. let artifactChestOpen = false;
  1668. /**
  1669. * The name of the function to open keys or orbs of titan artifacts
  1670. *
  1671. * Имя функции открытия ключей или сфер артефактов титанов
  1672. */
  1673. let artifactChestOpenCallName = '';
  1674. let correctShowOpenArtifact = 0;
  1675. /**
  1676. * Data for the last battle in the dungeon
  1677. * (Fix endless cards)
  1678. *
  1679. * Данные для последнего боя в подземке
  1680. * (Исправление бесконечных карт)
  1681. */
  1682. let lastDungeonBattleData = null;
  1683. /**
  1684. * Start time of the last battle in the dungeon
  1685. *
  1686. * Время начала последнего боя в подземелье
  1687. */
  1688. let lastDungeonBattleStart = 0;
  1689. /**
  1690. * Subscription end time
  1691. *
  1692. * Время окончания подписки
  1693. */
  1694. let subEndTime = 0;
  1695. /**
  1696. * Number of prediction cards
  1697. *
  1698. * Количество карт предсказаний
  1699. */
  1700. let countPredictionCard = 0;
  1701.  
  1702. /**
  1703. * Brawl pack
  1704. *
  1705. * Пачка для потасовок
  1706. */
  1707. let brawlsPack = null;
  1708. /**
  1709. * Autobrawl started
  1710. *
  1711. * Автопотасовка запущена
  1712. */
  1713. let isBrawlsAutoStart = false;
  1714. let clanDominationGetInfo = null;
  1715. /**
  1716. * Copies the text to the clipboard
  1717. *
  1718. * Копирует тест в буфер обмена
  1719. * @param {*} text copied text // копируемый текст
  1720. */
  1721. function copyText(text) {
  1722. let copyTextarea = document.createElement("textarea");
  1723. copyTextarea.style.opacity = "0";
  1724. copyTextarea.textContent = text;
  1725. document.body.appendChild(copyTextarea);
  1726. copyTextarea.select();
  1727. document.execCommand("copy");
  1728. document.body.removeChild(copyTextarea);
  1729. delete copyTextarea;
  1730. }
  1731. /**
  1732. * Returns the history of requests
  1733. *
  1734. * Возвращает историю запросов
  1735. */
  1736. this.getRequestHistory = function() {
  1737. return requestHistory;
  1738. }
  1739. /**
  1740. * Generates a random integer from min to max
  1741. *
  1742. * Гененирует случайное целое число от min до max
  1743. */
  1744. const random = function (min, max) {
  1745. return Math.floor(Math.random() * (max - min + 1) + min);
  1746. }
  1747. const randf = function (min, max) {
  1748. return Math.random() * (max - min + 1) + min;
  1749. };
  1750. /**
  1751. * Clearing the request history
  1752. *
  1753. * Очистка истоии запросов
  1754. */
  1755. setInterval(function () {
  1756. let now = Date.now();
  1757. for (let i in requestHistory) {
  1758. const time = +i.split('_')[0];
  1759. if (now - time > 300000) {
  1760. delete requestHistory[i];
  1761. }
  1762. }
  1763. }, 300000);
  1764. /**
  1765. * Displays the dialog box
  1766. *
  1767. * Отображает диалоговое окно
  1768. */
  1769. function confShow(message, yesCallback, noCallback) {
  1770. let buts = [];
  1771. message = message || I18N('DO_YOU_WANT');
  1772. noCallback = noCallback || (() => {});
  1773. if (yesCallback) {
  1774. buts = [
  1775. { msg: I18N('BTN_RUN'), result: true},
  1776. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true},
  1777. ]
  1778. } else {
  1779. yesCallback = () => {};
  1780. buts = [
  1781. { msg: I18N('BTN_OK'), result: true},
  1782. ];
  1783. }
  1784. popup.confirm(message, buts).then((e) => {
  1785. // dialogPromice = null;
  1786. if (e) {
  1787. yesCallback();
  1788. } else {
  1789. noCallback();
  1790. }
  1791. });
  1792. }
  1793. /**
  1794. * Override/proxy the method for creating a WS package send
  1795. *
  1796. * Переопределяем/проксируем метод создания отправки WS пакета
  1797. */
  1798. WebSocket.prototype.send = function (data) {
  1799. if (!this.isSetOnMessage) {
  1800. const oldOnmessage = this.onmessage;
  1801. this.onmessage = function (event) {
  1802. try {
  1803. const data = JSON.parse(event.data);
  1804. if (!this.isWebSocketLogin && data.result.type == "iframeEvent.login") {
  1805. this.isWebSocketLogin = true;
  1806. } else if (data.result.type == "iframeEvent.login") {
  1807. return;
  1808. }
  1809. } catch (e) { }
  1810. return oldOnmessage.apply(this, arguments);
  1811. }
  1812. this.isSetOnMessage = true;
  1813. }
  1814. original.SendWebSocket.call(this, data);
  1815. }
  1816. /**
  1817. * Overriding/Proxying the Ajax Request Creation Method
  1818. *
  1819. * Переопределяем/проксируем метод создания Ajax запроса
  1820. */
  1821. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1822. this.uniqid = Date.now() + '_' + random(1000000, 10000000);
  1823. this.errorRequest = false;
  1824. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1825. if (!apiUrl) {
  1826. apiUrl = url;
  1827. const socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1828. console.log(socialInfo);
  1829. }
  1830. requestHistory[this.uniqid] = {
  1831. method,
  1832. url,
  1833. error: [],
  1834. headers: {},
  1835. request: null,
  1836. response: null,
  1837. signature: [],
  1838. calls: {},
  1839. };
  1840. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1841. this.errorRequest = true;
  1842. }
  1843. return original.open.call(this, method, url, async, user, password);
  1844. };
  1845. /**
  1846. * Overriding/Proxying the header setting method for the AJAX request
  1847. *
  1848. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1849. */
  1850. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1851. if (this.uniqid in requestHistory) {
  1852. requestHistory[this.uniqid].headers[name] = value;
  1853. } else {
  1854. check = true;
  1855. }
  1856.  
  1857. if (name == 'X-Auth-Signature') {
  1858. requestHistory[this.uniqid].signature.push(value);
  1859. if (!check) {
  1860. return;
  1861. }
  1862. }
  1863.  
  1864. return original.setRequestHeader.call(this, name, value);
  1865. };
  1866. /**
  1867. * Overriding/Proxying the AJAX Request Sending Method
  1868. *
  1869. * Переопределяем/проксируем метод отправки AJAX запроса
  1870. */
  1871. XMLHttpRequest.prototype.send = async function (sourceData) {
  1872. if (this.uniqid in requestHistory) {
  1873. let tempData = null;
  1874. if (getClass(sourceData) == "ArrayBuffer") {
  1875. tempData = decoder.decode(sourceData);
  1876. } else {
  1877. tempData = sourceData;
  1878. }
  1879. requestHistory[this.uniqid].request = tempData;
  1880. let headers = requestHistory[this.uniqid].headers;
  1881. lastHeaders = Object.assign({}, headers);
  1882. /**
  1883. * Game loading event
  1884. *
  1885. * Событие загрузки игры
  1886. */
  1887. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1888. isLoadGame = true;
  1889. if (cheats.libGame) {
  1890. lib.setData(cheats.libGame);
  1891. } else {
  1892. lib.setData(await cheats.LibLoad());
  1893. }
  1894. addControls();
  1895. addControlButtons();
  1896. addBottomUrls();
  1897.  
  1898. if (isChecked('sendExpedition')) {
  1899. const isTimeBetweenDays = isTimeBetweenNewDays();
  1900. if (!isTimeBetweenDays) {
  1901. checkExpedition();
  1902. } else {
  1903. setProgress(I18N('EXPEDITIONS_NOTTIME'), true);
  1904. }
  1905. }
  1906.  
  1907. getAutoGifts();
  1908.  
  1909. cheats.activateHacks();
  1910. justInfo();
  1911. if (isChecked('dailyQuests')) {
  1912. testDailyQuests();
  1913. }
  1914.  
  1915. if (isChecked('buyForGold')) {
  1916. buyInStoreForGold();
  1917. }
  1918. }
  1919. /**
  1920. * Outgoing request data processing
  1921. *
  1922. * Обработка данных исходящего запроса
  1923. */
  1924. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1925. /**
  1926. * Handling incoming request data
  1927. *
  1928. * Обработка данных входящего запроса
  1929. */
  1930. const oldReady = this.onreadystatechange;
  1931. this.onreadystatechange = async function (e) {
  1932. if (this.errorRequest) {
  1933. return oldReady.apply(this, arguments);
  1934. }
  1935. if(this.readyState == 4 && this.status == 200) {
  1936. isTextResponse = this.responseType === "text" || this.responseType === "";
  1937. let response = isTextResponse ? this.responseText : this.response;
  1938. requestHistory[this.uniqid].response = response;
  1939. /**
  1940. * Replacing incoming request data
  1941. *
  1942. * Заменна данных входящего запроса
  1943. */
  1944. if (isTextResponse) {
  1945. await checkChangeResponse.call(this, response);
  1946. }
  1947. /**
  1948. * A function to run after the request is executed
  1949. *
  1950. * Функция запускаемая после выполения запроса
  1951. */
  1952. if (typeof this.onReadySuccess == 'function') {
  1953. setTimeout(this.onReadySuccess, 500);
  1954. }
  1955. /** Удаляем из истории запросов битвы с боссом */
  1956. if ('invasion_bossStart' in requestHistory[this.uniqid].calls) delete requestHistory[this.uniqid];
  1957. }
  1958. if (oldReady) {
  1959. try {
  1960. return oldReady.apply(this, arguments);
  1961. } catch(e) {
  1962. console.log(oldReady);
  1963. console.error('Error in oldReady:', e);
  1964. }
  1965.  
  1966. }
  1967. }
  1968. }
  1969. if (this.errorRequest) {
  1970. const oldReady = this.onreadystatechange;
  1971. this.onreadystatechange = function () {
  1972. Object.defineProperty(this, 'status', {
  1973. writable: true
  1974. });
  1975. this.status = 200;
  1976. Object.defineProperty(this, 'readyState', {
  1977. writable: true
  1978. });
  1979. this.readyState = 4;
  1980. Object.defineProperty(this, 'responseText', {
  1981. writable: true
  1982. });
  1983. this.responseText = JSON.stringify({
  1984. "result": true
  1985. });
  1986. if (typeof this.onReadySuccess == 'function') {
  1987. setTimeout(this.onReadySuccess, 200);
  1988. }
  1989. return oldReady.apply(this, arguments);
  1990. }
  1991. this.onreadystatechange();
  1992. } else {
  1993. try {
  1994. return original.send.call(this, sourceData);
  1995. } catch(e) {
  1996. debugger;
  1997. }
  1998. }
  1999. };
  2000. /**
  2001. * Processing and substitution of outgoing data
  2002. *
  2003. * Обработка и подмена исходящих данных
  2004. */
  2005. async function checkChangeSend(sourceData, tempData) {
  2006. try {
  2007. /**
  2008. * A function that replaces battle data with incorrect ones to cancel combatя
  2009. *
  2010. * Функция заменяющая данные боя на неверные для отмены боя
  2011. */
  2012. const fixBattle = function (heroes) {
  2013. for (const ids in heroes) {
  2014. hero = heroes[ids];
  2015. hero.energy = random(1, 999);
  2016. if (hero.hp > 0) {
  2017. hero.hp = random(1, hero.hp);
  2018. }
  2019. }
  2020. }
  2021. /**
  2022. * Dialog window 2
  2023. *
  2024. * Диалоговое окно 2
  2025. */
  2026. const showMsg = async function (msg, ansF, ansS) {
  2027. if (typeof popup == 'object') {
  2028. return await popup.confirm(msg, [
  2029. {msg: ansF, result: false},
  2030. {msg: ansS, result: true},
  2031. ]);
  2032. } else {
  2033. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  2034. }
  2035. }
  2036. /**
  2037. * Dialog window 3
  2038. *
  2039. * Диалоговое окно 3
  2040. */
  2041. const showMsgs = async function (msg, ansF, ansS, ansT) {
  2042. return await popup.confirm(msg, [
  2043. {msg: ansF, result: 0},
  2044. {msg: ansS, result: 1},
  2045. {msg: ansT, result: 2},
  2046. ]);
  2047. }
  2048.  
  2049. let changeRequest = false;
  2050. testData = JSON.parse(tempData);
  2051. for (const call of testData.calls) {
  2052. if (!artifactChestOpen) {
  2053. requestHistory[this.uniqid].calls[call.name] = call.ident;
  2054. }
  2055. /**
  2056. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  2057. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  2058. */
  2059. if ((call.name == 'adventure_endBattle' ||
  2060. call.name == 'adventureSolo_endBattle' ||
  2061. call.name == 'clanWarEndBattle' &&
  2062. isChecked('cancelBattle') ||
  2063. call.name == 'crossClanWar_endBattle' &&
  2064. isChecked('cancelBattle') ||
  2065. call.name == 'brawl_endBattle' ||
  2066. call.name == 'towerEndBattle' ||
  2067. call.name == 'invasion_bossEnd' ||
  2068. call.name == 'titanArenaEndBattle' ||
  2069. call.name == 'bossEndBattle' ||
  2070. call.name == 'clanRaid_endNodeBattle') &&
  2071. isCancalBattle) {
  2072. nameFuncEndBattle = call.name;
  2073.  
  2074. if (isChecked('tryFixIt_v2') &&
  2075. !call.args.result.win &&
  2076. (call.name == 'brawl_endBattle' ||
  2077. //call.name == 'crossClanWar_endBattle' ||
  2078. call.name == 'epicBrawl_endBattle' ||
  2079. //call.name == 'clanWarEndBattle' ||
  2080. call.name == 'adventure_endBattle' ||
  2081. call.name == 'titanArenaEndBattle' ||
  2082. call.name == 'bossEndBattle' ||
  2083. call.name == 'adventureSolo_endBattle') &&
  2084. lastBattleInfo) {
  2085. const noFixWin = call.name == 'clanWarEndBattle' || call.name == 'crossClanWar_endBattle';
  2086. const cloneBattle = structuredClone(lastBattleInfo);
  2087. lastBattleInfo = null;
  2088. try {
  2089. const { BestOrWinFixBattle } = HWHClasses;
  2090. const bFix = new BestOrWinFixBattle(cloneBattle);
  2091. bFix.setNoMakeWin(noFixWin);
  2092. let endTime = Date.now() + 3e4;
  2093. if (endTime < cloneBattle.endTime) {
  2094. endTime = cloneBattle.endTime;
  2095. }
  2096. const result = await bFix.start(cloneBattle.endTime, 150);
  2097.  
  2098. if (result.result.win) {
  2099. call.args.result = result.result;
  2100. call.args.progress = result.progress;
  2101. changeRequest = true;
  2102. } else if (result.value) {
  2103. if (
  2104. await popup.confirm(I18N('DEFEAT') + '<br>' + I18N('BEST_RESULT', { value: result.value }), [
  2105. { msg: I18N('BTN_CANCEL'), result: 0 },
  2106. { msg: I18N('BTN_ACCEPT'), result: 1 },
  2107. ])
  2108. ) {
  2109. call.args.result = result.result;
  2110. call.args.progress = result.progress;
  2111. changeRequest = true;
  2112. }
  2113. }
  2114. } catch (error) {
  2115. console.error(error);
  2116. }
  2117. }
  2118.  
  2119. if (!call.args.result.win) {
  2120. let resultPopup = false;
  2121. if (call.name == 'adventure_endBattle' ||
  2122. //call.name == 'invasion_bossEnd' ||
  2123. call.name == 'bossEndBattle' ||
  2124. call.name == 'adventureSolo_endBattle') {
  2125. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2126. } else if (call.name == 'clanWarEndBattle' ||
  2127. call.name == 'crossClanWar_endBattle') {
  2128. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  2129. } else if (call.name !== 'epicBrawl_endBattle' && call.name !== 'titanArenaEndBattle') {
  2130. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  2131. }
  2132. if (resultPopup) {
  2133. if (call.name == 'invasion_bossEnd') {
  2134. this.errorRequest = true;
  2135. }
  2136. fixBattle(call.args.progress[0].attackers.heroes);
  2137. fixBattle(call.args.progress[0].defenders.heroes);
  2138. changeRequest = true;
  2139. if (resultPopup > 1) {
  2140. this.onReadySuccess = testAutoBattle;
  2141. // setTimeout(bossBattle, 1000);
  2142. }
  2143. }
  2144. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  2145. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2146. if (resultPopup) {
  2147. fixBattle(call.args.progress[0].attackers.heroes);
  2148. fixBattle(call.args.progress[0].defenders.heroes);
  2149. changeRequest = true;
  2150. if (resultPopup > 1) {
  2151. this.onReadySuccess = testAutoBattle;
  2152. }
  2153. }
  2154. }
  2155. // Потасовки
  2156. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {}
  2157. }
  2158. /**
  2159. * Save pack for Brawls
  2160. *
  2161. * Сохраняем пачку для потасовок
  2162. */
  2163. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_startBattle') {
  2164. console.log(JSON.stringify(call.args));
  2165. brawlsPack = call.args;
  2166. if (
  2167. await popup.confirm(
  2168. I18N('START_AUTO_BRAWLS'),
  2169. [
  2170. { msg: I18N('BTN_NO'), result: false },
  2171. { msg: I18N('BTN_YES'), result: true },
  2172. ],
  2173. [
  2174. {
  2175. name: 'isAuto',
  2176. label: I18N('BRAWL_AUTO_PACK'),
  2177. checked: false,
  2178. },
  2179. ]
  2180. )
  2181. ) {
  2182. isBrawlsAutoStart = true;
  2183. const isAuto = popup.getCheckBoxes().find((e) => e.name === 'isAuto');
  2184. this.errorRequest = true;
  2185. testBrawls(isAuto.checked);
  2186. }
  2187. }
  2188. /**
  2189. * Canceled fight in Asgard
  2190. * Отмена боя в Асгарде
  2191. */
  2192. if (call.name == 'clanRaid_endBossBattle' && isChecked('cancelBattle')) {
  2193. const bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  2194. let maxDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  2195. const lastDamage = maxDamage;
  2196.  
  2197. const testFunc = [];
  2198.  
  2199. if (testFuntions.masterFix) {
  2200. testFunc.push({ msg: 'masterFix', isInput: true, default: 100 });
  2201. }
  2202.  
  2203. const resultPopup = await popup.confirm(
  2204. `${I18N('MSG_YOU_APPLIED')} ${lastDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  2205. [
  2206. { msg: I18N('BTN_OK'), result: false },
  2207. { msg: I18N('BTN_AUTO_F5'), result: 1 },
  2208. { msg: I18N('BTN_TRY_FIX_IT'), result: 2 },
  2209. ...testFunc,
  2210. ],
  2211. [
  2212. {
  2213. name: 'isStat',
  2214. label: I18N('CALC_STAT'),
  2215. checked: false,
  2216. },
  2217. ]
  2218. );
  2219. if (resultPopup) {
  2220. if (resultPopup == 2) {
  2221. setProgress(I18N('LETS_FIX'), false);
  2222. await new Promise((e) => setTimeout(e, 0));
  2223. const cloneBattle = structuredClone(lastBossBattle);
  2224. const endTime = cloneBattle.endTime - 1e4;
  2225. console.log('fixBossBattleStart');
  2226.  
  2227. const { BossFixBattle } = HWHClasses;
  2228. const bFix = new BossFixBattle(cloneBattle);
  2229. const result = await bFix.start(endTime, 300);
  2230. console.log(result);
  2231.  
  2232. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2233. lastDamage: lastDamage.toLocaleString()
  2234. });
  2235. if (result.value > lastDamage) {
  2236. call.args.result = result.result;
  2237. call.args.progress = result.progress;
  2238. msgResult = I18N('DAMAGE_FIXED', {
  2239. lastDamage: lastDamage.toLocaleString(),
  2240. maxDamage: result.value.toLocaleString(),
  2241. });
  2242. }
  2243. console.log(lastDamage, '>', result.value);
  2244. setProgress(
  2245. msgResult +
  2246. '<br/>' +
  2247. I18N('COUNT_FIXED', {
  2248. count: result.maxCount,
  2249. }),
  2250. false,
  2251. hideProgress
  2252. );
  2253. } else if (resultPopup > 3) {
  2254. const cloneBattle = structuredClone(lastBossBattle);
  2255. const { masterFixBattle } = HWHClasses;
  2256. const mFix = new masterFixBattle(cloneBattle);
  2257. const result = await mFix.start(cloneBattle.endTime, resultPopup);
  2258. console.log(result);
  2259. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2260. lastDamage: lastDamage.toLocaleString(),
  2261. });
  2262. if (result.value > lastDamage) {
  2263. maxDamage = result.value;
  2264. call.args.result = result.result;
  2265. call.args.progress = result.progress;
  2266. msgResult = I18N('DAMAGE_FIXED', {
  2267. lastDamage: lastDamage.toLocaleString(),
  2268. maxDamage: maxDamage.toLocaleString(),
  2269. });
  2270. }
  2271. console.log('Урон:', lastDamage, maxDamage);
  2272. setProgress(msgResult, false, hideProgress);
  2273. } else {
  2274. fixBattle(call.args.progress[0].attackers.heroes);
  2275. fixBattle(call.args.progress[0].defenders.heroes);
  2276. }
  2277. changeRequest = true;
  2278. }
  2279. const isStat = popup.getCheckBoxes().find((e) => e.name === 'isStat');
  2280. if (isStat.checked) {
  2281. this.onReadySuccess = testBossBattle;
  2282. }
  2283. }
  2284. /**
  2285. * Save the Asgard Boss Attack Pack
  2286. * Сохраняем пачку для атаки босса Асгарда
  2287. */
  2288. if (call.name == 'clanRaid_startBossBattle') {
  2289. console.log(JSON.stringify(call.args));
  2290. }
  2291. /**
  2292. * Saving the request to start the last battle
  2293. * Сохранение запроса начала последнего боя
  2294. */
  2295. if (
  2296. call.name == 'clanWarAttack' ||
  2297. call.name == 'crossClanWar_startBattle' ||
  2298. call.name == 'adventure_turnStartBattle' ||
  2299. call.name == 'adventureSolo_turnStartBattle' ||
  2300. call.name == 'bossAttack' ||
  2301. call.name == 'invasion_bossStart' ||
  2302. call.name == 'towerStartBattle'
  2303. ) {
  2304. nameFuncStartBattle = call.name;
  2305. lastBattleArg = call.args;
  2306.  
  2307. if (call.name == 'invasion_bossStart') {
  2308. const timePassed = Date.now() - lastBossBattleStart;
  2309. if (timePassed < invasionTimer) {
  2310. await new Promise((e) => setTimeout(e, invasionTimer - timePassed));
  2311. }
  2312. invasionTimer -= 1;
  2313. }
  2314. lastBossBattleStart = Date.now();
  2315. }
  2316. if (call.name == 'invasion_bossEnd') {
  2317. const lastBattle = lastBattleInfo;
  2318. if (lastBattle && call.args.result.win) {
  2319. lastBattle.progress = call.args.progress;
  2320. const result = await Calc(lastBattle);
  2321. let timer = getTimer(result.battleTime, 1) + addBattleTimer;
  2322. const period = Math.ceil((Date.now() - lastBossBattleStart) / 1000);
  2323. console.log(timer, period);
  2324. if (period < timer) {
  2325. timer = timer - period;
  2326. await countdownTimer(timer);
  2327. }
  2328. }
  2329. }
  2330. /**
  2331. * Disable spending divination cards
  2332. * Отключить трату карт предсказаний
  2333. */
  2334. if (call.name == 'dungeonEndBattle') {
  2335. if (call.args.isRaid) {
  2336. if (countPredictionCard <= 0) {
  2337. delete call.args.isRaid;
  2338. changeRequest = true;
  2339. } else if (countPredictionCard > 0) {
  2340. countPredictionCard--;
  2341. }
  2342. }
  2343. console.log(`Cards: ${countPredictionCard}`);
  2344. /**
  2345. * Fix endless cards
  2346. * Исправление бесконечных карт
  2347. */
  2348. const lastBattle = lastDungeonBattleData;
  2349. if (lastBattle && !call.args.isRaid) {
  2350. if (changeRequest) {
  2351. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2352. } else {
  2353. lastBattle.progress = call.args.progress;
  2354. }
  2355. const result = await Calc(lastBattle);
  2356.  
  2357. if (changeRequest) {
  2358. call.args.progress = result.progress;
  2359. call.args.result = result.result;
  2360. }
  2361. let timer = result.battleTimer + addBattleTimer;
  2362. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  2363. console.log(timer, period);
  2364. if (period < timer) {
  2365. timer = timer - period;
  2366. await countdownTimer(timer);
  2367. }
  2368. }
  2369. }
  2370. /**
  2371. * Quiz Answer
  2372. * Ответ на викторину
  2373. */
  2374. if (call.name == 'quiz_answer') {
  2375. /**
  2376. * Automatically changes the answer to the correct one if there is one.
  2377. * Автоматически меняет ответ на правильный если он есть
  2378. */
  2379. if (lastAnswer && isChecked('getAnswer')) {
  2380. call.args.answerId = lastAnswer;
  2381. lastAnswer = null;
  2382. changeRequest = true;
  2383. }
  2384. }
  2385. /**
  2386. * Present
  2387. * Подарки
  2388. */
  2389. if (call.name == 'freebieCheck') {
  2390. freebieCheckInfo = call;
  2391. }
  2392. /** missionTimer */
  2393. if (call.name == 'missionEnd' && missionBattle) {
  2394. let startTimer = false;
  2395. if (!call.args.result.win) {
  2396. startTimer = await popup.confirm(I18N('DEFEAT_TURN_TIMER'), [
  2397. { msg: I18N('BTN_NO'), result: false },
  2398. { msg: I18N('BTN_YES'), result: true },
  2399. ]);
  2400. }
  2401.  
  2402. if (call.args.result.win || startTimer) {
  2403. missionBattle.progress = call.args.progress;
  2404. missionBattle.result = call.args.result;
  2405. const result = await Calc(missionBattle);
  2406.  
  2407. let timer = result.battleTimer + addBattleTimer;
  2408. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  2409. if (period < timer) {
  2410. timer = timer - period;
  2411. await countdownTimer(timer);
  2412. }
  2413. missionBattle = null;
  2414. } else {
  2415. this.errorRequest = true;
  2416. }
  2417. }
  2418. /**
  2419. * Getting mission data for auto-repeat
  2420. * Получение данных миссии для автоповтора
  2421. */
  2422. if (isChecked('repeatMission') &&
  2423. call.name == 'missionEnd') {
  2424. let missionInfo = {
  2425. id: call.args.id,
  2426. result: call.args.result,
  2427. heroes: call.args.progress[0].attackers.heroes,
  2428. count: 0,
  2429. }
  2430. setTimeout(async () => {
  2431. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2432. { msg: I18N('BTN_REPEAT'), result: true},
  2433. { msg: I18N('BTN_NO'), result: false},
  2434. ])) {
  2435. isStopSendMission = false;
  2436. isSendsMission = true;
  2437. sendsMission(missionInfo);
  2438. }
  2439. }, 0);
  2440. }
  2441. /**
  2442. * Getting mission data
  2443. * Получение данных миссии
  2444. * missionTimer
  2445. */
  2446. if (call.name == 'missionStart') {
  2447. lastMissionStart = call.args;
  2448. lastMissionBattleStart = Date.now();
  2449. }
  2450. /**
  2451. * Specify the quantity for Titan Orbs and Pet Eggs
  2452. * Указать количество для сфер титанов и яиц петов
  2453. */
  2454. if (isChecked('countControl') &&
  2455. (call.name == 'pet_chestOpen' ||
  2456. call.name == 'titanUseSummonCircle') &&
  2457. call.args.amount > 1) {
  2458. const startAmount = call.args.amount;
  2459. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2460. { msg: I18N('BTN_OPEN'), isInput: true, default: 1},
  2461. ]);
  2462. if (result) {
  2463. const item = call.name == 'pet_chestOpen' ? { id: 90, type: 'consumable' } : { id: 13, type: 'coin' };
  2464. cheats.updateInventory({
  2465. [item.type]: {
  2466. [item.id]: -(result - startAmount),
  2467. },
  2468. });
  2469. call.args.amount = result;
  2470. changeRequest = true;
  2471. }
  2472. }
  2473. /**
  2474. * Specify the amount for keys and spheres of titan artifacts
  2475. * Указать колличество для ключей и сфер артефактов титанов
  2476. */
  2477. if (isChecked('countControl') &&
  2478. (call.name == 'artifactChestOpen' ||
  2479. call.name == 'titanArtifactChestOpen') &&
  2480. call.args.amount > 1 &&
  2481. call.args.free &&
  2482. !changeRequest) {
  2483. artifactChestOpenCallName = call.name;
  2484. const startAmount = call.args.amount;
  2485. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2486. { msg: I18N('BTN_OPEN'), isInput: true, default: 1 },
  2487. ]);
  2488. if (result) {
  2489. const openChests = result;
  2490. let sphere = result < 10 ? 1 : 10;
  2491. call.args.amount = sphere;
  2492. for (let count = openChests - sphere; count > 0; count -= sphere) {
  2493. if (count < 10) sphere = 1;
  2494. const ident = artifactChestOpenCallName + "_" + count;
  2495. testData.calls.push({
  2496. name: artifactChestOpenCallName,
  2497. args: {
  2498. amount: sphere,
  2499. free: true,
  2500. },
  2501. ident: ident
  2502. });
  2503. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2504. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2505. }
  2506. requestHistory[this.uniqid].calls[call.name].push(ident);
  2507. }
  2508.  
  2509. const consumableId = call.name == 'artifactChestOpen' ? 45 : 55;
  2510. cheats.updateInventory({
  2511. consumable: {
  2512. [consumableId]: -(openChests - startAmount),
  2513. },
  2514. });
  2515. artifactChestOpen = true;
  2516. changeRequest = true;
  2517. }
  2518. }
  2519. if (call.name == 'consumableUseLootBox') {
  2520. lastRussianDollId = call.args.libId;
  2521. /**
  2522. * Specify quantity for gold caskets
  2523. * Указать количество для золотых шкатулок
  2524. */
  2525. if (isChecked('countControl') &&
  2526. call.args.libId == 148 &&
  2527. call.args.amount > 1) {
  2528. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2529. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2530. ]);
  2531. call.args.amount = result;
  2532. changeRequest = true;
  2533. }
  2534. if (isChecked('countControl') && call.args.libId >= 362 && call.args.libId <= 389) {
  2535. this.massOpen = call.args.libId;
  2536. }
  2537. }
  2538. if (call.name == 'invasion_bossStart' && isChecked('tryFixIt_v2') && call.args.id == invasionInfo.id) {
  2539. const pack = invasionDataPacks[invasionInfo.bossLvl];
  2540. if (pack) {
  2541. if (pack.buff != invasionInfo.buff) {
  2542. setProgress(
  2543. I18N('INVASION_BOSS_BUFF', {
  2544. bossLvl: invasionInfo.bossLvl,
  2545. needBuff: pack.buff,
  2546. haveBuff: invasionInfo.buff,
  2547. }),
  2548. false
  2549. );
  2550. } else {
  2551. call.args.pet = pack.pet;
  2552. call.args.heroes = pack.heroes;
  2553. call.args.favor = pack.favor;
  2554. changeRequest = true;
  2555. }
  2556. }
  2557. }
  2558. if (call.name == 'workshopBuff_create') {
  2559. const pack = invasionDataPacks[invasionInfo.bossLvl];
  2560. if (pack) {
  2561. const addBuff = call.args.amount * 5;
  2562. if (pack.buff < addBuff + invasionInfo.buff) {
  2563. this.errorRequest = true;
  2564. }
  2565. setProgress(
  2566. I18N('INVASION_BOSS_BUFF', {
  2567. bossLvl: invasionInfo.bossLvl,
  2568. needBuff: pack.buff,
  2569. haveBuff: invasionInfo.buff,
  2570. }),
  2571. false
  2572. );
  2573. }
  2574. }
  2575. /**
  2576. * Changing the maximum number of raids in the campaign
  2577. * Изменение максимального количества рейдов в кампании
  2578. */
  2579. // if (call.name == 'missionRaid') {
  2580. // if (isChecked('countControl') && call.args.times > 1) {
  2581. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2582. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2583. // ]));
  2584. // call.args.times = result > call.args.times ? call.args.times : result;
  2585. // changeRequest = true;
  2586. // }
  2587. // }
  2588. }
  2589.  
  2590. let headers = requestHistory[this.uniqid].headers;
  2591. if (changeRequest) {
  2592. sourceData = JSON.stringify(testData);
  2593. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2594. }
  2595.  
  2596. let signature = headers['X-Auth-Signature'];
  2597. if (signature) {
  2598. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2599. }
  2600. } catch (err) {
  2601. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2602. }
  2603. return sourceData;
  2604. }
  2605. /**
  2606. * Processing and substitution of incoming data
  2607. *
  2608. * Обработка и подмена входящих данных
  2609. */
  2610. async function checkChangeResponse(response) {
  2611. try {
  2612. isChange = false;
  2613. let nowTime = Math.round(Date.now() / 1000);
  2614. callsIdent = requestHistory[this.uniqid].calls;
  2615. respond = JSON.parse(response);
  2616. /**
  2617. * If the request returned an error removes the error (removes synchronization errors)
  2618. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2619. */
  2620. if (respond.error) {
  2621. isChange = true;
  2622. console.error(respond.error);
  2623. if (isChecked('showErrors')) {
  2624. popup.confirm(I18N('ERROR_MSG', {
  2625. name: respond.error.name,
  2626. description: respond.error.description,
  2627. }));
  2628. }
  2629. if (respond.error.name != 'AccountBan') {
  2630. delete respond.error;
  2631. respond.results = [];
  2632. }
  2633. }
  2634. let mainReward = null;
  2635. const allReward = {};
  2636. let countTypeReward = 0;
  2637. let readQuestInfo = false;
  2638. for (const call of respond.results) {
  2639. /**
  2640. * Obtaining initial data for completing quests
  2641. * Получение исходных данных для выполнения квестов
  2642. */
  2643. if (readQuestInfo) {
  2644. questsInfo[call.ident] = call.result.response;
  2645. }
  2646. /**
  2647. * Getting a user ID
  2648. * Получение идетификатора пользователя
  2649. */
  2650. if (call.ident == callsIdent['registration']) {
  2651. userId = call.result.response.userId;
  2652. if (localStorage['userId'] != userId) {
  2653. localStorage['newGiftSendIds'] = '';
  2654. localStorage['userId'] = userId;
  2655. }
  2656. await openOrMigrateDatabase(userId);
  2657. readQuestInfo = true;
  2658. }
  2659. /**
  2660. * Hiding donation offers 1
  2661. * Скрываем предложения доната 1
  2662. */
  2663. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2664. const billings = call.result.response?.billings;
  2665. const bundle = call.result.response?.bundle;
  2666. if (billings && bundle) {
  2667. call.result.response.billings = call.result.response.billings.filter((e) => ['repeatableOffer'].includes(e.type));
  2668. call.result.response.bundle = [];
  2669. isChange = true;
  2670. }
  2671. }
  2672. /**
  2673. * Hiding donation offers 2
  2674. * Скрываем предложения доната 2
  2675. */
  2676. if (getSaveVal('noOfferDonat') &&
  2677. (call.ident == callsIdent['offerGetAll'] ||
  2678. call.ident == callsIdent['specialOffer_getAll'])) {
  2679. let offers = call.result.response;
  2680. if (offers) {
  2681. call.result.response = offers.filter(
  2682. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2683. );
  2684. isChange = true;
  2685. }
  2686. }
  2687. /**
  2688. * Hiding donation offers 3
  2689. * Скрываем предложения доната 3
  2690. */
  2691. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2692. delete call.result.bundleUpdate;
  2693. isChange = true;
  2694. }
  2695. /**
  2696. * Hiding donation offers 4
  2697. * Скрываем предложения доната 4
  2698. */
  2699. if (call.result?.specialOffers) {
  2700. const offers = call.result.specialOffers;
  2701. call.result.specialOffers = offers.filter(
  2702. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2703. );
  2704. isChange = true;
  2705. }
  2706. /**
  2707. * Copies a quiz question to the clipboard
  2708. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2709. */
  2710. if (call.ident == callsIdent['quiz_getNewQuestion']) {
  2711. let quest = call.result.response;
  2712. console.log(quest.question);
  2713. copyText(quest.question);
  2714. setProgress(I18N('QUESTION_COPY'), true);
  2715. quest.lang = null;
  2716. if (typeof NXFlashVars !== 'undefined') {
  2717. quest.lang = NXFlashVars.interface_lang;
  2718. }
  2719. lastQuestion = quest;
  2720. if (isChecked('getAnswer')) {
  2721. const answer = await getAnswer(lastQuestion);
  2722. let showText = '';
  2723. if (answer) {
  2724. lastAnswer = answer;
  2725. console.log(answer);
  2726. showText = `${I18N('ANSWER_KNOWN')}: ${answer}`;
  2727. } else {
  2728. showText = I18N('ANSWER_NOT_KNOWN');
  2729. }
  2730.  
  2731. try {
  2732. const hint = hintQuest(quest);
  2733. if (hint) {
  2734. showText += I18N('HINT') + hint;
  2735. }
  2736. } catch (e) {}
  2737.  
  2738. setProgress(showText, true);
  2739. }
  2740. }
  2741. /**
  2742. * Submits a question with an answer to the database
  2743. * Отправляет вопрос с ответом в базу данных
  2744. */
  2745. if (call.ident == callsIdent['quiz_answer']) {
  2746. const answer = call.result.response;
  2747. if (lastQuestion) {
  2748. const answerInfo = {
  2749. answer,
  2750. question: lastQuestion,
  2751. lang: null,
  2752. };
  2753. if (typeof NXFlashVars !== 'undefined') {
  2754. answerInfo.lang = NXFlashVars.interface_lang;
  2755. }
  2756. lastQuestion = null;
  2757. setTimeout(sendAnswerInfo, 0, answerInfo);
  2758. }
  2759. }
  2760. /**
  2761. * Get user data
  2762. * Получить даныне пользователя
  2763. */
  2764. if (call.ident == callsIdent['userGetInfo']) {
  2765. let user = call.result.response;
  2766. document.title = user.name;
  2767. userInfo = Object.assign({}, user);
  2768. delete userInfo.refillable;
  2769. if (!questsInfo['userGetInfo']) {
  2770. questsInfo['userGetInfo'] = user;
  2771. }
  2772. }
  2773. /**
  2774. * Start of the battle for recalculation
  2775. * Начало боя для прерасчета
  2776. */
  2777. if (call.ident == callsIdent['clanWarAttack'] ||
  2778. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2779. call.ident == callsIdent['bossAttack'] ||
  2780. call.ident == callsIdent['battleGetReplay'] ||
  2781. call.ident == callsIdent['brawl_startBattle'] ||
  2782. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2783. call.ident == callsIdent['invasion_bossStart'] ||
  2784. call.ident == callsIdent['titanArenaStartBattle'] ||
  2785. call.ident == callsIdent['towerStartBattle'] ||
  2786. call.ident == callsIdent['epicBrawl_startBattle'] ||
  2787. call.ident == callsIdent['adventure_turnStartBattle']) {
  2788. let battle = call.result.response.battle || call.result.response.replay;
  2789. if (call.ident == callsIdent['brawl_startBattle'] ||
  2790. call.ident == callsIdent['bossAttack'] ||
  2791. call.ident == callsIdent['towerStartBattle'] ||
  2792. call.ident == callsIdent['invasion_bossStart']) {
  2793. battle = call.result.response;
  2794. }
  2795. lastBattleInfo = battle;
  2796. if (call.ident == callsIdent['battleGetReplay'] && call.result.response.replay.type === "clan_raid") {
  2797. if (call?.result?.response?.replay?.result?.damage) {
  2798. const damages = Object.values(call.result.response.replay.result.damage);
  2799. const bossDamage = damages.reduce((a, v) => a + v, 0);
  2800. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2801. continue;
  2802. }
  2803. }
  2804. if (!isChecked('preCalcBattle')) {
  2805. continue;
  2806. }
  2807. const preCalcBattle = structuredClone(battle);
  2808. setProgress(I18N('BEING_RECALC'));
  2809. let battleDuration = 120;
  2810. try {
  2811. const typeBattle = getBattleType(preCalcBattle.type);
  2812. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2813. } catch (e) { }
  2814. //console.log(battle.type);
  2815. function getBattleInfo(battle, isRandSeed) {
  2816. return new Promise(function (resolve) {
  2817. if (isRandSeed) {
  2818. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2819. }
  2820. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2821. });
  2822. }
  2823. let actions = [getBattleInfo(preCalcBattle, false)];
  2824. let countTestBattle = getInput('countTestBattle');
  2825. if (call.ident == callsIdent['invasion_bossStart'] ) {
  2826. countTestBattle = 0;
  2827. }
  2828. if (call.ident == callsIdent['battleGetReplay']) {
  2829. preCalcBattle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', 0, 0] } }];
  2830. }
  2831. for (let i = 0; i < countTestBattle; i++) {
  2832. actions.push(getBattleInfo(preCalcBattle, true));
  2833. }
  2834. Promise.all(actions)
  2835. .then(e => {
  2836. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2837. let firstBattle = e.shift();
  2838. const timer = Math.floor(battleDuration - firstBattle.time);
  2839. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2840. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2841. let msg = `${I18N('THIS_TIME')} ${firstBattle.win ? I18N('VICTORY') : I18N('DEFEAT')}`;
  2842. if (e.length) {
  2843. const countWin = e.reduce((w, s) => w + s.win, 0);
  2844. msg += ` ${I18N('CHANCE_TO_WIN')}: ${Math.floor((countWin / e.length) * 100)}% (${e.length})`;
  2845. }
  2846. msg += `, ${min}:${sec}`
  2847. setProgress(msg, false, hideProgress)
  2848. });
  2849. }
  2850. /**
  2851. * Start of the Asgard boss fight
  2852. * Начало боя с боссом Асгарда
  2853. */
  2854. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2855. lastBossBattle = call.result.response.battle;
  2856. lastBossBattle.endTime = Date.now() + 160 * 1000;
  2857. if (isChecked('preCalcBattle')) {
  2858. const result = await Calc(lastBossBattle).then(e => e.progress[0].defenders.heroes[1].extra);
  2859. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2860. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2861. }
  2862. }
  2863. /**
  2864. * Cancel tutorial
  2865. * Отмена туториала
  2866. */
  2867. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2868. let chains = call.result.response.chains;
  2869. for (let n in chains) {
  2870. chains[n] = 9999;
  2871. }
  2872. isChange = true;
  2873. }
  2874. /**
  2875. * Opening keys and spheres of titan artifacts
  2876. * Открытие ключей и сфер артефактов титанов
  2877. */
  2878. if (artifactChestOpen &&
  2879. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2880. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2881. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2882.  
  2883. reward.forEach(e => {
  2884. for (let f in e) {
  2885. if (!allReward[f]) {
  2886. allReward[f] = {};
  2887. }
  2888. for (let o in e[f]) {
  2889. if (!allReward[f][o]) {
  2890. allReward[f][o] = e[f][o];
  2891. countTypeReward++;
  2892. } else {
  2893. allReward[f][o] += e[f][o];
  2894. }
  2895. }
  2896. }
  2897. });
  2898.  
  2899. if (!call.ident.includes(artifactChestOpenCallName)) {
  2900. mainReward = call.result.response;
  2901. }
  2902. }
  2903.  
  2904. if (countTypeReward > 20) {
  2905. correctShowOpenArtifact = 3;
  2906. } else {
  2907. correctShowOpenArtifact = 0;
  2908. }
  2909. /**
  2910. * Sum the result of opening Pet Eggs
  2911. * Суммирование результата открытия яиц питомцев
  2912. */
  2913. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2914. const rewards = call.result.response.rewards;
  2915. if (rewards.length > 10) {
  2916. /**
  2917. * Removing pet cards
  2918. * Убираем карточки петов
  2919. */
  2920. for (const reward of rewards) {
  2921. if (reward.petCard) {
  2922. delete reward.petCard;
  2923. }
  2924. }
  2925. }
  2926. rewards.forEach(e => {
  2927. for (let f in e) {
  2928. if (!allReward[f]) {
  2929. allReward[f] = {};
  2930. }
  2931. for (let o in e[f]) {
  2932. if (!allReward[f][o]) {
  2933. allReward[f][o] = e[f][o];
  2934. } else {
  2935. allReward[f][o] += e[f][o];
  2936. }
  2937. }
  2938. }
  2939. });
  2940. call.result.response.rewards = [allReward];
  2941. isChange = true;
  2942. }
  2943. /**
  2944. * Removing titan cards
  2945. * Убираем карточки титанов
  2946. */
  2947. if (call.ident == callsIdent['titanUseSummonCircle']) {
  2948. if (call.result.response.rewards.length > 10) {
  2949. for (const reward of call.result.response.rewards) {
  2950. if (reward.titanCard) {
  2951. delete reward.titanCard;
  2952. }
  2953. }
  2954. isChange = true;
  2955. }
  2956. }
  2957. /**
  2958. * Auto-repeat opening matryoshkas
  2959. * АвтоПовтор открытия матрешек
  2960. */
  2961. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2962. let [countLootBox, lootBox] = Object.entries(call.result.response).pop();
  2963. countLootBox = +countLootBox;
  2964. let newCount = 0;
  2965. if (lootBox?.consumable && lootBox.consumable[lastRussianDollId]) {
  2966. newCount += lootBox.consumable[lastRussianDollId];
  2967. delete lootBox.consumable[lastRussianDollId];
  2968. }
  2969. if (
  2970. newCount &&
  2971. (await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2972. { msg: I18N('BTN_OPEN'), result: true },
  2973. { msg: I18N('BTN_NO'), result: false, isClose: true },
  2974. ]))
  2975. ) {
  2976. const [count, recursionResult] = await openRussianDolls(lastRussianDollId, newCount);
  2977. countLootBox += +count;
  2978. mergeItemsObj(lootBox, recursionResult);
  2979. isChange = true;
  2980. }
  2981.  
  2982. if (this.massOpen) {
  2983. if (
  2984. await popup.confirm(I18N('OPEN_ALL_EQUIP_BOXES'), [
  2985. { msg: I18N('BTN_OPEN'), result: true },
  2986. { msg: I18N('BTN_NO'), result: false, isClose: true },
  2987. ])
  2988. ) {
  2989. const consumable = await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'inventoryGet' }] }).then((e) =>
  2990. Object.entries(e.results[0].result.response.consumable)
  2991. );
  2992. const calls = [];
  2993. const deleteItems = {};
  2994. for (const [libId, amount] of consumable) {
  2995. if (libId != this.massOpen && libId >= 362 && libId <= 389) {
  2996. calls.push({
  2997. name: 'consumableUseLootBox',
  2998. args: { libId, amount },
  2999. ident: 'consumableUseLootBox_' + libId,
  3000. });
  3001. deleteItems[libId] = -amount;
  3002. }
  3003. }
  3004. const responses = await Send({ calls }).then((e) => e.results.map((r) => r.result.response).flat());
  3005.  
  3006. for (const loot of responses) {
  3007. const [count, result] = Object.entries(loot).pop();
  3008. countLootBox += +count;
  3009.  
  3010. mergeItemsObj(lootBox, result);
  3011. }
  3012. isChange = true;
  3013.  
  3014. this.onReadySuccess = () => {
  3015. cheats.updateInventory({ consumable: deleteItems });
  3016. cheats.refreshInventory();
  3017. };
  3018. }
  3019. }
  3020.  
  3021. if (isChange) {
  3022. call.result.response = {
  3023. [countLootBox]: lootBox,
  3024. };
  3025. }
  3026. }
  3027. /**
  3028. * Dungeon recalculation (fix endless cards)
  3029. * Прерасчет подземки (исправление бесконечных карт)
  3030. */
  3031. if (call.ident == callsIdent['dungeonStartBattle']) {
  3032. lastDungeonBattleData = call.result.response;
  3033. lastDungeonBattleStart = Date.now();
  3034. }
  3035. /**
  3036. * Getting the number of prediction cards
  3037. * Получение количества карт предсказаний
  3038. */
  3039. if (call.ident == callsIdent['inventoryGet']) {
  3040. countPredictionCard = call.result.response.consumable[81] || 0;
  3041. }
  3042. /**
  3043. * Getting subscription status
  3044. * Получение состояния подписки
  3045. */
  3046. if (call.ident == callsIdent['subscriptionGetInfo']) {
  3047. const subscription = call.result.response.subscription;
  3048. if (subscription) {
  3049. subEndTime = subscription.endTime * 1000;
  3050. }
  3051. }
  3052. /**
  3053. * Getting prediction cards
  3054. * Получение карт предсказаний
  3055. */
  3056. if (call.ident == callsIdent['questFarm']) {
  3057. const consumable = call.result.response?.consumable;
  3058. if (consumable && consumable[81]) {
  3059. countPredictionCard += consumable[81];
  3060. console.log(`Cards: ${countPredictionCard}`);
  3061. }
  3062. }
  3063. /**
  3064. * Hiding extra servers
  3065. * Скрытие лишних серверов
  3066. */
  3067. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  3068. let servers = call.result.response.users.map(s => s.serverId)
  3069. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  3070. isChange = true;
  3071. }
  3072. /**
  3073. * Displays player positions in the adventure
  3074. * Отображает позиции игроков в приключении
  3075. */
  3076. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  3077. const users = Object.values(call.result.response.users);
  3078. const mapIdent = call.result.response.mapIdent;
  3079. const adventureId = call.result.response.adventureId;
  3080. const maps = {
  3081. adv_strongford_3pl_hell: 9,
  3082. adv_valley_3pl_hell: 10,
  3083. adv_ghirwil_3pl_hell: 11,
  3084. adv_angels_3pl_hell: 12,
  3085. }
  3086. let msg = I18N('MAP') + (mapIdent in maps ? maps[mapIdent] : adventureId);
  3087. msg += '<br>' + I18N('PLAYER_POS');
  3088. for (const user of users) {
  3089. msg += `<br>${user.user.name} - ${user.currentNode}`;
  3090. }
  3091. setProgress(msg, false, hideProgress);
  3092. }
  3093. /**
  3094. * Automatic launch of a raid at the end of the adventure
  3095. * Автоматический запуск рейда при окончании приключения
  3096. */
  3097. if (call.ident == callsIdent['adventure_end']) {
  3098. autoRaidAdventure()
  3099. }
  3100. /** Удаление лавки редкостей */
  3101. if (call.ident == callsIdent['missionRaid']) {
  3102. if (call.result?.heroesMerchant) {
  3103. delete call.result.heroesMerchant;
  3104. isChange = true;
  3105. }
  3106. }
  3107. /** missionTimer */
  3108. if (call.ident == callsIdent['missionStart']) {
  3109. missionBattle = call.result.response;
  3110. }
  3111. /** Награды турнира стихий */
  3112. if (call.ident == callsIdent['hallOfFameGetTrophies']) {
  3113. const trophys = call.result.response;
  3114. const calls = [];
  3115. for (const week in trophys) {
  3116. const trophy = trophys[week];
  3117. if (!trophy.championRewardFarmed) {
  3118. calls.push({
  3119. name: 'hallOfFameFarmTrophyReward',
  3120. args: { trophyId: week, rewardType: 'champion' },
  3121. ident: 'body_champion_' + week,
  3122. });
  3123. }
  3124. if (Object.keys(trophy.clanReward).length && !trophy.clanRewardFarmed) {
  3125. calls.push({
  3126. name: 'hallOfFameFarmTrophyReward',
  3127. args: { trophyId: week, rewardType: 'clan' },
  3128. ident: 'body_clan_' + week,
  3129. });
  3130. }
  3131. }
  3132. if (calls.length) {
  3133. Send({ calls })
  3134. .then((e) => e.results.map((e) => e.result.response))
  3135. .then(async results => {
  3136. let coin18 = 0,
  3137. coin19 = 0,
  3138. gold = 0,
  3139. starmoney = 0;
  3140. for (const r of results) {
  3141. coin18 += r?.coin ? +r.coin[18] : 0;
  3142. coin19 += r?.coin ? +r.coin[19] : 0;
  3143. gold += r?.gold ? +r.gold : 0;
  3144. starmoney += r?.starmoney ? +r.starmoney : 0;
  3145. }
  3146.  
  3147. let msg = I18N('ELEMENT_TOURNAMENT_REWARD') + '<br>';
  3148. if (coin18) {
  3149. msg += cheats.translate('LIB_COIN_NAME_18') + `: ${coin18}<br>`;
  3150. }
  3151. if (coin19) {
  3152. msg += cheats.translate('LIB_COIN_NAME_19') + `: ${coin19}<br>`;
  3153. }
  3154. if (gold) {
  3155. msg += cheats.translate('LIB_PSEUDO_COIN') + `: ${gold}<br>`;
  3156. }
  3157. if (starmoney) {
  3158. msg += cheats.translate('LIB_PSEUDO_STARMONEY') + `: ${starmoney}<br>`;
  3159. }
  3160.  
  3161. await popup.confirm(msg, [{ msg: I18N('BTN_OK'), result: 0 }]);
  3162. });
  3163. }
  3164. }
  3165. if (call.ident == callsIdent['clanDomination_getInfo']) {
  3166. clanDominationGetInfo = call.result.response;
  3167. }
  3168. if (call.ident == callsIdent['clanRaid_endBossBattle']) {
  3169. console.log(call.result.response);
  3170. const damage = Object.values(call.result.response.damage).reduce((a, e) => a + e);
  3171. if (call.result.response.result.afterInvalid) {
  3172. addProgress('<br>' + I18N('SERVER_NOT_ACCEPT'));
  3173. }
  3174. addProgress('<br>Server > ' + I18N('BOSS_DAMAGE') + damage.toLocaleString());
  3175. }
  3176. if (call.ident == callsIdent['invasion_getInfo']) {
  3177. const r = call.result.response;
  3178. if (r?.actions?.length) {
  3179. const boss = r.actions.find((e) => e.payload.id === invasionInfo.id);
  3180. if (boss) {
  3181. invasionInfo.buff = r.buffAmount;
  3182. invasionInfo.bossLvl = boss.payload.level;
  3183. if (isChecked('tryFixIt_v2')) {
  3184. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3185. if (pack) {
  3186. setProgress(
  3187. I18N('INVASION_BOSS_BUFF', {
  3188. bossLvl: invasionInfo.bossLvl,
  3189. needBuff: pack.buff,
  3190. haveBuff: invasionInfo.buff,
  3191. }),
  3192. false
  3193. );
  3194. }
  3195. }
  3196. }
  3197. }
  3198. }
  3199. if (call.ident == callsIdent['workshopBuff_create']) {
  3200. const r = call.result.response;
  3201. if (r.id == 1) {
  3202. invasionInfo.buff = r.amount;
  3203. if (isChecked('tryFixIt_v2')) {
  3204. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3205. if (pack) {
  3206. setProgress(
  3207. I18N('INVASION_BOSS_BUFF', {
  3208. bossLvl: invasionInfo.bossLvl,
  3209. needBuff: pack.buff,
  3210. haveBuff: invasionInfo.buff,
  3211. }),
  3212. false
  3213. );
  3214. }
  3215. }
  3216. }
  3217. }
  3218. /*
  3219. if (call.ident == callsIdent['chatGetAll'] && call.args.chatType == 'clanDomination' && !callsIdent['clanDomination_mapState']) {
  3220. this.onReadySuccess = async function () {
  3221. const result = await Send({
  3222. calls: [
  3223. {
  3224. name: 'clanDomination_mapState',
  3225. args: {},
  3226. ident: 'clanDomination_mapState',
  3227. },
  3228. ],
  3229. }).then((e) => e.results[0].result.response);
  3230. let townPositions = result.townPositions;
  3231. let positions = {};
  3232. for (let pos in townPositions) {
  3233. let townPosition = townPositions[pos];
  3234. positions[townPosition.position] = townPosition;
  3235. }
  3236. Object.assign(clanDominationGetInfo, {
  3237. townPositions: positions,
  3238. });
  3239. let userPositions = result.userPositions;
  3240. for (let pos in clanDominationGetInfo.townPositions) {
  3241. let townPosition = clanDominationGetInfo.townPositions[pos];
  3242. if (townPosition.status) {
  3243. userPositions[townPosition.userId] = +pos;
  3244. }
  3245. }
  3246. cheats.updateMap(result);
  3247. };
  3248. }
  3249. if (call.ident == callsIdent['clanDomination_mapState']) {
  3250. const townPositions = call.result.response.townPositions;
  3251. const userPositions = call.result.response.userPositions;
  3252. for (let pos in townPositions) {
  3253. let townPos = townPositions[pos];
  3254. if (townPos.status) {
  3255. userPositions[townPos.userId] = townPos.position;
  3256. }
  3257. }
  3258. isChange = true;
  3259. }
  3260. */
  3261. }
  3262.  
  3263. if (mainReward && artifactChestOpen) {
  3264. console.log(allReward);
  3265. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  3266. artifactChestOpen = false;
  3267. artifactChestOpenCallName = '';
  3268. isChange = true;
  3269. }
  3270. } catch(err) {
  3271. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  3272. }
  3273.  
  3274. if (isChange) {
  3275. Object.defineProperty(this, 'responseText', {
  3276. writable: true
  3277. });
  3278. this.responseText = JSON.stringify(respond);
  3279. }
  3280. }
  3281.  
  3282. /**
  3283. * Request an answer to a question
  3284. *
  3285. * Запрос ответа на вопрос
  3286. */
  3287. async function getAnswer(question) {
  3288. // c29tZSBzdHJhbmdlIHN5bWJvbHM=
  3289. const quizAPI = new ZingerYWebsiteAPI('getAnswer.php', arguments, { question });
  3290. return new Promise((resolve, reject) => {
  3291. quizAPI.request().then((data) => {
  3292. if (data.result) {
  3293. resolve(data.result);
  3294. } else {
  3295. resolve(false);
  3296. }
  3297. }).catch((error) => {
  3298. console.error(error);
  3299. resolve(false);
  3300. });
  3301. })
  3302. }
  3303.  
  3304. /**
  3305. * Submitting a question and answer to a database
  3306. *
  3307. * Отправка вопроса и ответа в базу данных
  3308. */
  3309. function sendAnswerInfo(answerInfo) {
  3310. // c29tZSBub25zZW5zZQ==
  3311. const quizAPI = new ZingerYWebsiteAPI('setAnswer.php', arguments, { answerInfo });
  3312. quizAPI.request().then((data) => {
  3313. if (data.result) {
  3314. console.log(I18N('SENT_QUESTION'));
  3315. }
  3316. });
  3317. }
  3318.  
  3319. /**
  3320. * Returns the battle type by preset type
  3321. *
  3322. * Возвращает тип боя по типу пресета
  3323. */
  3324. function getBattleType(strBattleType) {
  3325. if (!strBattleType) {
  3326. return null;
  3327. }
  3328. switch (strBattleType) {
  3329. case 'titan_pvp':
  3330. return 'get_titanPvp';
  3331. case 'titan_pvp_manual':
  3332. case 'titan_clan_pvp':
  3333. case 'clan_pvp_titan':
  3334. case 'clan_global_pvp_titan':
  3335. case 'brawl_titan':
  3336. case 'challenge_titan':
  3337. case 'titan_mission':
  3338. return 'get_titanPvpManual';
  3339. case 'clan_raid': // Asgard Boss // Босс асгарда
  3340. case 'adventure': // Adventures // Приключения
  3341. case 'clan_global_pvp':
  3342. case 'epic_brawl':
  3343. case 'clan_pvp':
  3344. return 'get_clanPvp';
  3345. case 'dungeon_titan':
  3346. case 'titan_tower':
  3347. return 'get_titan';
  3348. case 'tower':
  3349. case 'clan_dungeon':
  3350. return 'get_tower';
  3351. case 'pve':
  3352. case 'mission':
  3353. return 'get_pve';
  3354. case 'mission_boss':
  3355. return 'get_missionBoss';
  3356. case 'challenge':
  3357. case 'pvp_manual':
  3358. return 'get_pvpManual';
  3359. case 'grand':
  3360. case 'arena':
  3361. case 'pvp':
  3362. case 'clan_domination':
  3363. return 'get_pvp';
  3364. case 'core':
  3365. return 'get_core';
  3366. default: {
  3367. if (strBattleType.includes('invasion')) {
  3368. return 'get_invasion';
  3369. }
  3370. if (strBattleType.includes('boss')) {
  3371. return 'get_boss';
  3372. }
  3373. if (strBattleType.includes('titan_arena')) {
  3374. return 'get_titanPvpManual';
  3375. }
  3376. return 'get_clanPvp';
  3377. }
  3378. }
  3379. }
  3380. /**
  3381. * Returns the class name of the passed object
  3382. *
  3383. * Возвращает название класса переданного объекта
  3384. */
  3385. function getClass(obj) {
  3386. return {}.toString.call(obj).slice(8, -1);
  3387. }
  3388. /**
  3389. * Calculates the request signature
  3390. *
  3391. * Расчитывает сигнатуру запроса
  3392. */
  3393. this.getSignature = function(headers, data) {
  3394. const sign = {
  3395. signature: '',
  3396. length: 0,
  3397. add: function (text) {
  3398. this.signature += text;
  3399. if (this.length < this.signature.length) {
  3400. this.length = 3 * (this.signature.length + 1) >> 1;
  3401. }
  3402. },
  3403. }
  3404. sign.add(headers["X-Request-Id"]);
  3405. sign.add(':');
  3406. sign.add(headers["X-Auth-Token"]);
  3407. sign.add(':');
  3408. sign.add(headers["X-Auth-Session-Id"]);
  3409. sign.add(':');
  3410. sign.add(data);
  3411. sign.add(':');
  3412. sign.add('LIBRARY-VERSION=1');
  3413. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  3414.  
  3415. return md5(sign.signature);
  3416. }
  3417.  
  3418. class HotkeyManager {
  3419. constructor() {
  3420. if (HotkeyManager.instance) {
  3421. return HotkeyManager.instance;
  3422. }
  3423. this.hotkeys = [];
  3424. document.addEventListener('keydown', this.handleKeyDown.bind(this));
  3425. HotkeyManager.instance = this;
  3426. }
  3427.  
  3428. handleKeyDown(event) {
  3429. const key = event.key.toLowerCase();
  3430. const mods = {
  3431. ctrl: event.ctrlKey,
  3432. alt: event.altKey,
  3433. shift: event.shiftKey,
  3434. };
  3435.  
  3436. this.hotkeys.forEach((hotkey) => {
  3437. if (hotkey.key === key && hotkey.ctrl === mods.ctrl && hotkey.alt === mods.alt && hotkey.shift === mods.shift) {
  3438. hotkey.callback(hotkey);
  3439. }
  3440. });
  3441. }
  3442.  
  3443. add(key, opt = {}, callback) {
  3444. this.hotkeys.push({
  3445. key: key.toLowerCase(),
  3446. callback,
  3447. ctrl: opt.ctrl || false,
  3448. alt: opt.alt || false,
  3449. shift: opt.shift || false,
  3450. });
  3451. }
  3452.  
  3453. remove(key, opt = {}) {
  3454. this.hotkeys = this.hotkeys.filter((hotkey) => {
  3455. return !(
  3456. hotkey.key === key.toLowerCase() &&
  3457. hotkey.ctrl === (opt.ctrl || false) &&
  3458. hotkey.alt === (opt.alt || false) &&
  3459. hotkey.shift === (opt.shift || false)
  3460. );
  3461. });
  3462. }
  3463.  
  3464. static getInst() {
  3465. if (!HotkeyManager.instance) {
  3466. new HotkeyManager();
  3467. }
  3468. return HotkeyManager.instance;
  3469. }
  3470. }
  3471.  
  3472. class MouseClicker {
  3473. constructor(element) {
  3474. if (MouseClicker.instance) {
  3475. return MouseClicker.instance;
  3476. }
  3477. this.element = element;
  3478. this.mouse = {
  3479. bubbles: true,
  3480. cancelable: true,
  3481. clientX: 0,
  3482. clientY: 0,
  3483. };
  3484. this.element.addEventListener('mousemove', this.handleMouseMove.bind(this));
  3485. this.clickInfo = {};
  3486. this.nextTimeoutId = 1;
  3487. MouseClicker.instance = this;
  3488. }
  3489.  
  3490. handleMouseMove(event) {
  3491. this.mouse.clientX = event.clientX;
  3492. this.mouse.clientY = event.clientY;
  3493. }
  3494.  
  3495. click(options) {
  3496. options = options || this.mouse;
  3497. this.element.dispatchEvent(new MouseEvent('mousedown', options));
  3498. this.element.dispatchEvent(new MouseEvent('mouseup', options));
  3499. }
  3500.  
  3501. start(interval = 1000, clickCount = Infinity) {
  3502. const currentMouse = { ...this.mouse };
  3503. const timeoutId = this.nextTimeoutId++;
  3504. let count = 0;
  3505.  
  3506. const clickTimeout = () => {
  3507. this.click(currentMouse);
  3508. count++;
  3509. if (count < clickCount) {
  3510. this.clickInfo[timeoutId].timeout = setTimeout(clickTimeout, interval);
  3511. } else {
  3512. delete this.clickInfo[timeoutId];
  3513. }
  3514. };
  3515.  
  3516. this.clickInfo[timeoutId] = {
  3517. timeout: setTimeout(clickTimeout, interval),
  3518. count: clickCount,
  3519. };
  3520. return timeoutId;
  3521. }
  3522.  
  3523. stop(timeoutId) {
  3524. if (this.clickInfo[timeoutId]) {
  3525. clearTimeout(this.clickInfo[timeoutId].timeout);
  3526. delete this.clickInfo[timeoutId];
  3527. }
  3528. }
  3529.  
  3530. stopAll() {
  3531. for (const timeoutId in this.clickInfo) {
  3532. clearTimeout(this.clickInfo[timeoutId].timeout);
  3533. }
  3534. this.clickInfo = {};
  3535. }
  3536.  
  3537. static getInst(element) {
  3538. if (!MouseClicker.instance) {
  3539. new MouseClicker(element);
  3540. }
  3541. return MouseClicker.instance;
  3542. }
  3543. }
  3544.  
  3545. let extintionsList = [];
  3546. /**
  3547. * Creates an interface
  3548. *
  3549. * Создает интерфейс
  3550. */
  3551. function createInterface() {
  3552. popup.init();
  3553. scriptMenu.init();
  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'), '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'), '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: true,
  4435. showDetails: {},
  4436. };
  4437. }
  4438.  
  4439. init(option = {}) {
  4440. this.option = Object.assign(this.option, option);
  4441. const saveOption = this.loadSaveOption();
  4442. this.option = Object.assign(this.option, saveOption);
  4443. this.addStyle();
  4444. this.addBlocks();
  4445. }
  4446.  
  4447. addStyle() {
  4448. const style = document.createElement('style');
  4449. style.innerText = `
  4450. .scriptMenu_status {
  4451. position: absolute;
  4452. z-index: 10001;
  4453. top: -1px;
  4454. left: 30%;
  4455. cursor: pointer;
  4456. border-radius: 0px 0px 10px 10px;
  4457. background: #190e08e6;
  4458. border: 1px #ce9767 solid;
  4459. font-size: 18px;
  4460. font-family: sans-serif;
  4461. font-weight: 600;
  4462. font-stretch: condensed;
  4463. letter-spacing: 1px;
  4464. color: #fce1ac;
  4465. text-shadow: 0px 0px 1px;
  4466. transition: 0.5s;
  4467. padding: 2px 10px 3px;
  4468. }
  4469. .scriptMenu_statusHide {
  4470. top: -35px;
  4471. height: 30px;
  4472. overflow: hidden;
  4473. }
  4474. .scriptMenu_label {
  4475. position: absolute;
  4476. top: 30%;
  4477. left: -4px;
  4478. z-index: 9999;
  4479. cursor: pointer;
  4480. width: 30px;
  4481. height: 30px;
  4482. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  4483. border: 1px solid #1a2f04;
  4484. border-radius: 5px;
  4485. box-shadow:
  4486. inset 0px 2px 4px #83ce26,
  4487. inset 0px -4px 6px #1a2f04,
  4488. 0px 0px 2px black,
  4489. 0px 0px 0px 2px #ce9767;
  4490. }
  4491. .scriptMenu_label:hover {
  4492. filter: brightness(1.2);
  4493. }
  4494. .scriptMenu_arrowLabel {
  4495. width: 100%;
  4496. height: 100%;
  4497. background-size: 75%;
  4498. background-position: center;
  4499. background-repeat: no-repeat;
  4500. 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");
  4501. box-shadow: 0px 1px 2px #000;
  4502. border-radius: 5px;
  4503. filter: drop-shadow(0px 1px 2px #000D);
  4504. }
  4505. .scriptMenu_main {
  4506. position: absolute;
  4507. max-width: 285px;
  4508. z-index: 9999;
  4509. top: 50%;
  4510. transform: translateY(-40%);
  4511. background: #190e08e6;
  4512. border: 1px #ce9767 solid;
  4513. border-radius: 0px 10px 10px 0px;
  4514. border-left: none;
  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. }
  4525. .scriptMenu_conteiner {
  4526. max-height: 80vh;
  4527. overflow: scroll;
  4528. scrollbar-width: none; /* Для Firefox */
  4529. -ms-overflow-style: none; /* Для Internet Explorer и Edge */
  4530. display: flex;
  4531. flex-direction: column;
  4532. flex-wrap: nowrap;
  4533. padding: 5px 10px 5px 5px;
  4534. }
  4535. .scriptMenu_conteiner::-webkit-scrollbar {
  4536. display: none; /* Для Chrome, Safari и Opera */
  4537. }
  4538. .scriptMenu_showMenu {
  4539. display: none;
  4540. }
  4541. .scriptMenu_showMenu:checked~.scriptMenu_main {
  4542. left: 0px;
  4543. }
  4544. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  4545. left: -300px;
  4546. }
  4547. .scriptMenu_divInput {
  4548. margin: 2px;
  4549. }
  4550. .scriptMenu_divInputText {
  4551. margin: 2px;
  4552. align-self: center;
  4553. display: flex;
  4554. }
  4555. .scriptMenu_checkbox {
  4556. position: absolute;
  4557. z-index: -1;
  4558. opacity: 0;
  4559. }
  4560. .scriptMenu_checkbox+label {
  4561. display: inline-flex;
  4562. align-items: center;
  4563. user-select: none;
  4564. }
  4565. .scriptMenu_checkbox+label::before {
  4566. content: '';
  4567. display: inline-block;
  4568. width: 20px;
  4569. height: 20px;
  4570. border: 1px solid #cf9250;
  4571. border-radius: 7px;
  4572. margin-right: 7px;
  4573. }
  4574. .scriptMenu_checkbox:checked+label::before {
  4575. 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");
  4576. }
  4577. .scriptMenu_close {
  4578. width: 40px;
  4579. height: 40px;
  4580. position: absolute;
  4581. right: -18px;
  4582. top: -18px;
  4583. border: 3px solid #c18550;
  4584. border-radius: 20px;
  4585. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4586. background-position-y: 3px;
  4587. box-shadow: -1px 1px 3px black;
  4588. cursor: pointer;
  4589. box-sizing: border-box;
  4590. }
  4591. .scriptMenu_close:hover {
  4592. filter: brightness(1.2);
  4593. }
  4594. .scriptMenu_crossClose {
  4595. width: 100%;
  4596. height: 100%;
  4597. background-size: 65%;
  4598. background-position: center;
  4599. background-repeat: no-repeat;
  4600. 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")
  4601. }
  4602. .scriptMenu_button {
  4603. user-select: none;
  4604. cursor: pointer;
  4605. padding: 5px 14px 8px;
  4606. }
  4607. .scriptMenu_button:hover {
  4608. filter: brightness(1.2);
  4609. }
  4610. .scriptMenu_buttonText {
  4611. color: #fce5b7;
  4612. text-shadow: 0px 1px 2px black;
  4613. text-align: center;
  4614. }
  4615. .scriptMenu_header {
  4616. text-align: center;
  4617. align-self: center;
  4618. font-size: 15px;
  4619. margin: 0px 15px;
  4620. }
  4621. .scriptMenu_header a {
  4622. color: #fce5b7;
  4623. text-decoration: none;
  4624. }
  4625. .scriptMenu_InputText {
  4626. text-align: center;
  4627. width: 130px;
  4628. height: 24px;
  4629. border: 1px solid #cf9250;
  4630. border-radius: 9px;
  4631. background: transparent;
  4632. color: #fce1ac;
  4633. padding: 0px 10px;
  4634. box-sizing: border-box;
  4635. }
  4636. .scriptMenu_InputText:focus {
  4637. filter: brightness(1.2);
  4638. outline: 0;
  4639. }
  4640. .scriptMenu_InputText::placeholder {
  4641. color: #fce1ac75;
  4642. }
  4643. .scriptMenu_Summary {
  4644. cursor: pointer;
  4645. margin-left: 7px;
  4646. }
  4647. .scriptMenu_Details {
  4648. align-self: center;
  4649. }
  4650. .scriptMenu_buttonGroup {
  4651. display: flex;
  4652. justify-content: center;
  4653. user-select: none;
  4654. cursor: pointer;
  4655. padding: 0;
  4656. margin: 3px 0;
  4657. }
  4658. .scriptMenu_buttonGroup .scriptMenu_button {
  4659. width: 100%;
  4660. padding: 5px 8px 8px;
  4661. }
  4662. .scriptMenu_mainButton {
  4663. border-radius: 5px;
  4664. margin: 3px 0;
  4665. }
  4666. .scriptMenu_combineButtonLeft {
  4667. border-top-left-radius: 5px;
  4668. border-bottom-left-radius: 5px;
  4669. margin-right: 2px;
  4670. }
  4671. .scriptMenu_combineButtonCenter {
  4672. border-radius: 0px;
  4673. margin-right: 2px;
  4674. }
  4675. .scriptMenu_combineButtonRight {
  4676. border-top-right-radius: 5px;
  4677. border-bottom-right-radius: 5px;
  4678. }
  4679. .scriptMenu_beigeButton {
  4680. border: 1px solid #442901;
  4681. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  4682. 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;
  4683. }
  4684. .scriptMenu_beigeButton:active {
  4685. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4686. }
  4687. .scriptMenu_greenButton {
  4688. border: 1px solid #1a2f04;
  4689. background: radial-gradient(circle, #47a41b 0%, #1a2f04 150%);
  4690. box-shadow: inset 0px 2px 4px #83ce26, inset 0px -4px 6px #1a2f04, 0px 0px 2px black, 0px 0px 0px 1px #ce9767;
  4691. }
  4692. .scriptMenu_greenButton:active {
  4693. box-shadow: inset 0px 4px 6px #1a2f04, inset 0px 4px 6px #1a2f04, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4694. }
  4695. .scriptMenu_redButton {
  4696. border: 1px solid #440101;
  4697. background: radial-gradient(circle, rgb(198, 34, 34) 80%, rgb(0, 0, 0) 110%);
  4698. 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;
  4699. }
  4700. .scriptMenu_redButton:active {
  4701. box-shadow: inset 0px 4px 6px #440101, inset 0px 4px 6px #440101, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4702. }
  4703. .scriptMenu_attention {
  4704. position: relative;
  4705. }
  4706. .scriptMenu_attention .scriptMenu_dot {
  4707. display: flex;
  4708. justify-content: center;
  4709. align-items: center;
  4710. }
  4711. .scriptMenu_dot {
  4712. position: absolute;
  4713. top: -7px;
  4714. right: -7px;
  4715. width: 20px;
  4716. height: 20px;
  4717. border-radius: 50%;
  4718. border: 1px solid #c18550;
  4719. background: radial-gradient(circle, #f000 25%, black 100%);
  4720. box-shadow: 0px 0px 2px black;
  4721. background-position: 0px -1px;
  4722. font-size: 10px;
  4723. text-align: center;
  4724. color: white;
  4725. text-shadow: 1px 1px 1px black;
  4726. box-sizing: border-box;
  4727. display: none;
  4728. }
  4729. `;
  4730. document.head.appendChild(style);
  4731. }
  4732.  
  4733. addBlocks() {
  4734. const main = document.createElement('div');
  4735. document.body.appendChild(main);
  4736.  
  4737. this.status = document.createElement('div');
  4738. this.status.classList.add('scriptMenu_status');
  4739. this.setStatus('');
  4740. main.appendChild(this.status);
  4741.  
  4742. const label = document.createElement('label');
  4743. label.classList.add('scriptMenu_label');
  4744. label.setAttribute('for', 'checkbox_showMenu');
  4745. main.appendChild(label);
  4746.  
  4747. const arrowLabel = document.createElement('div');
  4748. arrowLabel.classList.add('scriptMenu_arrowLabel');
  4749. label.appendChild(arrowLabel);
  4750.  
  4751. const checkbox = document.createElement('input');
  4752. checkbox.type = 'checkbox';
  4753. checkbox.id = 'checkbox_showMenu';
  4754. checkbox.checked = this.option.showMenu;
  4755. checkbox.classList.add('scriptMenu_showMenu');
  4756. checkbox.addEventListener('change', () => {
  4757. this.option.showMenu = checkbox.checked;
  4758. this.saveSaveOption();
  4759. });
  4760. main.appendChild(checkbox);
  4761.  
  4762. const mainMenu = document.createElement('div');
  4763. mainMenu.classList.add('scriptMenu_main');
  4764. main.appendChild(mainMenu);
  4765.  
  4766. this.mainMenu = document.createElement('div');
  4767. this.mainMenu.classList.add('scriptMenu_conteiner');
  4768. mainMenu.appendChild(this.mainMenu);
  4769.  
  4770. const closeButton = document.createElement('label');
  4771. closeButton.classList.add('scriptMenu_close');
  4772. closeButton.setAttribute('for', 'checkbox_showMenu');
  4773. this.mainMenu.appendChild(closeButton);
  4774.  
  4775. const crossClose = document.createElement('div');
  4776. crossClose.classList.add('scriptMenu_crossClose');
  4777. closeButton.appendChild(crossClose);
  4778. }
  4779.  
  4780. getButtonColor(color) {
  4781. const buttonColors = {
  4782. green: 'scriptMenu_greenButton',
  4783. red: 'scriptMenu_redButton',
  4784. beige: 'scriptMenu_beigeButton',
  4785. };
  4786. return buttonColors[color] || buttonColors['beige'];
  4787. }
  4788.  
  4789. setStatus(text, onclick) {
  4790. if (!text) {
  4791. this.status.classList.add('scriptMenu_statusHide');
  4792. this.status.innerHTML = '';
  4793. } else {
  4794. this.status.classList.remove('scriptMenu_statusHide');
  4795. this.status.innerHTML = text;
  4796. }
  4797.  
  4798. if (typeof onclick === 'function') {
  4799. this.status.addEventListener('click', onclick, { once: true });
  4800. }
  4801. }
  4802.  
  4803. addStatus(text) {
  4804. if (!this.status.innerHTML) {
  4805. this.status.classList.remove('scriptMenu_statusHide');
  4806. }
  4807. this.status.innerHTML += text;
  4808. }
  4809.  
  4810. addHeader(text, onClick, main = this.mainMenu) {
  4811. const header = document.createElement('div');
  4812. header.classList.add('scriptMenu_header');
  4813. header.innerHTML = text;
  4814. if (typeof onClick === 'function') {
  4815. header.addEventListener('click', onClick);
  4816. }
  4817. main.appendChild(header);
  4818. return header;
  4819. }
  4820.  
  4821. addButton(btn, main = this.mainMenu) {
  4822. const { name, onClick, title, color, dot, classes = [], isCombine } = btn;
  4823. const button = document.createElement('div');
  4824. if (!isCombine) {
  4825. classes.push('scriptMenu_mainButton');
  4826. }
  4827. button.classList.add('scriptMenu_button', this.getButtonColor(color), ...classes);
  4828. button.title = title;
  4829. button.addEventListener('click', onClick);
  4830. main.appendChild(button);
  4831.  
  4832. const buttonText = document.createElement('div');
  4833. buttonText.classList.add('scriptMenu_buttonText');
  4834. buttonText.innerText = name;
  4835. button.appendChild(buttonText);
  4836.  
  4837. if (dot) {
  4838. const dotAtention = document.createElement('div');
  4839. dotAtention.classList.add('scriptMenu_dot');
  4840. dotAtention.title = dot;
  4841. button.appendChild(dotAtention);
  4842. }
  4843.  
  4844. this.buttons.push(button);
  4845. return button;
  4846. }
  4847.  
  4848. addCombinedButton(buttonList, main = this.mainMenu) {
  4849. const buttonGroup = document.createElement('div');
  4850. buttonGroup.classList.add('scriptMenu_buttonGroup');
  4851. let count = 0;
  4852.  
  4853. for (const btn of buttonList) {
  4854. btn.isCombine = true;
  4855. btn.classes ??= [];
  4856. if (count === 0) {
  4857. btn.classes.push('scriptMenu_combineButtonLeft');
  4858. } else if (count === buttonList.length - 1) {
  4859. btn.classes.push('scriptMenu_combineButtonRight');
  4860. } else {
  4861. btn.classes.push('scriptMenu_combineButtonCenter');
  4862. }
  4863. this.addButton(btn, buttonGroup);
  4864. count++;
  4865. }
  4866.  
  4867. const dotAtention = document.createElement('div');
  4868. dotAtention.classList.add('scriptMenu_dot');
  4869. buttonGroup.appendChild(dotAtention);
  4870.  
  4871. main.appendChild(buttonGroup);
  4872. return buttonGroup;
  4873. }
  4874.  
  4875. addCheckbox(label, title, main = this.mainMenu) {
  4876. const divCheckbox = document.createElement('div');
  4877. divCheckbox.classList.add('scriptMenu_divInput');
  4878. divCheckbox.title = title;
  4879. main.appendChild(divCheckbox);
  4880.  
  4881. const checkbox = document.createElement('input');
  4882. checkbox.type = 'checkbox';
  4883. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  4884. checkbox.classList.add('scriptMenu_checkbox');
  4885. divCheckbox.appendChild(checkbox);
  4886.  
  4887. const checkboxLabel = document.createElement('label');
  4888. checkboxLabel.innerText = label;
  4889. checkboxLabel.setAttribute('for', checkbox.id);
  4890. divCheckbox.appendChild(checkboxLabel);
  4891.  
  4892. this.checkboxes.push(checkbox);
  4893. return checkbox;
  4894. }
  4895.  
  4896. addInputText(title, placeholder, main = this.mainMenu) {
  4897. const divInputText = document.createElement('div');
  4898. divInputText.classList.add('scriptMenu_divInputText');
  4899. divInputText.title = title;
  4900. main.appendChild(divInputText);
  4901.  
  4902. const newInputText = document.createElement('input');
  4903. newInputText.type = 'text';
  4904. if (placeholder) {
  4905. newInputText.placeholder = placeholder;
  4906. }
  4907. newInputText.classList.add('scriptMenu_InputText');
  4908. divInputText.appendChild(newInputText);
  4909. return newInputText;
  4910. }
  4911.  
  4912. addDetails(summaryText, name = null) {
  4913. const details = document.createElement('details');
  4914. details.classList.add('scriptMenu_Details');
  4915. this.mainMenu.appendChild(details);
  4916.  
  4917. const summary = document.createElement('summary');
  4918. summary.classList.add('scriptMenu_Summary');
  4919. summary.innerText = summaryText;
  4920. if (name) {
  4921. details.open = this.option.showDetails[name] ?? false;
  4922. details.dataset.name = name;
  4923. details.addEventListener('toggle', () => {
  4924. this.option.showDetails[details.dataset.name] = details.open;
  4925. this.saveSaveOption();
  4926. });
  4927. }
  4928. details.appendChild(summary);
  4929.  
  4930. return details;
  4931. }
  4932.  
  4933. saveSaveOption() {
  4934. try {
  4935. localStorage.setItem('scriptMenu_saveOption', JSON.stringify(this.option));
  4936. } catch (e) {
  4937. console.log('¯\\_(ツ)_/¯');
  4938. }
  4939. }
  4940.  
  4941. loadSaveOption() {
  4942. let saveOption = null;
  4943. try {
  4944. saveOption = localStorage.getItem('scriptMenu_saveOption');
  4945. } catch (e) {
  4946. console.log('¯\\_(ツ)_/¯');
  4947. }
  4948.  
  4949. if (!saveOption) {
  4950. return {};
  4951. }
  4952.  
  4953. try {
  4954. saveOption = JSON.parse(saveOption);
  4955. } catch (e) {
  4956. return {};
  4957. }
  4958.  
  4959. return saveOption;
  4960. }
  4961. }
  4962.  
  4963. const scriptMenu = new ScriptMenu();
  4964.  
  4965. /**
  4966. * Пример использования
  4967. const scriptMenu = new ScriptMenu();
  4968. scriptMenu.init();
  4969. scriptMenu.addHeader('v1.508');
  4970. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  4971. scriptMenu.addButton({
  4972. text: 'Запуск!',
  4973. onClick: () => console.log('click'),
  4974. title: 'подсказака',
  4975. });
  4976. scriptMenu.addInputText('input подсказака');
  4977. */
  4978.  
  4979. /**
  4980. * Game Library
  4981. *
  4982. * Игровая библиотека
  4983. */
  4984. class Library {
  4985. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  4986.  
  4987. constructor() {
  4988. if (!Library.instance) {
  4989. Library.instance = this;
  4990. }
  4991.  
  4992. return Library.instance;
  4993. }
  4994.  
  4995. async load() {
  4996. try {
  4997. await this.getUrlLib();
  4998. console.log(this.defaultLibUrl);
  4999. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  5000. } catch (error) {
  5001. console.error('Не удалось загрузить библиотеку', error)
  5002. }
  5003. }
  5004.  
  5005. async getUrlLib() {
  5006. try {
  5007. const db = new Database('hw_cache', 'cache');
  5008. await db.open();
  5009. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  5010. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  5011. } catch(e) {}
  5012. }
  5013.  
  5014. getData(id) {
  5015. return this.data[id];
  5016. }
  5017.  
  5018. setData(data) {
  5019. this.data = data;
  5020. }
  5021. }
  5022.  
  5023. this.lib = new Library();
  5024. /**
  5025. * Database
  5026. *
  5027. * База данных
  5028. */
  5029. class Database {
  5030. constructor(dbName, storeName) {
  5031. this.dbName = dbName;
  5032. this.storeName = storeName;
  5033. this.db = null;
  5034. }
  5035.  
  5036. async open() {
  5037. return new Promise((resolve, reject) => {
  5038. const request = indexedDB.open(this.dbName);
  5039.  
  5040. request.onerror = () => {
  5041. reject(new Error(`Failed to open database ${this.dbName}`));
  5042. };
  5043.  
  5044. request.onsuccess = () => {
  5045. this.db = request.result;
  5046. resolve();
  5047. };
  5048.  
  5049. request.onupgradeneeded = (event) => {
  5050. const db = event.target.result;
  5051. if (!db.objectStoreNames.contains(this.storeName)) {
  5052. db.createObjectStore(this.storeName);
  5053. }
  5054. };
  5055. });
  5056. }
  5057.  
  5058. async set(key, value) {
  5059. return new Promise((resolve, reject) => {
  5060. const transaction = this.db.transaction([this.storeName], 'readwrite');
  5061. const store = transaction.objectStore(this.storeName);
  5062. const request = store.put(value, key);
  5063.  
  5064. request.onerror = () => {
  5065. reject(new Error(`Failed to save value with key ${key}`));
  5066. };
  5067.  
  5068. request.onsuccess = () => {
  5069. resolve();
  5070. };
  5071. });
  5072. }
  5073.  
  5074. async get(key, def) {
  5075. return new Promise((resolve, reject) => {
  5076. const transaction = this.db.transaction([this.storeName], 'readonly');
  5077. const store = transaction.objectStore(this.storeName);
  5078. const request = store.get(key);
  5079.  
  5080. request.onerror = () => {
  5081. resolve(def);
  5082. };
  5083.  
  5084. request.onsuccess = () => {
  5085. resolve(request.result);
  5086. };
  5087. });
  5088. }
  5089.  
  5090. async delete(key) {
  5091. return new Promise((resolve, reject) => {
  5092. const transaction = this.db.transaction([this.storeName], 'readwrite');
  5093. const store = transaction.objectStore(this.storeName);
  5094. const request = store.delete(key);
  5095.  
  5096. request.onerror = () => {
  5097. reject(new Error(`Failed to delete value with key ${key}`));
  5098. };
  5099.  
  5100. request.onsuccess = () => {
  5101. resolve();
  5102. };
  5103. });
  5104. }
  5105. }
  5106.  
  5107. /**
  5108. * Returns the stored value
  5109. *
  5110. * Возвращает сохраненное значение
  5111. */
  5112. function getSaveVal(saveName, def) {
  5113. const result = storage.get(saveName, def);
  5114. return result;
  5115. }
  5116. this.HWHFuncs.getSaveVal = getSaveVal;
  5117.  
  5118. /**
  5119. * Stores value
  5120. *
  5121. * Сохраняет значение
  5122. */
  5123. function setSaveVal(saveName, value) {
  5124. storage.set(saveName, value);
  5125. }
  5126. this.HWHFuncs.setSaveVal = setSaveVal;
  5127.  
  5128. /**
  5129. * Database initialization
  5130. *
  5131. * Инициализация базы данных
  5132. */
  5133. const db = new Database(GM_info.script.name, 'settings');
  5134.  
  5135. /**
  5136. * Data store
  5137. *
  5138. * Хранилище данных
  5139. */
  5140. const storage = {
  5141. userId: 0,
  5142. /**
  5143. * Default values
  5144. *
  5145. * Значения по умолчанию
  5146. */
  5147. values: [
  5148. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  5149. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  5150. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  5151. name: GM_info.script.name,
  5152. get: function (key, def) {
  5153. if (key in this.values) {
  5154. return this.values[key];
  5155. }
  5156. return def;
  5157. },
  5158. set: function (key, value) {
  5159. this.values[key] = value;
  5160. db.set(this.userId, this.values).catch(
  5161. e => null
  5162. );
  5163. localStorage[this.name + ':' + key] = value;
  5164. },
  5165. delete: function (key) {
  5166. delete this.values[key];
  5167. db.set(this.userId, this.values);
  5168. delete localStorage[this.name + ':' + key];
  5169. }
  5170. }
  5171.  
  5172. /**
  5173. * Returns all keys from localStorage that start with prefix (for migration)
  5174. *
  5175. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  5176. */
  5177. function getAllValuesStartingWith(prefix) {
  5178. const values = [];
  5179. for (let i = 0; i < localStorage.length; i++) {
  5180. const key = localStorage.key(i);
  5181. if (key.startsWith(prefix)) {
  5182. const val = localStorage.getItem(key);
  5183. const keyValue = key.split(':')[1];
  5184. values.push({ key: keyValue, val });
  5185. }
  5186. }
  5187. return values;
  5188. }
  5189.  
  5190. /**
  5191. * Opens or migrates to a database
  5192. *
  5193. * Открывает или мигрирует в базу данных
  5194. */
  5195. async function openOrMigrateDatabase(userId) {
  5196. storage.userId = userId;
  5197. try {
  5198. await db.open();
  5199. } catch(e) {
  5200. return;
  5201. }
  5202. let settings = await db.get(userId, false);
  5203.  
  5204. if (settings) {
  5205. storage.values = settings;
  5206. return;
  5207. }
  5208.  
  5209. const values = getAllValuesStartingWith(GM_info.script.name);
  5210. for (const value of values) {
  5211. let val = null;
  5212. try {
  5213. val = JSON.parse(value.val);
  5214. } catch {
  5215. break;
  5216. }
  5217. storage.values[value.key] = val;
  5218. }
  5219. await db.set(userId, storage.values);
  5220. }
  5221.  
  5222. class ZingerYWebsiteAPI {
  5223. /**
  5224. * Class for interaction with the API of the zingery.ru website
  5225. * Intended only for use with the HeroWarsHelper script:
  5226. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  5227. * Copyright ZingerY
  5228. */
  5229. url = 'https://zingery.ru/heroes/';
  5230. // YWJzb2x1dGVseSB1c2VsZXNzIGxpbmU=
  5231. constructor(urn, env, data = {}) {
  5232. this.urn = urn;
  5233. this.fd = {
  5234. now: Date.now(),
  5235. fp: this.constructor.toString().replaceAll(/\s/g, ''),
  5236. env: env.callee.toString().replaceAll(/\s/g, ''),
  5237. info: (({ name, version, author }) => [name, version, author])(GM_info.script),
  5238. ...data,
  5239. };
  5240. }
  5241.  
  5242. sign() {
  5243. return md5([...this.fd.info, ~(this.fd.now % 1e3), this.fd.fp].join('_'));
  5244. }
  5245.  
  5246. encode(data) {
  5247. return btoa(encodeURIComponent(JSON.stringify(data)));
  5248. }
  5249.  
  5250. decode(data) {
  5251. return JSON.parse(decodeURIComponent(atob(data)));
  5252. }
  5253.  
  5254. headers() {
  5255. return {
  5256. 'X-Request-Signature': this.sign(),
  5257. 'X-Script-Name': GM_info.script.name,
  5258. 'X-Script-Version': GM_info.script.version,
  5259. 'X-Script-Author': GM_info.script.author,
  5260. 'X-Script-ZingerY': 42,
  5261. };
  5262. }
  5263.  
  5264. async request() {
  5265. try {
  5266. const response = await fetch(this.url + this.urn, {
  5267. method: 'POST',
  5268. headers: this.headers(),
  5269. body: this.encode(this.fd),
  5270. });
  5271. const text = await response.text();
  5272. return this.decode(text);
  5273. } catch (e) {
  5274. console.error(e);
  5275. return [];
  5276. }
  5277. }
  5278. /**
  5279. * Класс для взаимодействия с API сайта zingery.ru
  5280. * Предназначен только для использования со скриптом HeroWarsHelper:
  5281. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  5282. * Copyright ZingerY
  5283. */
  5284. }
  5285.  
  5286. /**
  5287. * Sending expeditions
  5288. *
  5289. * Отправка экспедиций
  5290. */
  5291. function checkExpedition() {
  5292. const { Expedition } = HWHClasses;
  5293. return new Promise((resolve, reject) => {
  5294. const expedition = new Expedition(resolve, reject);
  5295. expedition.start();
  5296. });
  5297. }
  5298.  
  5299. class Expedition {
  5300. checkExpedInfo = {
  5301. calls: [
  5302. {
  5303. name: 'expeditionGet',
  5304. args: {},
  5305. ident: 'expeditionGet',
  5306. },
  5307. {
  5308. name: 'heroGetAll',
  5309. args: {},
  5310. ident: 'heroGetAll',
  5311. },
  5312. ],
  5313. };
  5314.  
  5315. constructor(resolve, reject) {
  5316. this.resolve = resolve;
  5317. this.reject = reject;
  5318. }
  5319.  
  5320. async start() {
  5321. const data = await Send(JSON.stringify(this.checkExpedInfo));
  5322.  
  5323. const expedInfo = data.results[0].result.response;
  5324. const dataHeroes = data.results[1].result.response;
  5325. const dataExped = { useHeroes: [], exped: [] };
  5326. const calls = [];
  5327.  
  5328. /**
  5329. * Adding expeditions to collect
  5330. * Добавляем экспедиции для сбора
  5331. */
  5332. let countGet = 0;
  5333. for (var n in expedInfo) {
  5334. const exped = expedInfo[n];
  5335. const dateNow = Date.now() / 1000;
  5336. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  5337. countGet++;
  5338. calls.push({
  5339. name: 'expeditionFarm',
  5340. args: { expeditionId: exped.id },
  5341. ident: 'expeditionFarm_' + exped.id,
  5342. });
  5343. } else {
  5344. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  5345. }
  5346. if (exped.status == 1) {
  5347. dataExped.exped.push({ id: exped.id, power: exped.power });
  5348. }
  5349. }
  5350. dataExped.exped = dataExped.exped.sort((a, b) => b.power - a.power);
  5351.  
  5352. /**
  5353. * Putting together a list of heroes
  5354. * Собираем список героев
  5355. */
  5356. const heroesArr = [];
  5357. for (let n in dataHeroes) {
  5358. const hero = dataHeroes[n];
  5359. if (hero.power > 0 && !dataExped.useHeroes.includes(hero.id)) {
  5360. let heroPower = hero.power;
  5361. // Лара Крофт * 3
  5362. if (hero.id == 63 && hero.color >= 16) {
  5363. heroPower *= 3;
  5364. }
  5365. heroesArr.push({ id: hero.id, power: heroPower });
  5366. }
  5367. }
  5368.  
  5369. /**
  5370. * Adding expeditions to send
  5371. * Добавляем экспедиции для отправки
  5372. */
  5373. let countSend = 0;
  5374. heroesArr.sort((a, b) => a.power - b.power);
  5375. for (const exped of dataExped.exped) {
  5376. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  5377. if (heroesIds && heroesIds.length > 4) {
  5378. for (let q in heroesArr) {
  5379. if (heroesIds.includes(heroesArr[q].id)) {
  5380. delete heroesArr[q];
  5381. }
  5382. }
  5383. countSend++;
  5384. calls.push({
  5385. name: 'expeditionSendHeroes',
  5386. args: {
  5387. expeditionId: exped.id,
  5388. heroes: heroesIds,
  5389. },
  5390. ident: 'expeditionSendHeroes_' + exped.id,
  5391. });
  5392. }
  5393. }
  5394.  
  5395. if (calls.length) {
  5396. await Send({ calls });
  5397. this.end(I18N('EXPEDITIONS_SENT', {countGet, countSend}));
  5398. return;
  5399. }
  5400.  
  5401. this.end(I18N('EXPEDITIONS_NOTHING'));
  5402. }
  5403.  
  5404. /**
  5405. * Selection of heroes for expeditions
  5406. *
  5407. * Подбор героев для экспедиций
  5408. */
  5409. selectionHeroes(heroes, power) {
  5410. const resultHeroers = [];
  5411. const heroesIds = [];
  5412. for (let q = 0; q < 5; q++) {
  5413. for (let i in heroes) {
  5414. let hero = heroes[i];
  5415. if (heroesIds.includes(hero.id)) {
  5416. continue;
  5417. }
  5418.  
  5419. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5420. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  5421. if (hero.power > need) {
  5422. resultHeroers.push(hero);
  5423. heroesIds.push(hero.id);
  5424. break;
  5425. }
  5426. }
  5427. }
  5428.  
  5429. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5430. if (summ < power) {
  5431. return false;
  5432. }
  5433. return heroesIds;
  5434. }
  5435.  
  5436. /**
  5437. * Ends expedition script
  5438. *
  5439. * Завершает скрипт экспедиции
  5440. */
  5441. end(msg) {
  5442. setProgress(msg, true);
  5443. this.resolve();
  5444. }
  5445. }
  5446.  
  5447. this.HWHClasses.Expedition = Expedition;
  5448.  
  5449. /**
  5450. * Walkthrough of the dungeon
  5451. *
  5452. * Прохождение подземелья
  5453. */
  5454. function testDungeon() {
  5455. const { executeDungeon } = HWHClasses;
  5456. return new Promise((resolve, reject) => {
  5457. const dung = new executeDungeon(resolve, reject);
  5458. const titanit = getInput('countTitanit');
  5459. dung.start(titanit);
  5460. });
  5461. }
  5462.  
  5463. /**
  5464. * Walkthrough of the dungeon
  5465. *
  5466. * Прохождение подземелья
  5467. */
  5468. function executeDungeon(resolve, reject) {
  5469. dungeonActivity = 0;
  5470. maxDungeonActivity = 150;
  5471.  
  5472. titanGetAll = [];
  5473.  
  5474. teams = {
  5475. heroes: [],
  5476. earth: [],
  5477. fire: [],
  5478. neutral: [],
  5479. water: [],
  5480. }
  5481.  
  5482. titanStats = [];
  5483.  
  5484. titansStates = {};
  5485.  
  5486. let talentMsg = '';
  5487. let talentMsgReward = '';
  5488.  
  5489. callsExecuteDungeon = {
  5490. calls: [{
  5491. name: "dungeonGetInfo",
  5492. args: {},
  5493. ident: "dungeonGetInfo"
  5494. }, {
  5495. name: "teamGetAll",
  5496. args: {},
  5497. ident: "teamGetAll"
  5498. }, {
  5499. name: "teamGetFavor",
  5500. args: {},
  5501. ident: "teamGetFavor"
  5502. }, {
  5503. name: "clanGetInfo",
  5504. args: {},
  5505. ident: "clanGetInfo"
  5506. }, {
  5507. name: "titanGetAll",
  5508. args: {},
  5509. ident: "titanGetAll"
  5510. }, {
  5511. name: "inventoryGet",
  5512. args: {},
  5513. ident: "inventoryGet"
  5514. }]
  5515. }
  5516.  
  5517. this.start = function(titanit) {
  5518. maxDungeonActivity = titanit || getInput('countTitanit');
  5519. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  5520. }
  5521.  
  5522. /**
  5523. * Getting data on the dungeon
  5524. *
  5525. * Получаем данные по подземелью
  5526. */
  5527. function startDungeon(e) {
  5528. res = e.results;
  5529. dungeonGetInfo = res[0].result.response;
  5530. if (!dungeonGetInfo) {
  5531. endDungeon('noDungeon', res);
  5532. return;
  5533. }
  5534. teamGetAll = res[1].result.response;
  5535. teamGetFavor = res[2].result.response;
  5536. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  5537. titanGetAll = Object.values(res[4].result.response);
  5538. countPredictionCard = res[5].result.response.consumable[81];
  5539.  
  5540. teams.hero = {
  5541. favor: teamGetFavor.dungeon_hero,
  5542. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  5543. teamNum: 0,
  5544. }
  5545. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  5546. if (heroPet) {
  5547. teams.hero.pet = heroPet;
  5548. }
  5549.  
  5550. teams.neutral = {
  5551. favor: {},
  5552. heroes: getTitanTeam(titanGetAll, 'neutral'),
  5553. teamNum: 0,
  5554. };
  5555. teams.water = {
  5556. favor: {},
  5557. heroes: getTitanTeam(titanGetAll, 'water'),
  5558. teamNum: 0,
  5559. };
  5560. teams.fire = {
  5561. favor: {},
  5562. heroes: getTitanTeam(titanGetAll, 'fire'),
  5563. teamNum: 0,
  5564. };
  5565. teams.earth = {
  5566. favor: {},
  5567. heroes: getTitanTeam(titanGetAll, 'earth'),
  5568. teamNum: 0,
  5569. };
  5570.  
  5571.  
  5572. checkFloor(dungeonGetInfo);
  5573. }
  5574.  
  5575. function getTitanTeam(titans, type) {
  5576. switch (type) {
  5577. case 'neutral':
  5578. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5579. case 'water':
  5580. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  5581. case 'fire':
  5582. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  5583. case 'earth':
  5584. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  5585. }
  5586. }
  5587.  
  5588. function getNeutralTeam() {
  5589. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5590. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5591. }
  5592.  
  5593. function fixTitanTeam(titans) {
  5594. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  5595. return titans;
  5596. }
  5597.  
  5598. /**
  5599. * Checking the floor
  5600. *
  5601. * Проверяем этаж
  5602. */
  5603. async function checkFloor(dungeonInfo) {
  5604. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  5605. saveProgress();
  5606. return;
  5607. }
  5608. checkTalent(dungeonInfo);
  5609. // console.log(dungeonInfo, dungeonActivity);
  5610. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5611. if (dungeonActivity >= maxDungeonActivity) {
  5612. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  5613. return;
  5614. }
  5615. titansStates = dungeonInfo.states.titans;
  5616. titanStats = titanObjToArray(titansStates);
  5617. const floorChoices = dungeonInfo.floor.userData;
  5618. const floorType = dungeonInfo.floorType;
  5619. //const primeElement = dungeonInfo.elements.prime;
  5620. if (floorType == "battle") {
  5621. const calls = [];
  5622. for (let teamNum in floorChoices) {
  5623. attackerType = floorChoices[teamNum].attackerType;
  5624. const args = fixTitanTeam(teams[attackerType]);
  5625. if (attackerType == 'neutral') {
  5626. args.heroes = getNeutralTeam();
  5627. }
  5628. if (!args.heroes.length) {
  5629. continue;
  5630. }
  5631. args.teamNum = teamNum;
  5632. calls.push({
  5633. name: "dungeonStartBattle",
  5634. args,
  5635. ident: "body_" + teamNum
  5636. })
  5637. }
  5638. if (!calls.length) {
  5639. endDungeon('endDungeon', 'All Dead');
  5640. return;
  5641. }
  5642. const battleDatas = await Send(JSON.stringify({ calls }))
  5643. .then(e => e.results.map(n => n.result.response))
  5644. const battleResults = [];
  5645. for (n in battleDatas) {
  5646. battleData = battleDatas[n]
  5647. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5648. battleResults.push(await Calc(battleData).then(result => {
  5649. result.teamNum = n;
  5650. result.attackerType = floorChoices[n].attackerType;
  5651. return result;
  5652. }));
  5653. }
  5654. processingPromises(battleResults)
  5655. }
  5656. }
  5657.  
  5658. async function checkTalent(dungeonInfo) {
  5659. const talent = dungeonInfo.talent;
  5660. if (!talent) {
  5661. return;
  5662. }
  5663. const dungeonFloor = +dungeonInfo.floorNumber;
  5664. const talentFloor = +talent.floorRandValue;
  5665. let doorsAmount = 3 - talent.conditions.doorsAmount;
  5666.  
  5667. if (dungeonFloor === talentFloor && (!doorsAmount || !talent.conditions?.farmedDoors[dungeonFloor])) {
  5668. const reward = await Send({
  5669. calls: [
  5670. { name: 'heroTalent_getReward', args: { talentType: 'tmntDungeonTalent', reroll: false }, ident: 'group_0_body' },
  5671. { name: 'heroTalent_farmReward', args: { talentType: 'tmntDungeonTalent' }, ident: 'group_1_body' },
  5672. ],
  5673. }).then((e) => e.results[0].result.response);
  5674. const type = Object.keys(reward).pop();
  5675. const itemId = Object.keys(reward[type]).pop();
  5676. const count = reward[type][itemId];
  5677. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  5678. talentMsgReward += `<br> ${count} ${itemName}`;
  5679. doorsAmount++;
  5680. }
  5681. talentMsg = `<br>TMNT Talent: ${doorsAmount}/3 ${talentMsgReward}<br>`;
  5682. }
  5683.  
  5684. function processingPromises(results) {
  5685. let selectBattle = results[0];
  5686. if (results.length < 2) {
  5687. // console.log(selectBattle);
  5688. if (!selectBattle.result.win) {
  5689. endDungeon('dungeonEndBattle\n', selectBattle);
  5690. return;
  5691. }
  5692. endBattle(selectBattle);
  5693. return;
  5694. }
  5695.  
  5696. selectBattle = false;
  5697. let bestState = -1000;
  5698. for (const result of results) {
  5699. const recovery = getState(result);
  5700. if (recovery > bestState) {
  5701. bestState = recovery;
  5702. selectBattle = result
  5703. }
  5704. }
  5705. // console.log(selectBattle.teamNum, results);
  5706. if (!selectBattle || bestState <= -1000) {
  5707. endDungeon('dungeonEndBattle\n', results);
  5708. return;
  5709. }
  5710.  
  5711. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  5712. .then(endBattle);
  5713. }
  5714.  
  5715. /**
  5716. * Let's start the fight
  5717. *
  5718. * Начинаем бой
  5719. */
  5720. function startBattle(teamNum, attackerType) {
  5721. return new Promise(function (resolve, reject) {
  5722. args = fixTitanTeam(teams[attackerType]);
  5723. args.teamNum = teamNum;
  5724. if (attackerType == 'neutral') {
  5725. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5726. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5727. }
  5728. startBattleCall = {
  5729. calls: [{
  5730. name: "dungeonStartBattle",
  5731. args,
  5732. ident: "body"
  5733. }]
  5734. }
  5735. send(JSON.stringify(startBattleCall), resultBattle, {
  5736. resolve,
  5737. teamNum,
  5738. attackerType
  5739. });
  5740. });
  5741. }
  5742. /**
  5743. * Returns the result of the battle in a promise
  5744. *
  5745. * Возращает резульат боя в промис
  5746. */
  5747. function resultBattle(resultBattles, args) {
  5748. battleData = resultBattles.results[0].result.response;
  5749. battleType = "get_tower";
  5750. if (battleData.type == "dungeon_titan") {
  5751. battleType = "get_titan";
  5752. }
  5753. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5754. BattleCalc(battleData, battleType, function (result) {
  5755. result.teamNum = args.teamNum;
  5756. result.attackerType = args.attackerType;
  5757. args.resolve(result);
  5758. });
  5759. }
  5760. /**
  5761. * Finishing the fight
  5762. *
  5763. * Заканчиваем бой
  5764. */
  5765. async function endBattle(battleInfo) {
  5766. if (battleInfo.result.win) {
  5767. const args = {
  5768. result: battleInfo.result,
  5769. progress: battleInfo.progress,
  5770. }
  5771. if (countPredictionCard > 0) {
  5772. args.isRaid = true;
  5773. } else {
  5774. const timer = getTimer(battleInfo.battleTime);
  5775. console.log(timer);
  5776. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5777. }
  5778. const calls = [{
  5779. name: "dungeonEndBattle",
  5780. args,
  5781. ident: "body"
  5782. }];
  5783. lastDungeonBattleData = null;
  5784. send(JSON.stringify({ calls }), resultEndBattle);
  5785. } else {
  5786. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  5787. }
  5788. }
  5789.  
  5790. /**
  5791. * Getting and processing battle results
  5792. *
  5793. * Получаем и обрабатываем результаты боя
  5794. */
  5795. function resultEndBattle(e) {
  5796. if ('error' in e) {
  5797. popup.confirm(I18N('ERROR_MSG', {
  5798. name: e.error.name,
  5799. description: e.error.description,
  5800. }));
  5801. endDungeon('errorRequest', e);
  5802. return;
  5803. }
  5804. battleResult = e.results[0].result.response;
  5805. if ('error' in battleResult) {
  5806. endDungeon('errorBattleResult', battleResult);
  5807. return;
  5808. }
  5809. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  5810. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  5811. checkFloor(dungeonGetInfo);
  5812. }
  5813.  
  5814. /**
  5815. * Returns the coefficient of condition of the
  5816. * difference in titanium before and after the battle
  5817. *
  5818. * Возвращает коэффициент состояния титанов после боя
  5819. */
  5820. function getState(result) {
  5821. if (!result.result.win) {
  5822. return -1000;
  5823. }
  5824.  
  5825. let beforeSumFactor = 0;
  5826. const beforeTitans = result.battleData.attackers;
  5827. for (let titanId in beforeTitans) {
  5828. const titan = beforeTitans[titanId];
  5829. const state = titan.state;
  5830. let factor = 1;
  5831. if (state) {
  5832. const hp = state.hp / titan.hp;
  5833. const energy = state.energy / 1e3;
  5834. factor = hp + energy / 20
  5835. }
  5836. beforeSumFactor += factor;
  5837. }
  5838.  
  5839. let afterSumFactor = 0;
  5840. const afterTitans = result.progress[0].attackers.heroes;
  5841. for (let titanId in afterTitans) {
  5842. const titan = afterTitans[titanId];
  5843. const hp = titan.hp / beforeTitans[titanId].hp;
  5844. const energy = titan.energy / 1e3;
  5845. const factor = hp + energy / 20;
  5846. afterSumFactor += factor;
  5847. }
  5848. return afterSumFactor - beforeSumFactor;
  5849. }
  5850.  
  5851. /**
  5852. * Converts an object with IDs to an array with IDs
  5853. *
  5854. * Преобразует объект с идетификаторами в массив с идетификаторами
  5855. */
  5856. function titanObjToArray(obj) {
  5857. let titans = [];
  5858. for (let id in obj) {
  5859. obj[id].id = id;
  5860. titans.push(obj[id]);
  5861. }
  5862. return titans;
  5863. }
  5864.  
  5865. function saveProgress() {
  5866. let saveProgressCall = {
  5867. calls: [{
  5868. name: "dungeonSaveProgress",
  5869. args: {},
  5870. ident: "body"
  5871. }]
  5872. }
  5873. send(JSON.stringify(saveProgressCall), resultEndBattle);
  5874. }
  5875.  
  5876. function endDungeon(reason, info) {
  5877. console.warn(reason, info);
  5878. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  5879. resolve();
  5880. }
  5881. }
  5882.  
  5883. this.HWHClasses.executeDungeon = executeDungeon;
  5884.  
  5885. /**
  5886. * Passing the tower
  5887. *
  5888. * Прохождение башни
  5889. */
  5890. function testTower() {
  5891. const { executeTower } = HWHClasses;
  5892. return new Promise((resolve, reject) => {
  5893. tower = new executeTower(resolve, reject);
  5894. tower.start();
  5895. });
  5896. }
  5897.  
  5898. /**
  5899. * Passing the tower
  5900. *
  5901. * Прохождение башни
  5902. */
  5903. function executeTower(resolve, reject) {
  5904. lastTowerInfo = {};
  5905.  
  5906. scullCoin = 0;
  5907.  
  5908. heroGetAll = [];
  5909.  
  5910. heroesStates = {};
  5911.  
  5912. argsBattle = {
  5913. heroes: [],
  5914. favor: {},
  5915. };
  5916.  
  5917. callsExecuteTower = {
  5918. calls: [{
  5919. name: "towerGetInfo",
  5920. args: {},
  5921. ident: "towerGetInfo"
  5922. }, {
  5923. name: "teamGetAll",
  5924. args: {},
  5925. ident: "teamGetAll"
  5926. }, {
  5927. name: "teamGetFavor",
  5928. args: {},
  5929. ident: "teamGetFavor"
  5930. }, {
  5931. name: "inventoryGet",
  5932. args: {},
  5933. ident: "inventoryGet"
  5934. }, {
  5935. name: "heroGetAll",
  5936. args: {},
  5937. ident: "heroGetAll"
  5938. }]
  5939. }
  5940.  
  5941. buffIds = [
  5942. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  5943. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  5944. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  5945. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  5946. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  5947. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  5948. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  5949. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  5950. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  5951. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5952. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  5953. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5954. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  5955. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  5956. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  5957. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  5958. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  5959. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5960. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5961. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  5962. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  5963. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  5964. ]
  5965.  
  5966. this.start = function () {
  5967. send(JSON.stringify(callsExecuteTower), startTower);
  5968. }
  5969.  
  5970. /**
  5971. * Getting data on the Tower
  5972. *
  5973. * Получаем данные по башне
  5974. */
  5975. function startTower(e) {
  5976. res = e.results;
  5977. towerGetInfo = res[0].result.response;
  5978. if (!towerGetInfo) {
  5979. endTower('noTower', res);
  5980. return;
  5981. }
  5982. teamGetAll = res[1].result.response;
  5983. teamGetFavor = res[2].result.response;
  5984. inventoryGet = res[3].result.response;
  5985. heroGetAll = Object.values(res[4].result.response);
  5986.  
  5987. scullCoin = inventoryGet.coin[7] ?? 0;
  5988.  
  5989. argsBattle.favor = teamGetFavor.tower;
  5990. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5991. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  5992. if (pet) {
  5993. argsBattle.pet = pet;
  5994. }
  5995.  
  5996. checkFloor(towerGetInfo);
  5997. }
  5998.  
  5999. function fixHeroesTeam(argsBattle) {
  6000. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  6001. if (fixHeroes.length < 5) {
  6002. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  6003. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  6004. Object.keys(argsBattle.favor).forEach(e => {
  6005. if (!fixHeroes.includes(+e)) {
  6006. delete argsBattle.favor[e];
  6007. }
  6008. })
  6009. }
  6010. argsBattle.heroes = fixHeroes;
  6011. return argsBattle;
  6012. }
  6013.  
  6014. /**
  6015. * Check the floor
  6016. *
  6017. * Проверяем этаж
  6018. */
  6019. function checkFloor(towerInfo) {
  6020. lastTowerInfo = towerInfo;
  6021. maySkipFloor = +towerInfo.maySkipFloor;
  6022. floorNumber = +towerInfo.floorNumber;
  6023. heroesStates = towerInfo.states.heroes;
  6024. floorInfo = towerInfo.floor;
  6025.  
  6026. /**
  6027. * Is there at least one chest open on the floor
  6028. * Открыт ли на этаже хоть один сундук
  6029. */
  6030. isOpenChest = false;
  6031. if (towerInfo.floorType == "chest") {
  6032. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  6033. }
  6034.  
  6035. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  6036. if (floorNumber > 49) {
  6037. if (isOpenChest) {
  6038. endTower('alreadyOpenChest 50 floor', floorNumber);
  6039. return;
  6040. }
  6041. }
  6042. /**
  6043. * If the chest is open and you can skip floors, then move on
  6044. * Если сундук открыт и можно скипать этажи, то переходим дальше
  6045. */
  6046. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  6047. if (floorNumber == 1) {
  6048. fullSkipTower();
  6049. return;
  6050. }
  6051. if (isOpenChest) {
  6052. nextOpenChest(floorNumber);
  6053. } else {
  6054. nextChestOpen(floorNumber);
  6055. }
  6056. return;
  6057. }
  6058.  
  6059. // console.log(towerInfo, scullCoin);
  6060. switch (towerInfo.floorType) {
  6061. case "battle":
  6062. if (floorNumber <= maySkipFloor) {
  6063. skipFloor();
  6064. return;
  6065. }
  6066. if (floorInfo.state == 2) {
  6067. nextFloor();
  6068. return;
  6069. }
  6070. startBattle().then(endBattle);
  6071. return;
  6072. case "buff":
  6073. checkBuff(towerInfo);
  6074. return;
  6075. case "chest":
  6076. openChest(floorNumber);
  6077. return;
  6078. default:
  6079. console.log('!', towerInfo.floorType, towerInfo);
  6080. break;
  6081. }
  6082. }
  6083.  
  6084. /**
  6085. * Let's start the fight
  6086. *
  6087. * Начинаем бой
  6088. */
  6089. function startBattle() {
  6090. return new Promise(function (resolve, reject) {
  6091. towerStartBattle = {
  6092. calls: [{
  6093. name: "towerStartBattle",
  6094. args: fixHeroesTeam(argsBattle),
  6095. ident: "body"
  6096. }]
  6097. }
  6098. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  6099. });
  6100. }
  6101. /**
  6102. * Returns the result of the battle in a promise
  6103. *
  6104. * Возращает резульат боя в промис
  6105. */
  6106. function resultBattle(resultBattles, resolve) {
  6107. battleData = resultBattles.results[0].result.response;
  6108. battleType = "get_tower";
  6109. BattleCalc(battleData, battleType, function (result) {
  6110. resolve(result);
  6111. });
  6112. }
  6113. /**
  6114. * Finishing the fight
  6115. *
  6116. * Заканчиваем бой
  6117. */
  6118. function endBattle(battleInfo) {
  6119. if (battleInfo.result.stars >= 3) {
  6120. endBattleCall = {
  6121. calls: [{
  6122. name: "towerEndBattle",
  6123. args: {
  6124. result: battleInfo.result,
  6125. progress: battleInfo.progress,
  6126. },
  6127. ident: "body"
  6128. }]
  6129. }
  6130. send(JSON.stringify(endBattleCall), resultEndBattle);
  6131. } else {
  6132. endTower('towerEndBattle win: false\n', battleInfo);
  6133. }
  6134. }
  6135.  
  6136. /**
  6137. * Getting and processing battle results
  6138. *
  6139. * Получаем и обрабатываем результаты боя
  6140. */
  6141. function resultEndBattle(e) {
  6142. battleResult = e.results[0].result.response;
  6143. if ('error' in battleResult) {
  6144. endTower('errorBattleResult', battleResult);
  6145. return;
  6146. }
  6147. if ('reward' in battleResult) {
  6148. scullCoin += battleResult.reward?.coin[7] ?? 0;
  6149. }
  6150. nextFloor();
  6151. }
  6152.  
  6153. function nextFloor() {
  6154. nextFloorCall = {
  6155. calls: [{
  6156. name: "towerNextFloor",
  6157. args: {},
  6158. ident: "body"
  6159. }]
  6160. }
  6161. send(JSON.stringify(nextFloorCall), checkDataFloor);
  6162. }
  6163.  
  6164. function openChest(floorNumber) {
  6165. floorNumber = floorNumber || 0;
  6166. openChestCall = {
  6167. calls: [{
  6168. name: "towerOpenChest",
  6169. args: {
  6170. num: 2
  6171. },
  6172. ident: "body"
  6173. }]
  6174. }
  6175. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  6176. }
  6177.  
  6178. function lastChest() {
  6179. endTower('openChest 50 floor', floorNumber);
  6180. }
  6181.  
  6182. function skipFloor() {
  6183. skipFloorCall = {
  6184. calls: [{
  6185. name: "towerSkipFloor",
  6186. args: {},
  6187. ident: "body"
  6188. }]
  6189. }
  6190. send(JSON.stringify(skipFloorCall), checkDataFloor);
  6191. }
  6192.  
  6193. function checkBuff(towerInfo) {
  6194. buffArr = towerInfo.floor;
  6195. promises = [];
  6196. for (let buff of buffArr) {
  6197. buffInfo = buffIds[buff.id];
  6198. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  6199. scullCoin -= buffInfo.cost;
  6200. promises.push(buyBuff(buff.id));
  6201. }
  6202. }
  6203. Promise.all(promises).then(nextFloor);
  6204. }
  6205.  
  6206. function buyBuff(buffId) {
  6207. return new Promise(function (resolve, reject) {
  6208. buyBuffCall = {
  6209. calls: [{
  6210. name: "towerBuyBuff",
  6211. args: {
  6212. buffId
  6213. },
  6214. ident: "body"
  6215. }]
  6216. }
  6217. send(JSON.stringify(buyBuffCall), resolve);
  6218. });
  6219. }
  6220.  
  6221. function checkDataFloor(result) {
  6222. towerInfo = result.results[0].result.response;
  6223. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  6224. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  6225. }
  6226. if ('tower' in towerInfo) {
  6227. towerInfo = towerInfo.tower;
  6228. }
  6229. if ('skullReward' in towerInfo) {
  6230. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6231. }
  6232. checkFloor(towerInfo);
  6233. }
  6234. /**
  6235. * Getting tower rewards
  6236. *
  6237. * Получаем награды башни
  6238. */
  6239. function farmTowerRewards(reason) {
  6240. let { pointRewards, points } = lastTowerInfo;
  6241. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  6242. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  6243. if (!farmPoints.length) {
  6244. return;
  6245. }
  6246. let farmTowerRewardsCall = {
  6247. calls: [{
  6248. name: "tower_farmPointRewards",
  6249. args: {
  6250. points: farmPoints
  6251. },
  6252. ident: "tower_farmPointRewards"
  6253. }]
  6254. }
  6255.  
  6256. if (scullCoin > 0) {
  6257. farmTowerRewardsCall.calls.push({
  6258. name: "tower_farmSkullReward",
  6259. args: {},
  6260. ident: "tower_farmSkullReward"
  6261. });
  6262. }
  6263.  
  6264. send(JSON.stringify(farmTowerRewardsCall), () => { });
  6265. }
  6266.  
  6267. function fullSkipTower() {
  6268. /**
  6269. * Next chest
  6270. *
  6271. * Следующий сундук
  6272. */
  6273. function nextChest(n) {
  6274. return {
  6275. name: "towerNextChest",
  6276. args: {},
  6277. ident: "group_" + n + "_body"
  6278. }
  6279. }
  6280. /**
  6281. * Open chest
  6282. *
  6283. * Открыть сундук
  6284. */
  6285. function openChest(n) {
  6286. return {
  6287. name: "towerOpenChest",
  6288. args: {
  6289. "num": 2
  6290. },
  6291. ident: "group_" + n + "_body"
  6292. }
  6293. }
  6294.  
  6295. const fullSkipTowerCall = {
  6296. calls: []
  6297. }
  6298.  
  6299. let n = 0;
  6300. for (let i = 0; i < 15; i++) {
  6301. // 15 сундуков
  6302. fullSkipTowerCall.calls.push(nextChest(++n));
  6303. fullSkipTowerCall.calls.push(openChest(++n));
  6304. // +5 сундуков, 250 изюма // towerOpenChest
  6305. // if (i < 5) {
  6306. // fullSkipTowerCall.calls.push(openChest(++n, 2));
  6307. // }
  6308. }
  6309.  
  6310. fullSkipTowerCall.calls.push({
  6311. name: 'towerGetInfo',
  6312. args: {},
  6313. ident: 'group_' + ++n + '_body',
  6314. });
  6315.  
  6316. send(JSON.stringify(fullSkipTowerCall), data => {
  6317. for (const r of data.results) {
  6318. const towerInfo = r?.result?.response;
  6319. if (towerInfo && 'skullReward' in towerInfo) {
  6320. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6321. }
  6322. }
  6323. data.results[0] = data.results[data.results.length - 1];
  6324. checkDataFloor(data);
  6325. });
  6326. }
  6327.  
  6328. function nextChestOpen(floorNumber) {
  6329. const calls = [{
  6330. name: "towerOpenChest",
  6331. args: {
  6332. num: 2
  6333. },
  6334. ident: "towerOpenChest"
  6335. }];
  6336.  
  6337. Send(JSON.stringify({ calls })).then(e => {
  6338. nextOpenChest(floorNumber);
  6339. });
  6340. }
  6341.  
  6342. function nextOpenChest(floorNumber) {
  6343. if (floorNumber > 49) {
  6344. endTower('openChest 50 floor', floorNumber);
  6345. return;
  6346. }
  6347.  
  6348. let nextOpenChestCall = {
  6349. calls: [{
  6350. name: "towerNextChest",
  6351. args: {},
  6352. ident: "towerNextChest"
  6353. }, {
  6354. name: "towerOpenChest",
  6355. args: {
  6356. num: 2
  6357. },
  6358. ident: "towerOpenChest"
  6359. }]
  6360. }
  6361. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  6362. }
  6363.  
  6364. function endTower(reason, info) {
  6365. console.log(reason, info);
  6366. if (reason != 'noTower') {
  6367. farmTowerRewards(reason);
  6368. }
  6369. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  6370. resolve();
  6371. }
  6372. }
  6373.  
  6374. this.HWHClasses.executeTower = executeTower;
  6375.  
  6376. /**
  6377. * Passage of the arena of the titans
  6378. *
  6379. * Прохождение арены титанов
  6380. */
  6381. function testTitanArena() {
  6382. const { executeTitanArena } = HWHClasses;
  6383. return new Promise((resolve, reject) => {
  6384. titAren = new executeTitanArena(resolve, reject);
  6385. titAren.start();
  6386. });
  6387. }
  6388.  
  6389. /**
  6390. * Passage of the arena of the titans
  6391. *
  6392. * Прохождение арены титанов
  6393. */
  6394. function executeTitanArena(resolve, reject) {
  6395. let titan_arena = [];
  6396. let finishListBattle = [];
  6397. /**
  6398. * ID of the current batch
  6399. *
  6400. * Идетификатор текущей пачки
  6401. */
  6402. let currentRival = 0;
  6403. /**
  6404. * Number of attempts to finish off the pack
  6405. *
  6406. * Количество попыток добития пачки
  6407. */
  6408. let attempts = 0;
  6409. /**
  6410. * Was there an attempt to finish off the current shooting range
  6411. *
  6412. * Была ли попытка добития текущего тира
  6413. */
  6414. let isCheckCurrentTier = false;
  6415. /**
  6416. * Current shooting range
  6417. *
  6418. * Текущий тир
  6419. */
  6420. let currTier = 0;
  6421. /**
  6422. * Number of battles on the current dash
  6423. *
  6424. * Количество битв на текущем тире
  6425. */
  6426. let countRivalsTier = 0;
  6427.  
  6428. let callsStart = {
  6429. calls: [{
  6430. name: "titanArenaGetStatus",
  6431. args: {},
  6432. ident: "titanArenaGetStatus"
  6433. }, {
  6434. name: "teamGetAll",
  6435. args: {},
  6436. ident: "teamGetAll"
  6437. }]
  6438. }
  6439.  
  6440. this.start = function () {
  6441. send(JSON.stringify(callsStart), startTitanArena);
  6442. }
  6443.  
  6444. function startTitanArena(data) {
  6445. let titanArena = data.results[0].result.response;
  6446. if (titanArena.status == 'disabled') {
  6447. endTitanArena('disabled', titanArena);
  6448. return;
  6449. }
  6450.  
  6451. let teamGetAll = data.results[1].result.response;
  6452. titan_arena = teamGetAll.titan_arena;
  6453.  
  6454. checkTier(titanArena)
  6455. }
  6456.  
  6457. function checkTier(titanArena) {
  6458. if (titanArena.status == "peace_time") {
  6459. endTitanArena('Peace_time', titanArena);
  6460. return;
  6461. }
  6462. currTier = titanArena.tier;
  6463. if (currTier) {
  6464. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  6465. }
  6466.  
  6467. if (titanArena.status == "completed_tier") {
  6468. titanArenaCompleteTier();
  6469. return;
  6470. }
  6471. /**
  6472. * Checking for the possibility of a raid
  6473. * Проверка на возможность рейда
  6474. */
  6475. if (titanArena.canRaid) {
  6476. titanArenaStartRaid();
  6477. return;
  6478. }
  6479. /**
  6480. * Check was an attempt to achieve the current shooting range
  6481. * Проверка была ли попытка добития текущего тира
  6482. */
  6483. if (!isCheckCurrentTier) {
  6484. checkRivals(titanArena.rivals);
  6485. return;
  6486. }
  6487.  
  6488. endTitanArena('Done or not canRaid', titanArena);
  6489. }
  6490. /**
  6491. * Submit dash information for verification
  6492. *
  6493. * Отправка информации о тире на проверку
  6494. */
  6495. function checkResultInfo(data) {
  6496. let titanArena = data.results[0].result.response;
  6497. checkTier(titanArena);
  6498. }
  6499. /**
  6500. * Finish the current tier
  6501. *
  6502. * Завершить текущий тир
  6503. */
  6504. function titanArenaCompleteTier() {
  6505. isCheckCurrentTier = false;
  6506. let calls = [{
  6507. name: "titanArenaCompleteTier",
  6508. args: {},
  6509. ident: "body"
  6510. }];
  6511. send(JSON.stringify({calls}), checkResultInfo);
  6512. }
  6513. /**
  6514. * Gathering points to be completed
  6515. *
  6516. * Собираем точки которые нужно добить
  6517. */
  6518. function checkRivals(rivals) {
  6519. finishListBattle = [];
  6520. for (let n in rivals) {
  6521. if (rivals[n].attackScore < 250) {
  6522. finishListBattle.push(n);
  6523. }
  6524. }
  6525. console.log('checkRivals', finishListBattle);
  6526. countRivalsTier = finishListBattle.length;
  6527. roundRivals();
  6528. }
  6529. /**
  6530. * Selecting the next point to finish off
  6531. *
  6532. * Выбор следующей точки для добития
  6533. */
  6534. function roundRivals() {
  6535. let countRivals = finishListBattle.length;
  6536. if (!countRivals) {
  6537. /**
  6538. * Whole range checked
  6539. *
  6540. * Весь тир проверен
  6541. */
  6542. isCheckCurrentTier = true;
  6543. titanArenaGetStatus();
  6544. return;
  6545. }
  6546. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  6547. currentRival = finishListBattle.pop();
  6548. attempts = +currentRival;
  6549. // console.log('roundRivals', currentRival);
  6550. titanArenaStartBattle(currentRival);
  6551. }
  6552. /**
  6553. * The start of a solo battle
  6554. *
  6555. * Начало одиночной битвы
  6556. */
  6557. function titanArenaStartBattle(rivalId) {
  6558. let calls = [{
  6559. name: "titanArenaStartBattle",
  6560. args: {
  6561. rivalId: rivalId,
  6562. titans: titan_arena
  6563. },
  6564. ident: "body"
  6565. }];
  6566. send(JSON.stringify({calls}), calcResult);
  6567. }
  6568. /**
  6569. * Calculation of the results of the battle
  6570. *
  6571. * Расчет результатов боя
  6572. */
  6573. function calcResult(data) {
  6574. let battlesInfo = data.results[0].result.response.battle;
  6575. /**
  6576. * If attempts are equal to the current battle number we make
  6577. * Если попытки равны номеру текущего боя делаем прерасчет
  6578. */
  6579. if (attempts == currentRival) {
  6580. preCalcBattle(battlesInfo);
  6581. return;
  6582. }
  6583. /**
  6584. * If there are still attempts, we calculate a new battle
  6585. * Если попытки еще есть делаем расчет нового боя
  6586. */
  6587. if (attempts > 0) {
  6588. attempts--;
  6589. calcBattleResult(battlesInfo)
  6590. .then(resultCalcBattle);
  6591. return;
  6592. }
  6593. /**
  6594. * Otherwise, go to the next opponent
  6595. * Иначе переходим к следующему сопернику
  6596. */
  6597. roundRivals();
  6598. }
  6599. /**
  6600. * Processing the results of the battle calculation
  6601. *
  6602. * Обработка результатов расчета битвы
  6603. */
  6604. function resultCalcBattle(resultBattle) {
  6605. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  6606. /**
  6607. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  6608. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  6609. */
  6610. if (resultBattle.result.win || !attempts) {
  6611. titanArenaEndBattle({
  6612. progress: resultBattle.progress,
  6613. result: resultBattle.result,
  6614. rivalId: resultBattle.battleData.typeId
  6615. });
  6616. return;
  6617. }
  6618. /**
  6619. * If not victory and there are attempts we start a new battle
  6620. * Если не победа и есть попытки начинаем новый бой
  6621. */
  6622. titanArenaStartBattle(resultBattle.battleData.typeId);
  6623. }
  6624. /**
  6625. * Returns the promise of calculating the results of the battle
  6626. *
  6627. * Возращает промис расчета результатов битвы
  6628. */
  6629. function getBattleInfo(battle, isRandSeed) {
  6630. return new Promise(function (resolve) {
  6631. if (isRandSeed) {
  6632. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  6633. }
  6634. // console.log(battle.seed);
  6635. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  6636. });
  6637. }
  6638. /**
  6639. * Recalculate battles
  6640. *
  6641. * Прерасчтет битвы
  6642. */
  6643. function preCalcBattle(battle) {
  6644. let actions = [getBattleInfo(battle, false)];
  6645. const countTestBattle = getInput('countTestBattle');
  6646. for (let i = 0; i < countTestBattle; i++) {
  6647. actions.push(getBattleInfo(battle, true));
  6648. }
  6649. Promise.all(actions)
  6650. .then(resultPreCalcBattle);
  6651. }
  6652. /**
  6653. * Processing the results of the battle recalculation
  6654. *
  6655. * Обработка результатов прерасчета битвы
  6656. */
  6657. function resultPreCalcBattle(e) {
  6658. let wins = e.map(n => n.result.win);
  6659. let firstBattle = e.shift();
  6660. let countWin = wins.reduce((w, s) => w + s);
  6661. const countTestBattle = getInput('countTestBattle');
  6662. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  6663. if (countWin > 0) {
  6664. attempts = getInput('countAutoBattle');
  6665. } else {
  6666. attempts = 0;
  6667. }
  6668. resultCalcBattle(firstBattle);
  6669. }
  6670.  
  6671. /**
  6672. * Complete an arena battle
  6673. *
  6674. * Завершить битву на арене
  6675. */
  6676. function titanArenaEndBattle(args) {
  6677. let calls = [{
  6678. name: "titanArenaEndBattle",
  6679. args,
  6680. ident: "body"
  6681. }];
  6682. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  6683. }
  6684.  
  6685. function resultTitanArenaEndBattle(e) {
  6686. let attackScore = e.results[0].result.response.attackScore;
  6687. let numReval = countRivalsTier - finishListBattle.length;
  6688. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  6689. /**
  6690. * TODO: Might need to improve the results.
  6691. * TODO: Возможно стоит сделать улучшение результатов
  6692. */
  6693. // console.log('resultTitanArenaEndBattle', e)
  6694. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  6695. roundRivals();
  6696. }
  6697. /**
  6698. * Arena State
  6699. *
  6700. * Состояние арены
  6701. */
  6702. function titanArenaGetStatus() {
  6703. let calls = [{
  6704. name: "titanArenaGetStatus",
  6705. args: {},
  6706. ident: "body"
  6707. }];
  6708. send(JSON.stringify({calls}), checkResultInfo);
  6709. }
  6710. /**
  6711. * Arena Raid Request
  6712. *
  6713. * Запрос рейда арены
  6714. */
  6715. function titanArenaStartRaid() {
  6716. let calls = [{
  6717. name: "titanArenaStartRaid",
  6718. args: {
  6719. titans: titan_arena
  6720. },
  6721. ident: "body"
  6722. }];
  6723. send(JSON.stringify({calls}), calcResults);
  6724. }
  6725.  
  6726. function calcResults(data) {
  6727. let battlesInfo = data.results[0].result.response;
  6728. let {attackers, rivals} = battlesInfo;
  6729.  
  6730. let promises = [];
  6731. for (let n in rivals) {
  6732. rival = rivals[n];
  6733. promises.push(calcBattleResult({
  6734. attackers: attackers,
  6735. defenders: [rival.team],
  6736. seed: rival.seed,
  6737. typeId: n,
  6738. }));
  6739. }
  6740.  
  6741. Promise.all(promises)
  6742. .then(results => {
  6743. const endResults = {};
  6744. for (let info of results) {
  6745. let id = info.battleData.typeId;
  6746. endResults[id] = {
  6747. progress: info.progress,
  6748. result: info.result,
  6749. }
  6750. }
  6751. titanArenaEndRaid(endResults);
  6752. });
  6753. }
  6754.  
  6755. function calcBattleResult(battleData) {
  6756. return new Promise(function (resolve, reject) {
  6757. BattleCalc(battleData, "get_titanClanPvp", resolve);
  6758. });
  6759. }
  6760.  
  6761. /**
  6762. * Sending Raid Results
  6763. *
  6764. * Отправка результатов рейда
  6765. */
  6766. function titanArenaEndRaid(results) {
  6767. titanArenaEndRaidCall = {
  6768. calls: [{
  6769. name: "titanArenaEndRaid",
  6770. args: {
  6771. results
  6772. },
  6773. ident: "body"
  6774. }]
  6775. }
  6776. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  6777. }
  6778.  
  6779. function checkRaidResults(data) {
  6780. results = data.results[0].result.response.results;
  6781. isSucsesRaid = true;
  6782. for (let i in results) {
  6783. isSucsesRaid &&= (results[i].attackScore >= 250);
  6784. }
  6785.  
  6786. if (isSucsesRaid) {
  6787. titanArenaCompleteTier();
  6788. } else {
  6789. titanArenaGetStatus();
  6790. }
  6791. }
  6792.  
  6793. function titanArenaFarmDailyReward() {
  6794. titanArenaFarmDailyRewardCall = {
  6795. calls: [{
  6796. name: "titanArenaFarmDailyReward",
  6797. args: {},
  6798. ident: "body"
  6799. }]
  6800. }
  6801. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  6802. }
  6803.  
  6804. function endTitanArena(reason, info) {
  6805. if (!['Peace_time', 'disabled'].includes(reason)) {
  6806. titanArenaFarmDailyReward();
  6807. }
  6808. console.log(reason, info);
  6809. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  6810. resolve();
  6811. }
  6812. }
  6813.  
  6814. this.HWHClasses.executeTitanArena = executeTitanArena;
  6815.  
  6816. function hackGame() {
  6817. const self = this;
  6818. selfGame = null;
  6819. bindId = 1e9;
  6820. this.libGame = null;
  6821. this.doneLibLoad = () => {};
  6822.  
  6823. /**
  6824. * List of correspondence of used classes to their names
  6825. *
  6826. * Список соответствия используемых классов их названиям
  6827. */
  6828. ObjectsList = [
  6829. { name: 'BattlePresets', prop: 'game.battle.controller.thread.BattlePresets' },
  6830. { name: 'DataStorage', prop: 'game.data.storage.DataStorage' },
  6831. { name: 'BattleConfigStorage', prop: 'game.data.storage.battle.BattleConfigStorage' },
  6832. { name: 'BattleInstantPlay', prop: 'game.battle.controller.instant.BattleInstantPlay' },
  6833. { name: 'MultiBattleInstantReplay', prop: 'game.battle.controller.instant.MultiBattleInstantReplay' },
  6834. { name: 'MultiBattleResult', prop: 'game.battle.controller.MultiBattleResult' },
  6835.  
  6836. { name: 'PlayerMissionData', prop: 'game.model.user.mission.PlayerMissionData' },
  6837. { name: 'PlayerMissionBattle', prop: 'game.model.user.mission.PlayerMissionBattle' },
  6838. { name: 'GameModel', prop: 'game.model.GameModel' },
  6839. { name: 'CommandManager', prop: 'game.command.CommandManager' },
  6840. { name: 'MissionCommandList', prop: 'game.command.rpc.mission.MissionCommandList' },
  6841. { name: 'RPCCommandBase', prop: 'game.command.rpc.RPCCommandBase' },
  6842. { name: 'PlayerTowerData', prop: 'game.model.user.tower.PlayerTowerData' },
  6843. { name: 'TowerCommandList', prop: 'game.command.tower.TowerCommandList' },
  6844. { name: 'PlayerHeroTeamResolver', prop: 'game.model.user.hero.PlayerHeroTeamResolver' },
  6845. { name: 'BattlePausePopup', prop: 'game.view.popup.battle.BattlePausePopup' },
  6846. { name: 'BattlePopup', prop: 'game.view.popup.battle.BattlePopup' },
  6847. { name: 'DisplayObjectContainer', prop: 'starling.display.DisplayObjectContainer' },
  6848. { name: 'GuiClipContainer', prop: 'engine.core.clipgui.GuiClipContainer' },
  6849. { name: 'BattlePausePopupClip', prop: 'game.view.popup.battle.BattlePausePopupClip' },
  6850. { name: 'ClipLabel', prop: 'game.view.gui.components.ClipLabel' },
  6851. { name: 'ClipLabelBase', prop: 'game.view.gui.components.ClipLabelBase' },
  6852. { name: 'Translate', prop: 'com.progrestar.common.lang.Translate' },
  6853. { name: 'ClipButtonLabeledCentered', prop: 'game.view.gui.components.ClipButtonLabeledCentered' },
  6854. { name: 'BattlePausePopupMediator', prop: 'game.mediator.gui.popup.battle.BattlePausePopupMediator' },
  6855. { name: 'SettingToggleButton', prop: 'game.mechanics.settings.popup.view.SettingToggleButton' },
  6856. { name: 'PlayerDungeonData', prop: 'game.mechanics.dungeon.model.PlayerDungeonData' },
  6857. { name: 'NextDayUpdatedManager', prop: 'game.model.user.NextDayUpdatedManager' },
  6858. { name: 'BattleController', prop: 'game.battle.controller.BattleController' },
  6859. { name: 'BattleSettingsModel', prop: 'game.battle.controller.BattleSettingsModel' },
  6860. { name: 'BooleanProperty', prop: 'engine.core.utils.property.BooleanProperty' },
  6861. { name: 'RuleStorage', prop: 'game.data.storage.rule.RuleStorage' },
  6862. { name: 'BattleConfig', prop: 'battle.BattleConfig' },
  6863. { name: 'BattleGuiMediator', prop: 'game.battle.gui.BattleGuiMediator' },
  6864. { name: 'BooleanPropertyWriteable', prop: 'engine.core.utils.property.BooleanPropertyWriteable' },
  6865. { name: 'BattleLogEncoder', prop: 'battle.log.BattleLogEncoder' },
  6866. { name: 'BattleLogReader', prop: 'battle.log.BattleLogReader' },
  6867. { name: 'PlayerSubscriptionInfoValueObject', prop: 'game.model.user.subscription.PlayerSubscriptionInfoValueObject' },
  6868. { name: 'AdventureMapCamera', prop: 'game.mechanics.adventure.popup.map.AdventureMapCamera' },
  6869. ];
  6870.  
  6871. /**
  6872. * Contains the game classes needed to write and override game methods
  6873. *
  6874. * Содержит классы игры необходимые для написания и подмены методов игры
  6875. */
  6876. Game = {
  6877. /**
  6878. * Function 'e'
  6879. * Функция 'e'
  6880. */
  6881. bindFunc: function (a, b) {
  6882. if (null == b) return null;
  6883. null == b.__id__ && (b.__id__ = bindId++);
  6884. var c;
  6885. null == a.hx__closures__ ? (a.hx__closures__ = {}) : (c = a.hx__closures__[b.__id__]);
  6886. null == c && ((c = b.bind(a)), (a.hx__closures__[b.__id__] = c));
  6887. return c;
  6888. },
  6889. };
  6890.  
  6891. /**
  6892. * Connects to game objects via the object creation event
  6893. *
  6894. * Подключается к объектам игры через событие создания объекта
  6895. */
  6896. function connectGame() {
  6897. for (let obj of ObjectsList) {
  6898. /**
  6899. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  6900. */
  6901. Object.defineProperty(Object.prototype, obj.prop, {
  6902. set: function (value) {
  6903. if (!selfGame) {
  6904. selfGame = this;
  6905. }
  6906. if (!Game[obj.name]) {
  6907. Game[obj.name] = value;
  6908. }
  6909. // console.log('set ' + obj.prop, this, value);
  6910. this[obj.prop + '_'] = value;
  6911. },
  6912. get: function () {
  6913. // console.log('get ' + obj.prop, this);
  6914. return this[obj.prop + '_'];
  6915. },
  6916. });
  6917. }
  6918. }
  6919.  
  6920. /**
  6921. * Game.BattlePresets
  6922. * @param {bool} a isReplay
  6923. * @param {bool} b autoToggleable
  6924. * @param {bool} c auto On Start
  6925. * @param {object} d config
  6926. * @param {bool} f showBothTeams
  6927. */
  6928. /**
  6929. * Returns the results of the battle to the callback function
  6930. * Возвращает в функцию callback результаты боя
  6931. * @param {*} battleData battle data данные боя
  6932. * @param {*} battleConfig combat configuration type options:
  6933. *
  6934. * тип конфигурации боя варианты:
  6935. *
  6936. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  6937. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  6938. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  6939. *
  6940. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  6941. *
  6942. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  6943. * @param {*} callback функция в которую вернуться результаты боя
  6944. */
  6945. this.BattleCalc = function (battleData, battleConfig, callback) {
  6946. // battleConfig = battleConfig || getBattleType(battleData.type)
  6947. if (!Game.BattlePresets) throw Error('Use connectGame');
  6948. battlePresets = new Game.BattlePresets(
  6949. battleData.progress,
  6950. !1,
  6951. !0,
  6952. Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](),
  6953. !1
  6954. );
  6955. let battleInstantPlay;
  6956. if (battleData.progress?.length > 1) {
  6957. battleInstantPlay = new Game.MultiBattleInstantReplay(battleData, battlePresets);
  6958. } else {
  6959. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  6960. }
  6961. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 9)].add((battleInstant) => {
  6962. const MBR_2 = getProtoFn(Game.MultiBattleResult, 2);
  6963. const battleResults = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  6964. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  6965. const battleLogs = [];
  6966. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  6967. let battleTime = 0;
  6968. let battleTimer = 0;
  6969. for (const battleResult of battleResults[MBR_2]) {
  6970. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult));
  6971. battleLogs.push(battleLog);
  6972. const maxTime = Math.max(...battleLog.map((e) => (e.time < timeLimit && e.time !== 168.8 ? e.time : 0)));
  6973. battleTimer += getTimer(maxTime);
  6974. battleTime += maxTime;
  6975. }
  6976. callback({
  6977. battleLogs,
  6978. battleTime,
  6979. battleTimer,
  6980. battleData,
  6981. progress: battleResults[getF(Game.MultiBattleResult, 'get_progress')](),
  6982. result: battleResults[getF(Game.MultiBattleResult, 'get_result')](),
  6983. });
  6984. });
  6985. battleInstantPlay.start();
  6986. };
  6987.  
  6988. /**
  6989. * Returns a function with the specified name from the class
  6990. *
  6991. * Возвращает из класса функцию с указанным именем
  6992. * @param {Object} classF Class // класс
  6993. * @param {String} nameF function name // имя функции
  6994. * @param {String} pos name and alias order // порядок имени и псевдонима
  6995. * @returns
  6996. */
  6997. function getF(classF, nameF, pos) {
  6998. pos = pos || false;
  6999. let prop = Object.entries(classF.prototype.__properties__);
  7000. if (!pos) {
  7001. return prop.filter((e) => e[1] == nameF).pop()[0];
  7002. } else {
  7003. return prop.filter((e) => e[0] == nameF).pop()[1];
  7004. }
  7005. }
  7006.  
  7007. /**
  7008. * Returns a function with the specified name from the class
  7009. *
  7010. * Возвращает из класса функцию с указанным именем
  7011. * @param {Object} classF Class // класс
  7012. * @param {String} nameF function name // имя функции
  7013. * @returns
  7014. */
  7015. function getFnP(classF, nameF) {
  7016. let prop = Object.entries(classF.__properties__);
  7017. return prop.filter((e) => e[1] == nameF).pop()[0];
  7018. }
  7019.  
  7020. /**
  7021. * Returns the function name with the specified ordinal from the class
  7022. *
  7023. * Возвращает имя функции с указаным порядковым номером из класса
  7024. * @param {Object} classF Class // класс
  7025. * @param {Number} nF Order number of function // порядковый номер функции
  7026. * @returns
  7027. */
  7028. function getFn(classF, nF) {
  7029. let prop = Object.keys(classF);
  7030. return prop[nF];
  7031. }
  7032.  
  7033. /**
  7034. * Returns the name of the function with the specified serial number from the prototype of the class
  7035. *
  7036. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  7037. * @param {Object} classF Class // класс
  7038. * @param {Number} nF Order number of function // порядковый номер функции
  7039. * @returns
  7040. */
  7041. function getProtoFn(classF, nF) {
  7042. let prop = Object.keys(classF.prototype);
  7043. return prop[nF];
  7044. }
  7045. /**
  7046. * Description of replaced functions
  7047. *
  7048. * Описание подменяемых функций
  7049. */
  7050. replaceFunction = {
  7051. company: function () {
  7052. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  7053. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  7054. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  7055. if (!isChecked('passBattle')) {
  7056. oldSkipMisson.call(this, a, b, c);
  7057. return;
  7058. }
  7059.  
  7060. try {
  7061. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  7062.  
  7063. var a = new Game.BattlePresets(
  7064. !1,
  7065. !1,
  7066. !0,
  7067. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  7068. !1
  7069. );
  7070. a = new Game.BattleInstantPlay(c, a);
  7071. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  7072. a.start();
  7073. } catch (error) {
  7074. console.error('company', error);
  7075. oldSkipMisson.call(this, a, b, c);
  7076. }
  7077. };
  7078.  
  7079. Game.PlayerMissionData.prototype.P$h = function (a) {
  7080. let GM_2 = getFn(Game.GameModel, 2);
  7081. let GM_P2 = getProtoFn(Game.GameModel, 2);
  7082. let CM_20 = getProtoFn(Game.CommandManager, 20);
  7083. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  7084. let MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  7085. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  7086. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  7087. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]));
  7088. };
  7089. },
  7090. /*
  7091. tower: function () {
  7092. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  7093. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  7094. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  7095. if (!isChecked('passBattle')) {
  7096. oldSkipTower.call(this, a);
  7097. return;
  7098. }
  7099. try {
  7100. var p = new Game.BattlePresets(
  7101. !1,
  7102. !1,
  7103. !0,
  7104. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  7105. !1
  7106. );
  7107. a = new Game.BattleInstantPlay(a, p);
  7108. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  7109. a.start();
  7110. } catch (error) {
  7111. console.error('tower', error);
  7112. oldSkipMisson.call(this, a, b, c);
  7113. }
  7114. };
  7115.  
  7116. Game.PlayerTowerData.prototype.P$h = function (a) {
  7117. const GM_2 = getFnP(Game.GameModel, 'get_instance');
  7118. const GM_P2 = getProtoFn(Game.GameModel, 2);
  7119. const CM_29 = getProtoFn(Game.CommandManager, 29);
  7120. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  7121. const MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  7122. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  7123. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  7124. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  7125. };
  7126. },
  7127. */
  7128. // skipSelectHero: function() {
  7129. // if (!HOST) throw Error('Use connectGame');
  7130. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  7131. // },
  7132. passBattle: function () {
  7133. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  7134. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  7135. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  7136. if (!isChecked('passBattle')) {
  7137. oldPassBattle.call(this, a);
  7138. return;
  7139. }
  7140. try {
  7141. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  7142. this[getProtoFn(Game.BattlePausePopup, 3)]();
  7143. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  7144. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](
  7145. Game.Translate.translate('UI_POPUP_BATTLE_PAUSE')
  7146. );
  7147.  
  7148. this.clip[getProtoFn(Game.BattlePausePopupClip, 2)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7149. Game.Translate.translate('UI_POPUP_BATTLE_RETREAT'),
  7150. ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 17)]))
  7151. );
  7152. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7153. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  7154. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]()
  7155. ? ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7156. : ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7157. );
  7158.  
  7159. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][
  7160. getProtoFn(Game.ClipLabelBase, 24)
  7161. ]();
  7162. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](
  7163. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]()
  7164. );
  7165. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](
  7166. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]()
  7167. );
  7168. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](
  7169. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]()
  7170. );
  7171. } catch (error) {
  7172. console.error('passBattle', error);
  7173. oldPassBattle.call(this, a);
  7174. }
  7175. };
  7176.  
  7177. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, 'get_retreatButtonLabel');
  7178. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  7179. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  7180. if (isChecked('passBattle')) {
  7181. return I18N('BTN_PASS');
  7182. } else {
  7183. return oldFunc.call(this);
  7184. }
  7185. };
  7186. },
  7187. endlessCards: function () {
  7188. let PDD_21 = getProtoFn(Game.PlayerDungeonData, 21);
  7189. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_21];
  7190. Game.PlayerDungeonData.prototype[PDD_21] = function () {
  7191. if (countPredictionCard <= 0) {
  7192. return true;
  7193. } else {
  7194. return oldEndlessCards.call(this);
  7195. }
  7196. };
  7197. },
  7198. speedBattle: function () {
  7199. const get_timeScale = getF(Game.BattleController, 'get_timeScale');
  7200. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  7201. Game.BattleController.prototype[get_timeScale] = function () {
  7202. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  7203. if (!speedBattle) {
  7204. return oldSpeedBattle.call(this);
  7205. }
  7206. try {
  7207. const BC_12 = getProtoFn(Game.BattleController, 12);
  7208. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  7209. const BP_get_value = getF(Game.BooleanProperty, 'get_value');
  7210. if (this[BC_12][BSM_12][BP_get_value]()) {
  7211. return 0;
  7212. }
  7213. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  7214. const BC_49 = getProtoFn(Game.BattleController, 49);
  7215. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  7216. const BC_14 = getProtoFn(Game.BattleController, 14);
  7217. const BC_3 = getFn(Game.BattleController, 3);
  7218. if (this[BC_12][BSM_2][BP_get_value]()) {
  7219. var a = speedBattle * this[BC_49]();
  7220. } else {
  7221. a = this[BC_12][BSM_1][BP_get_value]();
  7222. const maxSpeed = Math.max(...this[BC_14]);
  7223. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  7224. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_49]();
  7225. }
  7226. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  7227. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  7228. const DS_23 = getFn(Game.DataStorage, 23);
  7229. const get_battleSpeedMultiplier = getF(Game.RuleStorage, 'get_battleSpeedMultiplier', true);
  7230. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  7231. const R_1 = getFn(selfGame.Reflect, 1);
  7232. const BC_1 = getFn(Game.BattleController, 1);
  7233. const get_config = getF(Game.BattlePresets, 'get_config');
  7234. null != b &&
  7235. (a = selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7236. ? a * selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7237. : a * selfGame.Reflect[R_1](b, 'default'));
  7238. return a;
  7239. } catch (error) {
  7240. console.error('passBatspeedBattletle', error);
  7241. return oldSpeedBattle.call(this);
  7242. }
  7243. };
  7244. },
  7245.  
  7246. /**
  7247. * Acceleration button without Valkyries favor
  7248. *
  7249. * Кнопка ускорения без Покровительства Валькирий
  7250. */
  7251. battleFastKey: function () {
  7252. const BGM_44 = getProtoFn(Game.BattleGuiMediator, 44);
  7253. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_44];
  7254. Game.BattleGuiMediator.prototype[BGM_44] = function () {
  7255. let flag = true;
  7256. //console.log(flag)
  7257. if (!flag) {
  7258. return oldBattleFastKey.call(this);
  7259. }
  7260. try {
  7261. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  7262. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  7263. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  7264. this[BGM_9][BPW_0](true);
  7265. this[BGM_10][BPW_0](true);
  7266. } catch (error) {
  7267. console.error(error);
  7268. return oldBattleFastKey.call(this);
  7269. }
  7270. };
  7271. },
  7272. fastSeason: function () {
  7273. const GameNavigator = selfGame['game.screen.navigator.GameNavigator'];
  7274. const oldFuncName = getProtoFn(GameNavigator, 18);
  7275. const newFuncName = getProtoFn(GameNavigator, 16);
  7276. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  7277. const newFastSeason = GameNavigator.prototype[newFuncName];
  7278. GameNavigator.prototype[oldFuncName] = function (a, b) {
  7279. if (isChecked('fastSeason')) {
  7280. return newFastSeason.apply(this, [a]);
  7281. } else {
  7282. return oldFastSeason.apply(this, [a, b]);
  7283. }
  7284. };
  7285. },
  7286. ShowChestReward: function () {
  7287. const TitanArtifactChest = selfGame['game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator'];
  7288. const getOpenAmountTitan = getF(TitanArtifactChest, 'get_openAmount');
  7289. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  7290. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  7291. if (correctShowOpenArtifact) {
  7292. correctShowOpenArtifact--;
  7293. return 100;
  7294. }
  7295. return oldGetOpenAmountTitan.call(this);
  7296. };
  7297.  
  7298. const ArtifactChest = selfGame['game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator'];
  7299. const getOpenAmount = getF(ArtifactChest, 'get_openAmount');
  7300. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  7301. ArtifactChest.prototype[getOpenAmount] = function () {
  7302. if (correctShowOpenArtifact) {
  7303. correctShowOpenArtifact--;
  7304. return 100;
  7305. }
  7306. return oldGetOpenAmount.call(this);
  7307. };
  7308. },
  7309. fixCompany: function () {
  7310. const GameBattleView = selfGame['game.mediator.gui.popup.battle.GameBattleView'];
  7311. const BattleThread = selfGame['game.battle.controller.thread.BattleThread'];
  7312. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  7313. const getThread = getF(GameBattleView, 'get_thread');
  7314. const oldFunc = GameBattleView.prototype[getThread];
  7315. GameBattleView.prototype[getThread] = function () {
  7316. return (
  7317. oldFunc.call(this) || {
  7318. [getOnViewDisposed]: async () => {},
  7319. }
  7320. );
  7321. };
  7322. },
  7323. BuyTitanArtifact: function () {
  7324. const BIP_4 = getProtoFn(selfGame['game.view.popup.shop.buy.BuyItemPopup'], 4);
  7325. const BuyItemPopup = selfGame['game.view.popup.shop.buy.BuyItemPopup'];
  7326. const oldFunc = BuyItemPopup.prototype[BIP_4];
  7327. BuyItemPopup.prototype[BIP_4] = function () {
  7328. if (isChecked('countControl')) {
  7329. const BuyTitanArtifactItemPopup = selfGame['game.view.popup.shop.buy.BuyTitanArtifactItemPopup'];
  7330. const BTAP_0 = getProtoFn(BuyTitanArtifactItemPopup, 0);
  7331. if (this[BTAP_0]) {
  7332. const BuyTitanArtifactPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyTitanArtifactItemPopupMediator'];
  7333. const BTAM_1 = getProtoFn(BuyTitanArtifactPopupMediator, 1);
  7334. const BuyItemPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyItemPopupMediator'];
  7335. const BIPM_5 = getProtoFn(BuyItemPopupMediator, 5);
  7336. const BIPM_7 = getProtoFn(BuyItemPopupMediator, 7);
  7337. const BIPM_9 = getProtoFn(BuyItemPopupMediator, 9);
  7338.  
  7339. let need = Math.min(this[BTAP_0][BTAM_1](), this[BTAP_0][BIPM_7]);
  7340. need = need ? need : 60;
  7341. this[BTAP_0][BIPM_9] = need;
  7342. this[BTAP_0][BIPM_5] = 10;
  7343. }
  7344. }
  7345. oldFunc.call(this);
  7346. };
  7347. },
  7348. ClanQuestsFastFarm: function () {
  7349. const VipRuleValueObject = selfGame['game.data.storage.rule.VipRuleValueObject'];
  7350. const getClanQuestsFastFarm = getF(VipRuleValueObject, 'get_clanQuestsFastFarm', 1);
  7351. VipRuleValueObject.prototype[getClanQuestsFastFarm] = function () {
  7352. return 0;
  7353. };
  7354. },
  7355. adventureCamera: function () {
  7356. const AMC_40 = getProtoFn(Game.AdventureMapCamera, 40);
  7357. const AMC_5 = getProtoFn(Game.AdventureMapCamera, 5);
  7358. const oldFunc = Game.AdventureMapCamera.prototype[AMC_40];
  7359. Game.AdventureMapCamera.prototype[AMC_40] = function (a) {
  7360. this[AMC_5] = 0.4;
  7361. oldFunc.bind(this)(a);
  7362. };
  7363. },
  7364. unlockMission: function () {
  7365. const WorldMapStoryDrommerHelper = selfGame['game.mediator.gui.worldmap.WorldMapStoryDrommerHelper'];
  7366. const WMSDH_4 = getFn(WorldMapStoryDrommerHelper, 4);
  7367. const WMSDH_7 = getFn(WorldMapStoryDrommerHelper, 7);
  7368. WorldMapStoryDrommerHelper[WMSDH_4] = function () {
  7369. return true;
  7370. };
  7371. WorldMapStoryDrommerHelper[WMSDH_7] = function () {
  7372. return true;
  7373. };
  7374. },
  7375. };
  7376.  
  7377. /**
  7378. * Starts replacing recorded functions
  7379. *
  7380. * Запускает замену записанных функций
  7381. */
  7382. this.activateHacks = function () {
  7383. if (!selfGame) throw Error('Use connectGame');
  7384. for (let func in replaceFunction) {
  7385. try {
  7386. replaceFunction[func]();
  7387. } catch (error) {
  7388. console.error(error);
  7389. }
  7390. }
  7391. };
  7392.  
  7393. /**
  7394. * Returns the game object
  7395. *
  7396. * Возвращает объект игры
  7397. */
  7398. this.getSelfGame = function () {
  7399. return selfGame;
  7400. };
  7401.  
  7402. /**
  7403. * Updates game data
  7404. *
  7405. * Обновляет данные игры
  7406. */
  7407. this.refreshGame = function () {
  7408. new Game.NextDayUpdatedManager()[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  7409. try {
  7410. cheats.refreshInventory();
  7411. } catch (e) {}
  7412. };
  7413.  
  7414. /**
  7415. * Update inventory
  7416. *
  7417. * Обновляет инвентарь
  7418. */
  7419. this.refreshInventory = async function () {
  7420. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7421. const GM_0 = getProtoFn(Game.GameModel, 0);
  7422. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7423. const Player = Game.GameModel[GM_INST]()[GM_0];
  7424. Player[P_24] = new selfGame['game.model.user.inventory.PlayerInventory']();
  7425. Player[P_24].init(await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'body' }] }).then((e) => e.results[0].result.response));
  7426. };
  7427. this.updateInventory = function (reward) {
  7428. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7429. const GM_0 = getProtoFn(Game.GameModel, 0);
  7430. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7431. const Player = Game.GameModel[GM_INST]()[GM_0];
  7432. Player[P_24].init(reward);
  7433. };
  7434.  
  7435. this.updateMap = function (data) {
  7436. const PCDD_21 = getProtoFn(selfGame['game.mechanics.clanDomination.model.PlayerClanDominationData'], 21);
  7437. const P_60 = getProtoFn(selfGame['game.model.user.Player'], 60);
  7438. const GM_0 = getProtoFn(Game.GameModel, 0);
  7439. const getInstance = getFnP(selfGame['Game'], 'get_instance');
  7440. const PlayerClanDominationData = Game.GameModel[getInstance]()[GM_0];
  7441. PlayerClanDominationData[P_60][PCDD_21].update(data);
  7442. };
  7443.  
  7444. /**
  7445. * Change the play screen on windowName
  7446. *
  7447. * Сменить экран игры на windowName
  7448. *
  7449. * Possible options:
  7450. *
  7451. * Возможные варианты:
  7452. *
  7453. * 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
  7454. */
  7455. this.goNavigtor = function (windowName) {
  7456. let mechanicStorage = selfGame['game.data.storage.mechanic.MechanicStorage'];
  7457. let window = mechanicStorage[windowName];
  7458. let event = new selfGame['game.mediator.gui.popup.PopupStashEventParams']();
  7459. let Game = selfGame['Game'];
  7460. let navigator = getF(Game, 'get_navigator');
  7461. let navigate = getProtoFn(selfGame['game.screen.navigator.GameNavigator'], 20);
  7462. let instance = getFnP(Game, 'get_instance');
  7463. Game[instance]()[navigator]()[navigate](window, event);
  7464. };
  7465.  
  7466. /**
  7467. * Move to the sanctuary cheats.goSanctuary()
  7468. *
  7469. * Переместиться в святилище cheats.goSanctuary()
  7470. */
  7471. this.goSanctuary = () => {
  7472. this.goNavigtor('SANCTUARY');
  7473. };
  7474.  
  7475. /** Перейти в Долину титанов */
  7476. this.goTitanValley = () => {
  7477. this.goNavigtor('TITAN_VALLEY');
  7478. };
  7479.  
  7480. /**
  7481. * Go to Guild War
  7482. *
  7483. * Перейти к Войне Гильдий
  7484. */
  7485. this.goClanWar = function () {
  7486. let instance = getFnP(Game.GameModel, 'get_instance');
  7487. let player = Game.GameModel[instance]().A;
  7488. let clanWarSelect = selfGame['game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator'];
  7489. new clanWarSelect(player).open();
  7490. };
  7491.  
  7492. /** Перейти к Острову гильдии */
  7493. this.goClanIsland = function () {
  7494. let instance = getFnP(Game.GameModel, 'get_instance');
  7495. let player = Game.GameModel[instance]().A;
  7496. let clanIslandSelect = selfGame['game.view.gui.ClanIslandPopupMediator'];
  7497. new clanIslandSelect(player).open();
  7498. };
  7499.  
  7500. /**
  7501. * Go to BrawlShop
  7502. *
  7503. * Переместиться в BrawlShop
  7504. */
  7505. this.goBrawlShop = () => {
  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. const PSDE_4 = getProtoFn(selfGame['game.model.user.shop.PlayerShopDataEntry'], 4);
  7511.  
  7512. const player = Game.GameModel[instance]().A;
  7513. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  7514. const shopPopup = new selfGame['game.mechanics.brawl.mediator.BrawlShopPopupMediator'](player, shop);
  7515. shopPopup.open(new selfGame['game.mediator.gui.popup.PopupStashEventParams']());
  7516. };
  7517.  
  7518. /**
  7519. * Returns all stores from game data
  7520. *
  7521. * Возвращает все магазины из данных игры
  7522. */
  7523. this.getShops = () => {
  7524. const instance = getFnP(Game.GameModel, 'get_instance');
  7525. const P_36 = getProtoFn(selfGame['game.model.user.Player'], 36);
  7526. const PSD_0 = getProtoFn(selfGame['game.model.user.shop.PlayerShopData'], 0);
  7527. const IM_0 = getProtoFn(selfGame['haxe.ds.IntMap'], 0);
  7528.  
  7529. const player = Game.GameModel[instance]().A;
  7530. return player[P_36][PSD_0][IM_0];
  7531. };
  7532.  
  7533. /**
  7534. * Returns the store from the game data by ID
  7535. *
  7536. * Возвращает магазин из данных игры по идетификатору
  7537. */
  7538. this.getShop = (id) => {
  7539. const PSDE_4 = getProtoFn(selfGame['game.model.user.shop.PlayerShopDataEntry'], 4);
  7540. const shops = this.getShops();
  7541. const shop = shops[id]?.[PSDE_4];
  7542. return shop;
  7543. };
  7544.  
  7545. /**
  7546. * Change island map
  7547. *
  7548. * Сменить карту острова
  7549. */
  7550. this.changeIslandMap = (mapId = 2) => {
  7551. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  7552. const GM_0 = getProtoFn(Game.GameModel, 0);
  7553. const P_59 = getProtoFn(selfGame['game.model.user.Player'], 60);
  7554. const PSAD_31 = getProtoFn(selfGame['game.mechanics.season_adventure.model.PlayerSeasonAdventureData'], 31);
  7555. const Player = Game.GameModel[GameInst]()[GM_0];
  7556. Player[P_59][PSAD_31]({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  7557.  
  7558. const GN_15 = getProtoFn(selfGame['game.screen.navigator.GameNavigator'], 17);
  7559. const navigator = getF(selfGame['Game'], 'get_navigator');
  7560. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame['game.mediator.gui.popup.PopupStashEventParams']());
  7561. };
  7562.  
  7563. /**
  7564. * Game library availability tracker
  7565. *
  7566. * Отслеживание доступности игровой библиотеки
  7567. */
  7568. function checkLibLoad() {
  7569. timeout = setTimeout(() => {
  7570. if (Game.GameModel) {
  7571. changeLib();
  7572. } else {
  7573. checkLibLoad();
  7574. }
  7575. }, 100);
  7576. }
  7577.  
  7578. /**
  7579. * Game library data spoofing
  7580. *
  7581. * Подмена данных игровой библиотеки
  7582. */
  7583. function changeLib() {
  7584. console.log('lib connect');
  7585. const originalStartFunc = Game.GameModel.prototype.start;
  7586. Game.GameModel.prototype.start = function (a, b, c) {
  7587. self.libGame = b.raw;
  7588. self.doneLibLoad(self.libGame);
  7589. try {
  7590. const levels = b.raw.seasonAdventure.level;
  7591. for (const id in levels) {
  7592. const level = levels[id];
  7593. level.clientData.graphics.fogged = level.clientData.graphics.visible;
  7594. }
  7595. const adv = b.raw.seasonAdventure.list[1];
  7596. adv.clientData.asset = 'dialog_season_adventure_tiles';
  7597. } catch (e) {
  7598. console.warn(e);
  7599. }
  7600. originalStartFunc.call(this, a, b, c);
  7601. };
  7602. }
  7603.  
  7604. this.LibLoad = function () {
  7605. return new Promise((e) => {
  7606. this.doneLibLoad = e;
  7607. });
  7608. };
  7609.  
  7610. /**
  7611. * Returns the value of a language constant
  7612. *
  7613. * Возвращает значение языковой константы
  7614. * @param {*} langConst language constant // языковая константа
  7615. * @returns
  7616. */
  7617. this.translate = function (langConst) {
  7618. return Game.Translate.translate(langConst);
  7619. };
  7620.  
  7621. connectGame();
  7622. checkLibLoad();
  7623. }
  7624.  
  7625. /**
  7626. * Auto collection of gifts
  7627. *
  7628. * Автосбор подарков
  7629. */
  7630. function getAutoGifts() {
  7631. // c3ltYm9scyB0aGF0IG1lYW4gbm90aGluZw==
  7632. let valName = 'giftSendIds_' + userInfo.id;
  7633.  
  7634. if (!localStorage['clearGift' + userInfo.id]) {
  7635. localStorage[valName] = '';
  7636. localStorage['clearGift' + userInfo.id] = '+';
  7637. }
  7638.  
  7639. if (!localStorage[valName]) {
  7640. localStorage[valName] = '';
  7641. }
  7642.  
  7643. const giftsAPI = new ZingerYWebsiteAPI('getGifts.php', arguments);
  7644. /**
  7645. * Submit a request to receive gift codes
  7646. *
  7647. * Отправка запроса для получения кодов подарков
  7648. */
  7649. giftsAPI.request().then((data) => {
  7650. let freebieCheckCalls = {
  7651. calls: [],
  7652. };
  7653. data.forEach((giftId, n) => {
  7654. if (localStorage[valName].includes(giftId)) return;
  7655. freebieCheckCalls.calls.push({
  7656. name: 'registration',
  7657. args: {
  7658. user: { referrer: {} },
  7659. giftId,
  7660. },
  7661. context: {
  7662. actionTs: Math.floor(performance.now()),
  7663. cookie: window?.NXAppInfo?.session_id || null,
  7664. },
  7665. ident: giftId,
  7666. });
  7667. });
  7668.  
  7669. if (!freebieCheckCalls.calls.length) {
  7670. return;
  7671. }
  7672.  
  7673. send(JSON.stringify(freebieCheckCalls), (e) => {
  7674. let countGetGifts = 0;
  7675. const gifts = [];
  7676. for (check of e.results) {
  7677. gifts.push(check.ident);
  7678. if (check.result.response != null) {
  7679. countGetGifts++;
  7680. }
  7681. }
  7682. const saveGifts = localStorage[valName].split(';');
  7683. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  7684. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  7685. });
  7686. });
  7687. }
  7688.  
  7689. /**
  7690. * To fill the kills in the Forge of Souls
  7691. *
  7692. * Набить килов в горниле душ
  7693. */
  7694. async function bossRatingEvent() {
  7695. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  7696. if (!topGet || !topGet.results[0].result.response[0]) {
  7697. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7698. return;
  7699. }
  7700. const replayId = topGet.results[0].result.response[0].userData.replayId;
  7701. const result = await Send(JSON.stringify({
  7702. calls: [
  7703. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  7704. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  7705. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  7706. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  7707. ]
  7708. }));
  7709. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  7710. if (!bossEventInfo) {
  7711. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7712. return;
  7713. }
  7714. const usedHeroes = bossEventInfo.progress.usedHeroes;
  7715. const party = Object.values(result.results[0].result.response.replay.attackers);
  7716. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  7717. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  7718. const calls = [];
  7719. /**
  7720. * First pack
  7721. *
  7722. * Первая пачка
  7723. */
  7724. const args = {
  7725. heroes: [],
  7726. favor: {}
  7727. }
  7728. for (let hero of party) {
  7729. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  7730. args.pet = hero.id;
  7731. continue;
  7732. }
  7733. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  7734. continue;
  7735. }
  7736. args.heroes.push(hero.id);
  7737. if (hero.favorPetId) {
  7738. args.favor[hero.id] = hero.favorPetId;
  7739. }
  7740. }
  7741. if (args.heroes.length) {
  7742. calls.push({
  7743. name: 'bossRating_startBattle',
  7744. args,
  7745. ident: 'body_0',
  7746. });
  7747. }
  7748. /**
  7749. * Other packs
  7750. *
  7751. * Другие пачки
  7752. */
  7753. let heroes = [];
  7754. let count = 1;
  7755. while (heroId = availableHeroes.pop()) {
  7756. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  7757. continue;
  7758. }
  7759. heroes.push(heroId);
  7760. if (heroes.length == 5) {
  7761. calls.push({
  7762. name: 'bossRating_startBattle',
  7763. args: {
  7764. heroes: [...heroes],
  7765. pet: availablePets[Math.floor(Math.random() * availablePets.length)],
  7766. },
  7767. ident: 'body_' + count,
  7768. });
  7769. heroes = [];
  7770. count++;
  7771. }
  7772. }
  7773.  
  7774. if (!calls.length) {
  7775. setProgress(`${I18N('NO_HEROES')}`, true);
  7776. return;
  7777. }
  7778.  
  7779. const resultBattles = await Send(JSON.stringify({ calls }));
  7780. console.log(resultBattles);
  7781. rewardBossRatingEvent();
  7782. }
  7783.  
  7784. /**
  7785. * Collecting Rewards from the Forge of Souls
  7786. *
  7787. * Сбор награды из Горнила Душ
  7788. */
  7789. function rewardBossRatingEvent() {
  7790. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7791. send(rewardBossRatingCall, function (data) {
  7792. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  7793. if (!bossEventInfo) {
  7794. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7795. return;
  7796. }
  7797.  
  7798. let farmedChests = bossEventInfo.progress.farmedChests;
  7799. let score = bossEventInfo.progress.score;
  7800. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  7801. let revard = bossEventInfo.reward;
  7802.  
  7803. let getRewardCall = {
  7804. calls: []
  7805. }
  7806.  
  7807. let count = 0;
  7808. for (let i = 1; i < 10; i++) {
  7809. if (farmedChests.includes(i)) {
  7810. continue;
  7811. }
  7812. if (score < revard[i].score) {
  7813. break;
  7814. }
  7815. getRewardCall.calls.push({
  7816. name: 'bossRating_getReward',
  7817. args: {
  7818. rewardId: i,
  7819. },
  7820. ident: 'body_' + i,
  7821. });
  7822. count++;
  7823. }
  7824. if (!count) {
  7825. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7826. return;
  7827. }
  7828.  
  7829. send(JSON.stringify(getRewardCall), e => {
  7830. console.log(e);
  7831. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7832. });
  7833. });
  7834. }
  7835.  
  7836. /**
  7837. * Collect Easter eggs and event rewards
  7838. *
  7839. * Собрать пасхалки и награды событий
  7840. */
  7841. function offerFarmAllReward() {
  7842. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7843. return Send(offerGetAllCall).then((data) => {
  7844. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  7845. if (!offerGetAll.length) {
  7846. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7847. return;
  7848. }
  7849.  
  7850. const calls = [];
  7851. for (let reward of offerGetAll) {
  7852. calls.push({
  7853. name: "offerFarmReward",
  7854. args: {
  7855. offerId: reward.id
  7856. },
  7857. ident: "offerFarmReward_" + reward.id
  7858. });
  7859. }
  7860.  
  7861. return Send(JSON.stringify({ calls })).then(e => {
  7862. console.log(e);
  7863. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7864. });
  7865. });
  7866. }
  7867.  
  7868. /**
  7869. * Assemble Outland
  7870. *
  7871. * Собрать запределье
  7872. */
  7873. function getOutland() {
  7874. return new Promise(function (resolve, reject) {
  7875. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  7876. let bosses = e.results[0].result.response;
  7877.  
  7878. let bossRaidOpenChestCall = {
  7879. calls: []
  7880. };
  7881.  
  7882. for (let boss of bosses) {
  7883. if (boss.mayRaid) {
  7884. bossRaidOpenChestCall.calls.push({
  7885. name: "bossRaid",
  7886. args: {
  7887. bossId: boss.id
  7888. },
  7889. ident: "bossRaid_" + boss.id
  7890. });
  7891. bossRaidOpenChestCall.calls.push({
  7892. name: "bossOpenChest",
  7893. args: {
  7894. bossId: boss.id,
  7895. amount: 1,
  7896. starmoney: 0
  7897. },
  7898. ident: "bossOpenChest_" + boss.id
  7899. });
  7900. } else if (boss.chestId == 1) {
  7901. bossRaidOpenChestCall.calls.push({
  7902. name: "bossOpenChest",
  7903. args: {
  7904. bossId: boss.id,
  7905. amount: 1,
  7906. starmoney: 0
  7907. },
  7908. ident: "bossOpenChest_" + boss.id
  7909. });
  7910. }
  7911. }
  7912.  
  7913. if (!bossRaidOpenChestCall.calls.length) {
  7914. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  7915. resolve();
  7916. return;
  7917. }
  7918.  
  7919. send(JSON.stringify(bossRaidOpenChestCall), e => {
  7920. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  7921. resolve();
  7922. });
  7923. });
  7924. });
  7925. }
  7926.  
  7927. /**
  7928. * Collect all rewards
  7929. *
  7930. * Собрать все награды
  7931. */
  7932. function questAllFarm() {
  7933. return new Promise(function (resolve, reject) {
  7934. let questGetAllCall = {
  7935. calls: [{
  7936. name: "questGetAll",
  7937. args: {},
  7938. ident: "body"
  7939. }]
  7940. }
  7941. send(JSON.stringify(questGetAllCall), function (data) {
  7942. let questGetAll = data.results[0].result.response;
  7943. const questAllFarmCall = {
  7944. calls: []
  7945. }
  7946. let number = 0;
  7947. for (let quest of questGetAll) {
  7948. if (quest.id < 1e6 && quest.state == 2) {
  7949. questAllFarmCall.calls.push({
  7950. name: "questFarm",
  7951. args: {
  7952. questId: quest.id
  7953. },
  7954. ident: `group_${number}_body`
  7955. });
  7956. number++;
  7957. }
  7958. }
  7959.  
  7960. if (!questAllFarmCall.calls.length) {
  7961. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7962. resolve();
  7963. return;
  7964. }
  7965.  
  7966. send(JSON.stringify(questAllFarmCall), function (res) {
  7967. console.log(res);
  7968. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7969. resolve();
  7970. });
  7971. });
  7972. })
  7973. }
  7974.  
  7975. /**
  7976. * Mission auto repeat
  7977. *
  7978. * Автоповтор миссии
  7979. * isStopSendMission = false;
  7980. * isSendsMission = true;
  7981. **/
  7982. this.sendsMission = async function (param) {
  7983. if (isStopSendMission) {
  7984. isSendsMission = false;
  7985. console.log(I18N('STOPPED'));
  7986. setProgress('');
  7987. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  7988. msg: 'Ok',
  7989. result: true
  7990. }, ])
  7991. return;
  7992. }
  7993. lastMissionBattleStart = Date.now();
  7994. let missionStartCall = {
  7995. "calls": [{
  7996. "name": "missionStart",
  7997. "args": lastMissionStart,
  7998. "ident": "body"
  7999. }]
  8000. }
  8001. /**
  8002. * Mission Request
  8003. *
  8004. * Запрос на выполнение мисии
  8005. */
  8006. SendRequest(JSON.stringify(missionStartCall), async e => {
  8007. if (e['error']) {
  8008. isSendsMission = false;
  8009. console.log(e['error']);
  8010. setProgress('');
  8011. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  8012. await popup.confirm(msg, [
  8013. {msg: 'Ok', result: true},
  8014. ])
  8015. return;
  8016. }
  8017. /**
  8018. * Mission data calculation
  8019. *
  8020. * Расчет данных мисии
  8021. */
  8022. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  8023. /** missionTimer */
  8024. let timer = getTimer(r.battleTime) + 5;
  8025. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  8026. if (period < timer) {
  8027. timer = timer - period;
  8028. await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`);
  8029. }
  8030.  
  8031. let missionEndCall = {
  8032. "calls": [{
  8033. "name": "missionEnd",
  8034. "args": {
  8035. "id": param.id,
  8036. "result": r.result,
  8037. "progress": r.progress
  8038. },
  8039. "ident": "body"
  8040. }]
  8041. }
  8042. /**
  8043. * Mission Completion Request
  8044. *
  8045. * Запрос на завершение миссии
  8046. */
  8047. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  8048. if (e['error']) {
  8049. isSendsMission = false;
  8050. console.log(e['error']);
  8051. setProgress('');
  8052. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  8053. await popup.confirm(msg, [
  8054. {msg: 'Ok', result: true},
  8055. ])
  8056. return;
  8057. }
  8058. r = e.results[0].result.response;
  8059. if (r['error']) {
  8060. isSendsMission = false;
  8061. console.log(r['error']);
  8062. setProgress('');
  8063. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  8064. {msg: 'Ok', result: true},
  8065. ])
  8066. return;
  8067. }
  8068.  
  8069. param.count++;
  8070. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  8071. isStopSendMission = true;
  8072. });
  8073. setTimeout(sendsMission, 1, param);
  8074. });
  8075. })
  8076. });
  8077. }
  8078.  
  8079. /**
  8080. * Opening of russian dolls
  8081. *
  8082. * Открытие матрешек
  8083. */
  8084. async function openRussianDolls(libId, amount) {
  8085. let sum = 0;
  8086. const sumResult = {};
  8087. let count = 0;
  8088.  
  8089. while (amount) {
  8090. sum += amount;
  8091. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  8092. const calls = [
  8093. {
  8094. name: 'consumableUseLootBox',
  8095. args: { libId, amount },
  8096. ident: 'body',
  8097. },
  8098. ];
  8099. const response = await Send(JSON.stringify({ calls })).then((e) => e.results[0].result.response);
  8100. let [countLootBox, result] = Object.entries(response).pop();
  8101. count += +countLootBox;
  8102. let newCount = 0;
  8103.  
  8104. if (result?.consumable && result.consumable[libId]) {
  8105. newCount = result.consumable[libId];
  8106. delete result.consumable[libId];
  8107. }
  8108.  
  8109. mergeItemsObj(sumResult, result);
  8110. amount = newCount;
  8111. }
  8112.  
  8113. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  8114. return [count, sumResult];
  8115. }
  8116.  
  8117. function mergeItemsObj(obj1, obj2) {
  8118. for (const key in obj2) {
  8119. if (obj1[key]) {
  8120. if (typeof obj1[key] == 'object') {
  8121. for (const innerKey in obj2[key]) {
  8122. obj1[key][innerKey] = (obj1[key][innerKey] || 0) + obj2[key][innerKey];
  8123. }
  8124. } else {
  8125. obj1[key] += obj2[key] || 0;
  8126. }
  8127. } else {
  8128. obj1[key] = obj2[key];
  8129. }
  8130. }
  8131.  
  8132. return obj1;
  8133. }
  8134.  
  8135. /**
  8136. * Collect all mail, except letters with energy and charges of the portal
  8137. *
  8138. * Собрать всю почту, кроме писем с энергией и зарядами портала
  8139. */
  8140. function mailGetAll() {
  8141. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  8142.  
  8143. return Send(getMailInfo).then(dataMail => {
  8144. const letters = dataMail.results[0].result.response.letters;
  8145. const letterIds = lettersFilter(letters);
  8146. if (!letterIds.length) {
  8147. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8148. return;
  8149. }
  8150.  
  8151. const calls = [
  8152. { name: "mailFarm", args: { letterIds }, ident: "body" }
  8153. ];
  8154.  
  8155. return Send(JSON.stringify({ calls })).then(res => {
  8156. const lettersIds = res.results[0].result.response;
  8157. if (lettersIds) {
  8158. const countLetters = Object.keys(lettersIds).length;
  8159. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  8160. }
  8161. });
  8162. });
  8163. }
  8164.  
  8165. /**
  8166. * Filters received emails
  8167. *
  8168. * Фильтрует получаемые письма
  8169. */
  8170. function lettersFilter(letters) {
  8171. const lettersIds = [];
  8172. for (let l in letters) {
  8173. letter = letters[l];
  8174. const reward = letter?.reward;
  8175. if (!reward || !Object.keys(reward).length) {
  8176. continue;
  8177. }
  8178. /**
  8179. * Mail Collection Exceptions
  8180. *
  8181. * Исключения на сбор писем
  8182. */
  8183. const isFarmLetter = !(
  8184. /** Portals // сферы портала */
  8185. (reward?.refillable ? reward.refillable[45] : false) ||
  8186. /** Energy // энергия */
  8187. (reward?.stamina ? reward.stamina : false) ||
  8188. /** accelerating energy gain // ускорение набора энергии */
  8189. (reward?.buff ? true : false) ||
  8190. /** VIP Points // вип очки */
  8191. (reward?.vipPoints ? reward.vipPoints : false) ||
  8192. /** souls of heroes // душы героев */
  8193. (reward?.fragmentHero ? true : false) ||
  8194. /** heroes // герои */
  8195. (reward?.bundleHeroReward ? true : false)
  8196. );
  8197. if (isFarmLetter) {
  8198. lettersIds.push(~~letter.id);
  8199. continue;
  8200. }
  8201. /**
  8202. * Если до окончания годности письма менее 24 часов,
  8203. * то оно собирается не смотря на исключения
  8204. */
  8205. const availableUntil = +letter?.availableUntil;
  8206. if (availableUntil) {
  8207. const maxTimeLeft = 24 * 60 * 60 * 1000;
  8208. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  8209. console.log('Time left:', timeLeft)
  8210. if (timeLeft < maxTimeLeft) {
  8211. lettersIds.push(~~letter.id);
  8212. continue;
  8213. }
  8214. }
  8215. }
  8216. return lettersIds;
  8217. }
  8218.  
  8219. /**
  8220. * Displaying information about the areas of the portal and attempts on the VG
  8221. *
  8222. * Отображение информации о сферах портала и попытках на ВГ
  8223. */
  8224. async function justInfo() {
  8225. return new Promise(async (resolve, reject) => {
  8226. const calls = [
  8227. {
  8228. name: 'userGetInfo',
  8229. args: {},
  8230. ident: 'userGetInfo',
  8231. },
  8232. {
  8233. name: 'clanWarGetInfo',
  8234. args: {},
  8235. ident: 'clanWarGetInfo',
  8236. },
  8237. {
  8238. name: 'titanArenaGetStatus',
  8239. args: {},
  8240. ident: 'titanArenaGetStatus',
  8241. },
  8242. {
  8243. name: 'quest_completeEasterEggQuest',
  8244. args: {},
  8245. ident: 'quest_completeEasterEggQuest',
  8246. },
  8247. ];
  8248. const result = await Send(JSON.stringify({ calls }));
  8249. const infos = result.results;
  8250. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  8251. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  8252. const arePointsMax = infos[1].result.response?.arePointsMax;
  8253. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  8254. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  8255.  
  8256. const sanctuaryButton = buttons['testAdventure'].button;
  8257. const sanctuaryDot = sanctuaryButton.querySelector('.scriptMenu_dot');
  8258. const clanWarButton = buttons['goToClanWar'].button;
  8259. const clanWarDot = clanWarButton.querySelector('.scriptMenu_dot');
  8260. const titansArenaButton = buttons['testTitanArena'].button;
  8261. const titansArenaDot = titansArenaButton.querySelector('.scriptMenu_dot');
  8262.  
  8263. if (portalSphere.amount) {
  8264. sanctuaryButton.classList.add('scriptMenu_attention');
  8265. sanctuaryDot.title = `${portalSphere.amount} ${I18N('PORTALS')}`;
  8266. sanctuaryDot.innerText = portalSphere.amount;
  8267. sanctuaryDot.style.backgroundColor = 'red';
  8268. } else {
  8269. sanctuaryButton.classList.remove('scriptMenu_attention');
  8270. }
  8271. if (clanWarMyTries && !arePointsMax) {
  8272. clanWarButton.classList.add('scriptMenu_attention');
  8273. clanWarDot.title = `${clanWarMyTries} ${I18N('ATTEMPTS')}`;
  8274. clanWarDot.innerText = clanWarMyTries;
  8275. clanWarDot.style.backgroundColor = 'red';
  8276. } else {
  8277. clanWarButton.classList.remove('scriptMenu_attention');
  8278. }
  8279.  
  8280. if (titansLevel < 7 && titansStatus == 'battle') { ;
  8281. titansArenaButton.classList.add('scriptMenu_attention');
  8282. titansArenaDot.title = `${titansLevel} ${I18N('LEVEL')}`;
  8283. titansArenaDot.innerText = titansLevel;
  8284. titansArenaDot.style.backgroundColor = 'red';
  8285. } else {
  8286. titansArenaButton.classList.remove('scriptMenu_attention');
  8287. }
  8288.  
  8289. const imgPortal =
  8290. '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';
  8291.  
  8292. setProgress('<img src="' + imgPortal + '" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  8293. resolve();
  8294. });
  8295. }
  8296.  
  8297. async function getDailyBonus() {
  8298. const dailyBonusInfo = await Send(JSON.stringify({
  8299. calls: [{
  8300. name: "dailyBonusGetInfo",
  8301. args: {},
  8302. ident: "body"
  8303. }]
  8304. })).then(e => e.results[0].result.response);
  8305. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  8306.  
  8307. if (!availableToday) {
  8308. console.log('Уже собрано');
  8309. return;
  8310. }
  8311.  
  8312. const currentVipPoints = +userInfo.vipPoints;
  8313. const dailyBonusStat = lib.getData('dailyBonusStatic');
  8314. const vipInfo = lib.getData('level').vip;
  8315. let currentVipLevel = 0;
  8316. for (let i in vipInfo) {
  8317. vipLvl = vipInfo[i];
  8318. if (currentVipPoints >= vipLvl.vipPoints) {
  8319. currentVipLevel = vipLvl.level;
  8320. }
  8321. }
  8322. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  8323.  
  8324. const calls = [{
  8325. name: "dailyBonusFarm",
  8326. args: {
  8327. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  8328. },
  8329. ident: "body"
  8330. }];
  8331.  
  8332. const result = await Send(JSON.stringify({ calls }));
  8333. if (result.error) {
  8334. console.error(result.error);
  8335. return;
  8336. }
  8337.  
  8338. const reward = result.results[0].result.response;
  8339. const type = Object.keys(reward).pop();
  8340. const itemId = Object.keys(reward[type]).pop();
  8341. const count = reward[type][itemId];
  8342. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  8343.  
  8344. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  8345. }
  8346.  
  8347. async function farmStamina(lootBoxId = 148) {
  8348. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  8349. .then(e => e.results[0].result.response.consumable[148]);
  8350.  
  8351. /** Добавить другие ящики */
  8352. /**
  8353. * 144 - медная шкатулка
  8354. * 145 - бронзовая шкатулка
  8355. * 148 - платиновая шкатулка
  8356. */
  8357. if (!lootBox) {
  8358. setProgress(I18N('NO_BOXES'), true);
  8359. return;
  8360. }
  8361.  
  8362. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  8363. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  8364. { result: false, isClose: true },
  8365. { msg: I18N('BTN_YES'), result: true },
  8366. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  8367. ]);
  8368. if (!+result) {
  8369. return;
  8370. }
  8371.  
  8372. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  8373. maxFarmEnergy = +result;
  8374. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  8375. } else {
  8376. maxFarmEnergy = 0;
  8377. }
  8378.  
  8379. let collectEnergy = 0;
  8380. for (let count = lootBox; count > 0; count--) {
  8381. const response = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}').then(
  8382. (e) => e.results[0].result.response
  8383. );
  8384. const result = Object.values(response).pop();
  8385. if ('stamina' in result) {
  8386. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8387. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  8388. if (!maxFarmEnergy) {
  8389. return;
  8390. }
  8391. collectEnergy += +result.stamina;
  8392. if (collectEnergy >= maxFarmEnergy) {
  8393. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  8394. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  8395. return;
  8396. }
  8397. } else {
  8398. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8399. console.log(result);
  8400. }
  8401. }
  8402.  
  8403. setProgress(I18N('BOXES_OVER'), true);
  8404. }
  8405.  
  8406. async function fillActive() {
  8407. const data = await Send(JSON.stringify({
  8408. calls: [{
  8409. name: "questGetAll",
  8410. args: {},
  8411. ident: "questGetAll"
  8412. }, {
  8413. name: "inventoryGet",
  8414. args: {},
  8415. ident: "inventoryGet"
  8416. }, {
  8417. name: "clanGetInfo",
  8418. args: {},
  8419. ident: "clanGetInfo"
  8420. }
  8421. ]
  8422. })).then(e => e.results.map(n => n.result.response));
  8423.  
  8424. const quests = data[0];
  8425. const inv = data[1];
  8426. const stat = data[2].stat;
  8427. const maxActive = 2000 - stat.todayItemsActivity;
  8428. if (maxActive <= 0) {
  8429. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  8430. return;
  8431. }
  8432. let countGetActive = 0;
  8433. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  8434. if (quest) {
  8435. countGetActive = 1750 - quest.progress;
  8436. }
  8437. if (countGetActive <= 0) {
  8438. countGetActive = maxActive;
  8439. }
  8440. console.log(countGetActive);
  8441.  
  8442. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  8443. { result: false, isClose: true },
  8444. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  8445. ]));
  8446.  
  8447. if (!countGetActive) {
  8448. return;
  8449. }
  8450.  
  8451. if (countGetActive > maxActive) {
  8452. countGetActive = maxActive;
  8453. }
  8454.  
  8455. const items = lib.getData('inventoryItem');
  8456.  
  8457. let itemsInfo = [];
  8458. for (let type of ['gear', 'scroll']) {
  8459. for (let i in inv[type]) {
  8460. const v = items[type][i]?.enchantValue || 0;
  8461. itemsInfo.push({
  8462. id: i,
  8463. count: inv[type][i],
  8464. v,
  8465. type
  8466. })
  8467. }
  8468. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  8469. for (let i in inv[invType]) {
  8470. const v = items[type][i]?.fragmentEnchantValue || 0;
  8471. itemsInfo.push({
  8472. id: i,
  8473. count: inv[invType][i],
  8474. v,
  8475. type: invType
  8476. })
  8477. }
  8478. }
  8479. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  8480. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  8481. console.log(itemsInfo);
  8482. const activeItem = itemsInfo.shift();
  8483. console.log(activeItem);
  8484. const countItem = Math.ceil(countGetActive / activeItem.v);
  8485. if (countItem > activeItem.count) {
  8486. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  8487. console.log(activeItem);
  8488. return;
  8489. }
  8490.  
  8491. await Send(JSON.stringify({
  8492. calls: [{
  8493. name: "clanItemsForActivity",
  8494. args: {
  8495. items: {
  8496. [activeItem.type]: {
  8497. [activeItem.id]: countItem
  8498. }
  8499. }
  8500. },
  8501. ident: "body"
  8502. }]
  8503. })).then(e => {
  8504. /** TODO: Вывести потраченые предметы */
  8505. console.log(e);
  8506. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  8507. });
  8508. }
  8509.  
  8510. async function buyHeroFragments() {
  8511. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  8512. .then(e => e.results.map(n => n.result.response));
  8513. const inv = result[0];
  8514. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  8515. const calls = [];
  8516.  
  8517. for (let shop of shops) {
  8518. const slots = Object.values(shop.slots);
  8519. for (const slot of slots) {
  8520. /* Уже куплено */
  8521. if (slot.bought) {
  8522. continue;
  8523. }
  8524. /* Не душа героя */
  8525. if (!('fragmentHero' in slot.reward)) {
  8526. continue;
  8527. }
  8528. const coin = Object.keys(slot.cost).pop();
  8529. const coinId = Object.keys(slot.cost[coin]).pop();
  8530. const stock = inv[coin][coinId] || 0;
  8531. /* Не хватает на покупку */
  8532. if (slot.cost[coin][coinId] > stock) {
  8533. continue;
  8534. }
  8535. inv[coin][coinId] -= slot.cost[coin][coinId];
  8536. calls.push({
  8537. name: "shopBuy",
  8538. args: {
  8539. shopId: shop.id,
  8540. slot: slot.id,
  8541. cost: slot.cost,
  8542. reward: slot.reward,
  8543. },
  8544. ident: `shopBuy_${shop.id}_${slot.id}`,
  8545. })
  8546. }
  8547. }
  8548.  
  8549. if (!calls.length) {
  8550. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  8551. return;
  8552. }
  8553.  
  8554. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8555. if (!bought) {
  8556. console.log('что-то пошло не так')
  8557. return;
  8558. }
  8559.  
  8560. let countHeroSouls = 0;
  8561. for (const buy of bought) {
  8562. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  8563. }
  8564. console.log(countHeroSouls, bought, calls);
  8565. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  8566. }
  8567.  
  8568. /** Открыть платные сундуки в Запределье за 90 */
  8569. async function bossOpenChestPay() {
  8570. const callsNames = ['userGetInfo', 'bossGetAll', 'specialOffer_getAll', 'getTime'];
  8571. const info = await Send({ calls: callsNames.map((name) => ({ name, args: {}, ident: name })) }).then((e) =>
  8572. e.results.map((n) => n.result.response)
  8573. );
  8574.  
  8575. const user = info[0];
  8576. const boses = info[1];
  8577. const offers = info[2];
  8578. const time = info[3];
  8579.  
  8580. const discountOffer = offers.find((e) => e.offerType == 'costReplaceOutlandChest');
  8581.  
  8582. let discount = 1;
  8583. if (discountOffer && discountOffer.endTime > time) {
  8584. discount = 1 - discountOffer.offerData.outlandChest.discountPercent / 100;
  8585. }
  8586.  
  8587. cost9chests = 540 * discount;
  8588. cost18chests = 1740 * discount;
  8589. costFirstChest = 90 * discount;
  8590. costSecondChest = 200 * discount;
  8591.  
  8592. const currentStarMoney = user.starMoney;
  8593. if (currentStarMoney < cost9chests) {
  8594. setProgress('Недостаточно изюма, нужно ' + cost9chests + ' у Вас ' + currentStarMoney, true);
  8595. return;
  8596. }
  8597.  
  8598. const imgEmerald =
  8599. "<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='>";
  8600.  
  8601. if (currentStarMoney < cost9chests) {
  8602. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney, imgEmerald }), true);
  8603. return;
  8604. }
  8605.  
  8606. const buttons = [{ result: false, isClose: true }];
  8607.  
  8608. if (currentStarMoney >= cost9chests) {
  8609. buttons.push({
  8610. msg: I18N('BUY_OUTLAND_BTN', { count: 9, countEmerald: cost9chests, imgEmerald }),
  8611. result: [costFirstChest, costFirstChest, 0],
  8612. });
  8613. }
  8614.  
  8615. if (currentStarMoney >= cost18chests) {
  8616. buttons.push({
  8617. msg: I18N('BUY_OUTLAND_BTN', { count: 18, countEmerald: cost18chests, imgEmerald }),
  8618. result: [costFirstChest, costFirstChest, 0, costSecondChest, costSecondChest, 0],
  8619. });
  8620. }
  8621.  
  8622. const answer = await popup.confirm(`<div style="margin-bottom: 15px;">${I18N('BUY_OUTLAND')}</div>`, buttons);
  8623.  
  8624. if (!answer) {
  8625. return;
  8626. }
  8627.  
  8628. const callBoss = [];
  8629. let n = 0;
  8630. for (let boss of boses) {
  8631. const bossId = boss.id;
  8632. if (boss.chestNum != 2) {
  8633. continue;
  8634. }
  8635. const calls = [];
  8636. for (const starmoney of answer) {
  8637. calls.push({
  8638. name: 'bossOpenChest',
  8639. args: {
  8640. amount: 1,
  8641. bossId,
  8642. starmoney,
  8643. },
  8644. ident: 'bossOpenChest_' + ++n,
  8645. });
  8646. }
  8647. callBoss.push(calls);
  8648. }
  8649.  
  8650. if (!callBoss.length) {
  8651. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  8652. return;
  8653. }
  8654.  
  8655. let count = 0;
  8656. let errors = 0;
  8657. for (const calls of callBoss) {
  8658. const result = await Send({ calls });
  8659. console.log(result);
  8660. if (result?.results) {
  8661. count += result.results.length;
  8662. } else {
  8663. errors++;
  8664. }
  8665. }
  8666.  
  8667. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ${count}`, true);
  8668. }
  8669.  
  8670. async function autoRaidAdventure() {
  8671. const calls = [
  8672. {
  8673. name: "userGetInfo",
  8674. args: {},
  8675. ident: "userGetInfo"
  8676. },
  8677. {
  8678. name: "adventure_raidGetInfo",
  8679. args: {},
  8680. ident: "adventure_raidGetInfo"
  8681. }
  8682. ];
  8683. const result = await Send(JSON.stringify({ calls }))
  8684. .then(e => e.results.map(n => n.result.response));
  8685.  
  8686. const portalSphere = result[0].refillable.find(n => n.id == 45);
  8687. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  8688. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  8689.  
  8690. if (!portalSphere.amount || !adventureId) {
  8691. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  8692. return;
  8693. }
  8694.  
  8695. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  8696. { result: false, isClose: true },
  8697. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  8698. ]));
  8699.  
  8700. if (!countRaid) {
  8701. return;
  8702. }
  8703.  
  8704. if (countRaid > portalSphere.amount) {
  8705. countRaid = portalSphere.amount;
  8706. }
  8707.  
  8708. const resultRaid = await Send(JSON.stringify({
  8709. calls: [...Array(countRaid)].map((e, i) => ({
  8710. name: "adventure_raid",
  8711. args: {
  8712. adventureId
  8713. },
  8714. ident: `body_${i}`
  8715. }))
  8716. })).then(e => e.results.map(n => n.result.response));
  8717.  
  8718. if (!resultRaid.length) {
  8719. console.log(resultRaid);
  8720. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  8721. return;
  8722. }
  8723.  
  8724. console.log(resultRaid, adventureId, portalSphere.amount);
  8725. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  8726. }
  8727.  
  8728. /** Вывести всю клановую статистику в консоль браузера */
  8729. async function clanStatistic() {
  8730. const copy = function (text) {
  8731. const copyTextarea = document.createElement("textarea");
  8732. copyTextarea.style.opacity = "0";
  8733. copyTextarea.textContent = text;
  8734. document.body.appendChild(copyTextarea);
  8735. copyTextarea.select();
  8736. document.execCommand("copy");
  8737. document.body.removeChild(copyTextarea);
  8738. delete copyTextarea;
  8739. }
  8740. const calls = [
  8741. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  8742. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  8743. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  8744. ];
  8745.  
  8746. const result = await Send(JSON.stringify({ calls }));
  8747.  
  8748. const dataClanInfo = result.results[0].result.response;
  8749. const dataClanStat = result.results[1].result.response;
  8750. const dataClanLog = result.results[2].result.response;
  8751.  
  8752. const membersStat = {};
  8753. for (let i = 0; i < dataClanStat.stat.length; i++) {
  8754. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  8755. }
  8756.  
  8757. const joinStat = {};
  8758. historyLog = dataClanLog.history;
  8759. for (let j in historyLog) {
  8760. his = historyLog[j];
  8761. if (his.event == 'join') {
  8762. joinStat[his.userId] = his.ctime;
  8763. }
  8764. }
  8765.  
  8766. const infoArr = [];
  8767. const members = dataClanInfo.clan.members;
  8768. for (let n in members) {
  8769. var member = [
  8770. n,
  8771. members[n].name,
  8772. members[n].level,
  8773. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  8774. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  8775. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  8776. membersStat[n].activity.reverse().join('\t'),
  8777. membersStat[n].adventureStat.reverse().join('\t'),
  8778. membersStat[n].clanGifts.reverse().join('\t'),
  8779. membersStat[n].clanWarStat.reverse().join('\t'),
  8780. membersStat[n].dungeonActivity.reverse().join('\t'),
  8781. ];
  8782. infoArr.push(member);
  8783. }
  8784. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  8785. console.log(info);
  8786. copy(info);
  8787. setProgress(I18N('CLAN_STAT_COPY'), true);
  8788. }
  8789.  
  8790. async function buyInStoreForGold() {
  8791. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  8792. const shops = result[0];
  8793. const user = result[1];
  8794. let gold = user.gold;
  8795. const calls = [];
  8796. if (shops[17]) {
  8797. const slots = shops[17].slots;
  8798. for (let i = 1; i <= 2; i++) {
  8799. if (!slots[i].bought) {
  8800. const costGold = slots[i].cost.gold;
  8801. if ((gold - costGold) < 0) {
  8802. continue;
  8803. }
  8804. gold -= costGold;
  8805. calls.push({
  8806. name: "shopBuy",
  8807. args: {
  8808. shopId: 17,
  8809. slot: i,
  8810. cost: slots[i].cost,
  8811. reward: slots[i].reward,
  8812. },
  8813. ident: 'body_' + i,
  8814. })
  8815. }
  8816. }
  8817. }
  8818. const slots = shops[1].slots;
  8819. for (let i = 4; i <= 6; i++) {
  8820. if (!slots[i].bought && slots[i]?.cost?.gold) {
  8821. const costGold = slots[i].cost.gold;
  8822. if ((gold - costGold) < 0) {
  8823. continue;
  8824. }
  8825. gold -= costGold;
  8826. calls.push({
  8827. name: "shopBuy",
  8828. args: {
  8829. shopId: 1,
  8830. slot: i,
  8831. cost: slots[i].cost,
  8832. reward: slots[i].reward,
  8833. },
  8834. ident: 'body_' + i,
  8835. })
  8836. }
  8837. }
  8838.  
  8839. if (!calls.length) {
  8840. setProgress(I18N('NOTHING_BUY'), true);
  8841. return;
  8842. }
  8843.  
  8844. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8845. console.log(resultBuy);
  8846. const countBuy = resultBuy.length;
  8847. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  8848. }
  8849.  
  8850. function rewardsAndMailFarm() {
  8851. return new Promise(function (resolve, reject) {
  8852. let questGetAllCall = {
  8853. calls: [{
  8854. name: "questGetAll",
  8855. args: {},
  8856. ident: "questGetAll"
  8857. }, {
  8858. name: "mailGetAll",
  8859. args: {},
  8860. ident: "mailGetAll"
  8861. }]
  8862. }
  8863. send(JSON.stringify(questGetAllCall), function (data) {
  8864. if (!data) return;
  8865. const questGetAll = data.results[0].result.response.filter((e) => e.state == 2);
  8866. const questBattlePass = lib.getData('quest').battlePass;
  8867. const questChainBPass = lib.getData('battlePass').questChain;
  8868. const listBattlePass = lib.getData('battlePass').list;
  8869.  
  8870. const questAllFarmCall = {
  8871. calls: [],
  8872. };
  8873. const questIds = [];
  8874. for (let quest of questGetAll) {
  8875. if (quest.id >= 2001e4) {
  8876. continue;
  8877. }
  8878. if (quest.id > 1e6 && quest.id < 2e7) {
  8879. const questInfo = questBattlePass[quest.id];
  8880. const chain = questChainBPass[questInfo.chain];
  8881. if (chain.requirement?.battlePassTicket) {
  8882. continue;
  8883. }
  8884. const battlePass = listBattlePass[chain.battlePass];
  8885. const startTime = battlePass.startCondition.time.value * 1e3
  8886. const endTime = new Date(startTime + battlePass.duration * 1e3);
  8887. if (startTime > Date.now() || endTime < Date.now()) {
  8888. continue;
  8889. }
  8890. }
  8891. if (quest.id >= 2e7) {
  8892. questIds.push(quest.id);
  8893. continue;
  8894. }
  8895. questAllFarmCall.calls.push({
  8896. name: 'questFarm',
  8897. args: {
  8898. questId: quest.id,
  8899. },
  8900. ident: `questFarm_${quest.id}`,
  8901. });
  8902. }
  8903.  
  8904. if (questIds.length) {
  8905. questAllFarmCall.calls.push({
  8906. name: 'quest_questsFarm',
  8907. args: { questIds },
  8908. ident: 'quest_questsFarm',
  8909. });
  8910. }
  8911.  
  8912. let letters = data?.results[1]?.result?.response?.letters;
  8913. letterIds = lettersFilter(letters);
  8914.  
  8915. if (letterIds.length) {
  8916. questAllFarmCall.calls.push({
  8917. name: 'mailFarm',
  8918. args: { letterIds },
  8919. ident: 'mailFarm',
  8920. });
  8921. }
  8922.  
  8923. if (!questAllFarmCall.calls.length) {
  8924. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8925. resolve();
  8926. return;
  8927. }
  8928.  
  8929. send(JSON.stringify(questAllFarmCall), async function (res) {
  8930. let countQuests = 0;
  8931. let countMail = 0;
  8932. let questsIds = [];
  8933. for (let call of res.results) {
  8934. if (call.ident.includes('questFarm')) {
  8935. countQuests++;
  8936. } else if (call.ident.includes('questsFarm')) {
  8937. countQuests += Object.keys(call.result.response).length;
  8938. } else if (call.ident.includes('mailFarm')) {
  8939. countMail = Object.keys(call.result.response).length;
  8940. }
  8941.  
  8942. const newQuests = call.result.newQuests;
  8943. if (newQuests) {
  8944. for (let quest of newQuests) {
  8945. if ((quest.id < 1e6 || (quest.id >= 2e7 && quest.id < 2001e4)) && quest.state == 2) {
  8946. questsIds.push(quest.id);
  8947. }
  8948. }
  8949. }
  8950. }
  8951.  
  8952. while (questsIds.length) {
  8953. const questIds = [];
  8954. const calls = [];
  8955. for (let questId of questsIds) {
  8956. if (questId < 1e6) {
  8957. calls.push({
  8958. name: 'questFarm',
  8959. args: {
  8960. questId,
  8961. },
  8962. ident: `questFarm_${questId}`,
  8963. });
  8964. countQuests++;
  8965. } else if (questId >= 2e7 && questId < 2001e4) {
  8966. questIds.push(questId);
  8967. countQuests++;
  8968. }
  8969. }
  8970. calls.push({
  8971. name: 'quest_questsFarm',
  8972. args: { questIds },
  8973. ident: 'body',
  8974. });
  8975. const results = await Send({ calls }).then((e) => e.results.map((e) => e.result));
  8976. questsIds = [];
  8977. for (const result of results) {
  8978. const newQuests = result.newQuests;
  8979. if (newQuests) {
  8980. for (let quest of newQuests) {
  8981. if (quest.state == 2) {
  8982. questsIds.push(quest.id);
  8983. }
  8984. }
  8985. }
  8986. }
  8987. }
  8988.  
  8989. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  8990. resolve();
  8991. });
  8992. });
  8993. })
  8994. }
  8995.  
  8996. class epicBrawl {
  8997. timeout = null;
  8998. time = null;
  8999.  
  9000. constructor() {
  9001. if (epicBrawl.inst) {
  9002. return epicBrawl.inst;
  9003. }
  9004. epicBrawl.inst = this;
  9005. return this;
  9006. }
  9007.  
  9008. runTimeout(func, timeDiff) {
  9009. const worker = new Worker(URL.createObjectURL(new Blob([`
  9010. self.onmessage = function(e) {
  9011. const timeDiff = e.data;
  9012.  
  9013. if (timeDiff > 0) {
  9014. setTimeout(() => {
  9015. self.postMessage(1);
  9016. self.close();
  9017. }, timeDiff);
  9018. }
  9019. };
  9020. `])));
  9021. worker.postMessage(timeDiff);
  9022. worker.onmessage = () => {
  9023. func();
  9024. };
  9025. return true;
  9026. }
  9027.  
  9028. timeDiff(date1, date2) {
  9029. const date1Obj = new Date(date1);
  9030. const date2Obj = new Date(date2);
  9031.  
  9032. const timeDiff = Math.abs(date2Obj - date1Obj);
  9033.  
  9034. const totalSeconds = timeDiff / 1000;
  9035. const minutes = Math.floor(totalSeconds / 60);
  9036. const seconds = Math.floor(totalSeconds % 60);
  9037.  
  9038. const formattedMinutes = String(minutes).padStart(2, '0');
  9039. const formattedSeconds = String(seconds).padStart(2, '0');
  9040.  
  9041. return `${formattedMinutes}:${formattedSeconds}`;
  9042. }
  9043.  
  9044. check() {
  9045. console.log(new Date(this.time))
  9046. if (Date.now() > this.time) {
  9047. this.timeout = null;
  9048. this.start()
  9049. return;
  9050. }
  9051. this.timeout = this.runTimeout(() => this.check(), 6e4);
  9052. return this.timeDiff(this.time, Date.now())
  9053. }
  9054.  
  9055. async start() {
  9056. if (this.timeout) {
  9057. const time = this.timeDiff(this.time, Date.now());
  9058. console.log(new Date(this.time))
  9059. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  9060. return;
  9061. }
  9062. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  9063. 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));
  9064. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  9065. this.time = (refill.lastRefill + 3600) * 1000
  9066. const attempts = refill.amount;
  9067. if (!attempts) {
  9068. console.log(new Date(this.time));
  9069. const time = this.check();
  9070. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  9071. return;
  9072. }
  9073.  
  9074. if (!teamInfo[0].epic_brawl) {
  9075. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  9076. return;
  9077. }
  9078.  
  9079. const args = {
  9080. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  9081. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  9082. favor: teamInfo[1].epic_brawl,
  9083. }
  9084.  
  9085. let wins = 0;
  9086. let coins = 0;
  9087. let streak = { progress: 0, nextStage: 0 };
  9088. for (let i = attempts; i > 0; i--) {
  9089. const info = await Send(JSON.stringify({
  9090. calls: [
  9091. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  9092. ]
  9093. })).then(e => e.results.map(n => n.result.response));
  9094.  
  9095. const { progress, result } = await Calc(info[1].battle);
  9096. 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));
  9097.  
  9098. const resultInfo = endResult[0].result;
  9099. streak = endResult[1];
  9100.  
  9101. wins += resultInfo.win;
  9102. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  9103.  
  9104. console.log(endResult[0].result)
  9105. if (endResult[1].progress == endResult[1].nextStage) {
  9106. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  9107. coins += farm.coin[39];
  9108. }
  9109.  
  9110. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9111. i, wins, attempts, coins,
  9112. progress: streak.progress,
  9113. nextStage: streak.nextStage,
  9114. end: '',
  9115. }), false, hideProgress);
  9116. }
  9117.  
  9118. console.log(new Date(this.time));
  9119. const time = this.check();
  9120. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9121. wins, attempts, coins,
  9122. i: '',
  9123. progress: streak.progress,
  9124. nextStage: streak.nextStage,
  9125. end: I18N('ATTEMPT_ENDED', { time }),
  9126. }), false, hideProgress);
  9127. }
  9128. }
  9129.  
  9130. function countdownTimer(seconds, message) {
  9131. message = message || I18N('TIMER');
  9132. const stopTimer = Date.now() + seconds * 1e3
  9133. return new Promise(resolve => {
  9134. const interval = setInterval(async () => {
  9135. const now = Date.now();
  9136. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  9137. if (now > stopTimer) {
  9138. clearInterval(interval);
  9139. setProgress('', 1);
  9140. resolve();
  9141. }
  9142. }, 100);
  9143. });
  9144. }
  9145.  
  9146. this.HWHFuncs.countdownTimer = countdownTimer;
  9147.  
  9148. /** Набить килов в горниле душк */
  9149. async function bossRatingEventSouls() {
  9150. const data = await Send({
  9151. calls: [
  9152. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  9153. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  9154. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  9155. ]
  9156. });
  9157. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  9158. if (!bossEventInfo) {
  9159. setProgress('Эвент завершен', true);
  9160. return;
  9161. }
  9162.  
  9163. if (bossEventInfo.progress.score > 250) {
  9164. setProgress('Уже убито больше 250 врагов');
  9165. rewardBossRatingEventSouls();
  9166. return;
  9167. }
  9168. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  9169. const heroGetAllList = data.results[0].result.response;
  9170. const usedHeroes = bossEventInfo.progress.usedHeroes;
  9171. const heroList = [];
  9172.  
  9173. for (let heroId in heroGetAllList) {
  9174. let hero = heroGetAllList[heroId];
  9175. if (usedHeroes.includes(hero.id)) {
  9176. continue;
  9177. }
  9178. heroList.push(hero.id);
  9179. }
  9180.  
  9181. if (!heroList.length) {
  9182. setProgress('Нет героев', true);
  9183. return;
  9184. }
  9185.  
  9186. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  9187. const petLib = lib.getData('pet');
  9188. let count = 1;
  9189.  
  9190. for (const heroId of heroList) {
  9191. const args = {
  9192. heroes: [heroId],
  9193. pet
  9194. }
  9195. /** Поиск питомца для героя */
  9196. for (const petId of availablePets) {
  9197. if (petLib[petId].favorHeroes.includes(heroId)) {
  9198. args.favor = {
  9199. [heroId]: petId
  9200. }
  9201. break;
  9202. }
  9203. }
  9204.  
  9205. const calls = [{
  9206. name: "bossRatingEvent_startBattle",
  9207. args,
  9208. ident: "body"
  9209. }, {
  9210. name: "offerGetAll",
  9211. args: {},
  9212. ident: "offerGetAll"
  9213. }];
  9214.  
  9215. const res = await Send({ calls });
  9216. count++;
  9217.  
  9218. if ('error' in res) {
  9219. console.error(res.error);
  9220. setProgress('Перезагрузите игру и попробуйте позже', true);
  9221. return;
  9222. }
  9223.  
  9224. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  9225. if (eventInfo.progress.score > 250) {
  9226. break;
  9227. }
  9228. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  9229. }
  9230.  
  9231. rewardBossRatingEventSouls();
  9232. }
  9233. /** Сбор награды из Горнила Душ */
  9234. async function rewardBossRatingEventSouls() {
  9235. const data = await Send({
  9236. calls: [
  9237. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  9238. ]
  9239. });
  9240.  
  9241. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  9242. if (!bossEventInfo) {
  9243. setProgress('Эвент завершен', true);
  9244. return;
  9245. }
  9246.  
  9247. const farmedChests = bossEventInfo.progress.farmedChests;
  9248. const score = bossEventInfo.progress.score;
  9249. // setProgress('Количество убитых врагов: ' + score);
  9250. const revard = bossEventInfo.reward;
  9251. const calls = [];
  9252.  
  9253. let count = 0;
  9254. for (let i = 1; i < 10; i++) {
  9255. if (farmedChests.includes(i)) {
  9256. continue;
  9257. }
  9258. if (score < revard[i].score) {
  9259. break;
  9260. }
  9261. calls.push({
  9262. name: "bossRatingEvent_getReward",
  9263. args: {
  9264. rewardId: i
  9265. },
  9266. ident: "body_" + i
  9267. });
  9268. count++;
  9269. }
  9270. if (!count) {
  9271. setProgress('Нечего собирать', true);
  9272. return;
  9273. }
  9274.  
  9275. Send({ calls }).then(e => {
  9276. console.log(e);
  9277. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  9278. })
  9279. }
  9280. /**
  9281. * Spin the Seer
  9282. *
  9283. * Покрутить провидца
  9284. */
  9285. async function rollAscension() {
  9286. const refillable = await Send({calls:[
  9287. {
  9288. name:"userGetInfo",
  9289. args:{},
  9290. ident:"userGetInfo"
  9291. }
  9292. ]}).then(e => e.results[0].result.response.refillable);
  9293. const i47 = refillable.find(i => i.id == 47);
  9294. if (i47?.amount) {
  9295. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  9296. setProgress(I18N('DONE'), true);
  9297. } else {
  9298. setProgress(I18N('NOT_ENOUGH_AP'), true);
  9299. }
  9300. }
  9301.  
  9302. /**
  9303. * Collect gifts for the New Year
  9304. *
  9305. * Собрать подарки на новый год
  9306. */
  9307. function getGiftNewYear() {
  9308. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  9309. const gifts = e.results[0].result.response.gifts;
  9310. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  9311. name: "newYearGiftOpen",
  9312. args: {
  9313. giftId: e.id
  9314. },
  9315. ident: `body_${e.id}`
  9316. }));
  9317. if (!calls.length) {
  9318. setProgress(I18N('NY_NO_GIFTS'), 5000);
  9319. return;
  9320. }
  9321. Send({ calls }).then(e => {
  9322. console.log(e.results)
  9323. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  9324. console.log(msg);
  9325. setProgress(msg, 5000);
  9326. });
  9327. })
  9328. }
  9329.  
  9330. async function updateArtifacts() {
  9331. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9332. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9333. { result: false, isClose: true }
  9334. ]);
  9335. if (!count) {
  9336. return;
  9337. }
  9338. const quest = new questRun;
  9339. await quest.autoInit();
  9340. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9341. const inventory = quest.questInfo['inventoryGet'];
  9342. const calls = [];
  9343. for (let i = count; i > 0; i--) {
  9344. const upArtifact = quest.getUpgradeArtifact();
  9345. if (!upArtifact.heroId) {
  9346. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9347. { msg: I18N('YES'), result: true },
  9348. { result: false, isClose: true }
  9349. ])) {
  9350. break;
  9351. } else {
  9352. return;
  9353. }
  9354. }
  9355. const hero = heroes.find(e => e.id == upArtifact.heroId);
  9356. hero.artifacts[upArtifact.slotId].level++;
  9357. inventory[upArtifact.costCurrency][upArtifact.costId] -= upArtifact.costValue;
  9358. calls.push({
  9359. name: "heroArtifactLevelUp",
  9360. args: {
  9361. heroId: upArtifact.heroId,
  9362. slotId: upArtifact.slotId
  9363. },
  9364. ident: `heroArtifactLevelUp_${i}`
  9365. });
  9366. }
  9367.  
  9368. if (!calls.length) {
  9369. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9370. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9371. return;
  9372. }
  9373.  
  9374. await Send(JSON.stringify({ calls })).then(e => {
  9375. if ('error' in e) {
  9376. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9377. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9378. } else {
  9379. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9380. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9381. }
  9382. });
  9383. }
  9384.  
  9385. window.sign = a => {
  9386. const i = this['\x78\x79\x7a'];
  9387. 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'))
  9388. }
  9389.  
  9390. async function updateSkins() {
  9391. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9392. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9393. { result: false, isClose: true }
  9394. ]);
  9395. if (!count) {
  9396. return;
  9397. }
  9398.  
  9399. const quest = new questRun;
  9400. await quest.autoInit();
  9401. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9402. const inventory = quest.questInfo['inventoryGet'];
  9403. const calls = [];
  9404. for (let i = count; i > 0; i--) {
  9405. const upSkin = quest.getUpgradeSkin();
  9406. if (!upSkin.heroId) {
  9407. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9408. { msg: I18N('YES'), result: true },
  9409. { result: false, isClose: true }
  9410. ])) {
  9411. break;
  9412. } else {
  9413. return;
  9414. }
  9415. }
  9416. const hero = heroes.find(e => e.id == upSkin.heroId);
  9417. hero.skins[upSkin.skinId]++;
  9418. inventory[upSkin.costCurrency][upSkin.costCurrencyId] -= upSkin.cost;
  9419. calls.push({
  9420. name: "heroSkinUpgrade",
  9421. args: {
  9422. heroId: upSkin.heroId,
  9423. skinId: upSkin.skinId
  9424. },
  9425. ident: `heroSkinUpgrade_${i}`
  9426. })
  9427. }
  9428.  
  9429. if (!calls.length) {
  9430. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9431. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9432. return;
  9433. }
  9434.  
  9435. await Send(JSON.stringify({ calls })).then(e => {
  9436. if ('error' in e) {
  9437. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9438. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9439. } else {
  9440. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9441. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9442. }
  9443. });
  9444. }
  9445.  
  9446. function getQuestionInfo(img, nameOnly = false) {
  9447. const libHeroes = Object.values(lib.data.hero);
  9448. const parts = img.split(':');
  9449. const id = parts[1];
  9450. switch (parts[0]) {
  9451. case 'titanArtifact_id':
  9452. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  9453. case 'titan':
  9454. return cheats.translate("LIB_HERO_NAME_" + id);
  9455. case 'skill':
  9456. return cheats.translate("LIB_SKILL_" + id);
  9457. case 'inventoryItem_gear':
  9458. return cheats.translate("LIB_GEAR_NAME_" + id);
  9459. case 'inventoryItem_coin':
  9460. return cheats.translate("LIB_COIN_NAME_" + id);
  9461. case 'artifact':
  9462. if (nameOnly) {
  9463. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  9464. }
  9465. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  9466. return {
  9467. /** Как называется этот артефакт? */
  9468. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  9469. /** Какому герою принадлежит этот артефакт? */
  9470. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  9471. };
  9472. case 'hero':
  9473. if (nameOnly) {
  9474. return cheats.translate("LIB_HERO_NAME_" + id);
  9475. }
  9476. artifacts = lib.data.hero[id].artifacts;
  9477. return {
  9478. /** Как зовут этого героя? */
  9479. name: cheats.translate("LIB_HERO_NAME_" + id),
  9480. /** Какой артефакт принадлежит этому герою? */
  9481. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  9482. };
  9483. }
  9484. }
  9485.  
  9486. function hintQuest(quest) {
  9487. const result = {};
  9488. if (quest?.questionIcon) {
  9489. const info = getQuestionInfo(quest.questionIcon);
  9490. if (info?.heroes) {
  9491. /** Какому герою принадлежит этот артефакт? */
  9492. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  9493. }
  9494. if (info?.artifact) {
  9495. /** Какой артефакт принадлежит этому герою? */
  9496. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  9497. }
  9498. if (typeof info == 'string') {
  9499. result.info = { name: info };
  9500. } else {
  9501. result.info = info;
  9502. }
  9503. }
  9504.  
  9505. if (quest.answers[0]?.answerIcon) {
  9506. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  9507. }
  9508.  
  9509. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  9510. return false;
  9511. }
  9512.  
  9513. let resultText = '';
  9514. if (result?.info) {
  9515. resultText += I18N('PICTURE') + result.info.name;
  9516. }
  9517. console.log(result);
  9518. if (result?.answer && result.answer.length) {
  9519. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  9520. }
  9521.  
  9522. return resultText;
  9523. }
  9524.  
  9525. async function farmBattlePass() {
  9526. const isFarmReward = (reward) => {
  9527. return !(reward?.buff || reward?.fragmentHero || reward?.bundleHeroReward);
  9528. };
  9529.  
  9530. const battlePassProcess = (pass) => {
  9531. if (!pass.id) {return []}
  9532. const levels = Object.values(lib.data.battlePass.level).filter(x => x.battlePass == pass.id)
  9533. const last_level = levels[levels.length - 1];
  9534. let actual = Math.max(...levels.filter(p => pass.exp >= p.experience).map(p => p.level))
  9535.  
  9536. if (pass.exp > last_level.experience) {
  9537. actual = last_level.level + (pass.exp - last_level.experience) / last_level.experienceByLevel;
  9538. }
  9539. const calls = [];
  9540. for(let i = 1; i <= actual; i++) {
  9541. const level = i >= last_level.level ? last_level : levels.find(l => l.level === i);
  9542. const reward = {free: level?.freeReward, paid:level?.paidReward};
  9543.  
  9544. if (!pass.rewards[i]?.free && isFarmReward(reward.free)) {
  9545. const args = {level: i, free:true};
  9546. if (!pass.gold) { args.id = pass.id }
  9547. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_free_${args.id}_${i}` });
  9548. }
  9549. if (pass.ticket && !pass.rewards[i]?.paid && isFarmReward(reward.paid)) {
  9550. const args = {level: i, free:false};
  9551. if (!pass.gold) { args.id = pass.id}
  9552. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_paid_${args.id}_${i}` });
  9553. }
  9554. }
  9555. return calls;
  9556. }
  9557.  
  9558. const passes = await Send({
  9559. calls: [
  9560. { name: 'battlePass_getInfo', args: {}, ident: 'getInfo' },
  9561. { name: 'battlePass_getSpecial', args: {}, ident: 'getSpecial' },
  9562. ],
  9563. }).then((e) => [{...e.results[0].result.response?.battlePass, gold: true}, ...Object.values(e.results[1].result.response)]);
  9564.  
  9565. const calls = passes.map(p => battlePassProcess(p)).flat()
  9566.  
  9567. if (!calls.length) {
  9568. setProgress(I18N('NOTHING_TO_COLLECT'));
  9569. return;
  9570. }
  9571.  
  9572. let results = await Send({calls});
  9573. if (results.error) {
  9574. console.log(results.error);
  9575. setProgress(I18N('SOMETHING_WENT_WRONG'));
  9576. } else {
  9577. setProgress(I18N('SEASON_REWARD_COLLECTED', {count: results.results.length}), true);
  9578. }
  9579. }
  9580.  
  9581. async function sellHeroSoulsForGold() {
  9582. let { fragmentHero, heroes } = await Send({
  9583. calls: [
  9584. { name: 'inventoryGet', args: {}, ident: 'inventoryGet' },
  9585. { name: 'heroGetAll', args: {}, ident: 'heroGetAll' },
  9586. ],
  9587. })
  9588. .then((e) => e.results.map((r) => r.result.response))
  9589. .then((e) => ({ fragmentHero: e[0].fragmentHero, heroes: e[1] }));
  9590.  
  9591. const calls = [];
  9592. for (let i in fragmentHero) {
  9593. if (heroes[i] && heroes[i].star == 6) {
  9594. calls.push({
  9595. name: 'inventorySell',
  9596. args: {
  9597. type: 'hero',
  9598. libId: i,
  9599. amount: fragmentHero[i],
  9600. fragment: true,
  9601. },
  9602. ident: 'inventorySell_' + i,
  9603. });
  9604. }
  9605. }
  9606. if (!calls.length) {
  9607. console.log(0);
  9608. return 0;
  9609. }
  9610. const rewards = await Send({ calls }).then((e) => e.results.map((r) => r.result?.response?.gold || 0));
  9611. const gold = rewards.reduce((e, a) => e + a, 0);
  9612. setProgress(I18N('GOLD_RECEIVED', { gold }), true);
  9613. }
  9614.  
  9615. /**
  9616. * Attack of the minions of Asgard
  9617. *
  9618. * Атака прислужников Асгарда
  9619. */
  9620. function testRaidNodes() {
  9621. const { executeRaidNodes } = HWHClasses;
  9622. return new Promise((resolve, reject) => {
  9623. const tower = new executeRaidNodes(resolve, reject);
  9624. tower.start();
  9625. });
  9626. }
  9627.  
  9628. /**
  9629. * Attack of the minions of Asgard
  9630. *
  9631. * Атака прислужников Асгарда
  9632. */
  9633. function executeRaidNodes(resolve, reject) {
  9634. let raidData = {
  9635. teams: [],
  9636. favor: {},
  9637. nodes: [],
  9638. attempts: 0,
  9639. countExecuteBattles: 0,
  9640. cancelBattle: 0,
  9641. }
  9642.  
  9643. callsExecuteRaidNodes = {
  9644. calls: [{
  9645. name: "clanRaid_getInfo",
  9646. args: {},
  9647. ident: "clanRaid_getInfo"
  9648. }, {
  9649. name: "teamGetAll",
  9650. args: {},
  9651. ident: "teamGetAll"
  9652. }, {
  9653. name: "teamGetFavor",
  9654. args: {},
  9655. ident: "teamGetFavor"
  9656. }]
  9657. }
  9658.  
  9659. this.start = function () {
  9660. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  9661. }
  9662.  
  9663. async function startRaidNodes(data) {
  9664. res = data.results;
  9665. clanRaidInfo = res[0].result.response;
  9666. teamGetAll = res[1].result.response;
  9667. teamGetFavor = res[2].result.response;
  9668.  
  9669. let index = 0;
  9670. let isNotFullPack = false;
  9671. for (let team of teamGetAll.clanRaid_nodes) {
  9672. if (team.length < 6) {
  9673. isNotFullPack = true;
  9674. }
  9675. raidData.teams.push({
  9676. data: {},
  9677. heroes: team.filter(id => id < 6000),
  9678. pet: team.filter(id => id >= 6000).pop(),
  9679. battleIndex: index++
  9680. });
  9681. }
  9682. raidData.favor = teamGetFavor.clanRaid_nodes;
  9683.  
  9684. if (isNotFullPack) {
  9685. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  9686. { msg: I18N('BTN_NO'), result: true },
  9687. { msg: I18N('BTN_YES'), result: false },
  9688. ])) {
  9689. endRaidNodes('isNotFullPack');
  9690. return;
  9691. }
  9692. }
  9693.  
  9694. raidData.nodes = clanRaidInfo.nodes;
  9695. raidData.attempts = clanRaidInfo.attempts;
  9696. setIsCancalBattle(false);
  9697.  
  9698. checkNodes();
  9699. }
  9700.  
  9701. function getAttackNode() {
  9702. for (let nodeId in raidData.nodes) {
  9703. let node = raidData.nodes[nodeId];
  9704. let points = 0
  9705. for (team of node.teams) {
  9706. points += team.points;
  9707. }
  9708. let now = Date.now() / 1000;
  9709. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  9710. let countTeam = node.teams.length;
  9711. delete raidData.nodes[nodeId];
  9712. return {
  9713. nodeId,
  9714. countTeam
  9715. };
  9716. }
  9717. }
  9718. return null;
  9719. }
  9720.  
  9721. function checkNodes() {
  9722. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  9723. let nodeInfo = getAttackNode();
  9724. if (nodeInfo && raidData.attempts) {
  9725. startNodeBattles(nodeInfo);
  9726. return;
  9727. }
  9728.  
  9729. endRaidNodes('EndRaidNodes');
  9730. }
  9731.  
  9732. function startNodeBattles(nodeInfo) {
  9733. let {nodeId, countTeam} = nodeInfo;
  9734. let teams = raidData.teams.slice(0, countTeam);
  9735. let heroes = raidData.teams.map(e => e.heroes).flat();
  9736. let favor = {...raidData.favor};
  9737. for (let heroId in favor) {
  9738. if (!heroes.includes(+heroId)) {
  9739. delete favor[heroId];
  9740. }
  9741. }
  9742.  
  9743. let calls = [{
  9744. name: "clanRaid_startNodeBattles",
  9745. args: {
  9746. nodeId,
  9747. teams,
  9748. favor
  9749. },
  9750. ident: "body"
  9751. }];
  9752.  
  9753. send(JSON.stringify({calls}), resultNodeBattles);
  9754. }
  9755.  
  9756. function resultNodeBattles(e) {
  9757. if (e['error']) {
  9758. endRaidNodes('nodeBattlesError', e['error']);
  9759. return;
  9760. }
  9761.  
  9762. console.log(e);
  9763. let battles = e.results[0].result.response.battles;
  9764. let promises = [];
  9765. let battleIndex = 0;
  9766. for (let battle of battles) {
  9767. battle.battleIndex = battleIndex++;
  9768. promises.push(calcBattleResult(battle));
  9769. }
  9770.  
  9771. Promise.all(promises)
  9772. .then(results => {
  9773. const endResults = {};
  9774. let isAllWin = true;
  9775. for (let r of results) {
  9776. isAllWin &&= r.result.win;
  9777. }
  9778. if (!isAllWin) {
  9779. cancelEndNodeBattle(results[0]);
  9780. return;
  9781. }
  9782. raidData.countExecuteBattles = results.length;
  9783. let timeout = 500;
  9784. for (let r of results) {
  9785. setTimeout(endNodeBattle, timeout, r);
  9786. timeout += 500;
  9787. }
  9788. });
  9789. }
  9790. /**
  9791. * Returns the battle calculation promise
  9792. *
  9793. * Возвращает промис расчета боя
  9794. */
  9795. function calcBattleResult(battleData) {
  9796. return new Promise(function (resolve, reject) {
  9797. BattleCalc(battleData, "get_clanPvp", resolve);
  9798. });
  9799. }
  9800. /**
  9801. * Cancels the fight
  9802. *
  9803. * Отменяет бой
  9804. */
  9805. function cancelEndNodeBattle(r) {
  9806. const fixBattle = function (heroes) {
  9807. for (const ids in heroes) {
  9808. hero = heroes[ids];
  9809. hero.energy = random(1, 999);
  9810. if (hero.hp > 0) {
  9811. hero.hp = random(1, hero.hp);
  9812. }
  9813. }
  9814. }
  9815. fixBattle(r.progress[0].attackers.heroes);
  9816. fixBattle(r.progress[0].defenders.heroes);
  9817. endNodeBattle(r);
  9818. }
  9819. /**
  9820. * Ends the fight
  9821. *
  9822. * Завершает бой
  9823. */
  9824. function endNodeBattle(r) {
  9825. let nodeId = r.battleData.result.nodeId;
  9826. let battleIndex = r.battleData.battleIndex;
  9827. let calls = [{
  9828. name: "clanRaid_endNodeBattle",
  9829. args: {
  9830. nodeId,
  9831. battleIndex,
  9832. result: r.result,
  9833. progress: r.progress
  9834. },
  9835. ident: "body"
  9836. }]
  9837.  
  9838. SendRequest(JSON.stringify({calls}), battleResult);
  9839. }
  9840. /**
  9841. * Processing the results of the battle
  9842. *
  9843. * Обработка результатов боя
  9844. */
  9845. function battleResult(e) {
  9846. if (e['error']) {
  9847. endRaidNodes('missionEndError', e['error']);
  9848. return;
  9849. }
  9850. r = e.results[0].result.response;
  9851. if (r['error']) {
  9852. if (r.reason == "invalidBattle") {
  9853. raidData.cancelBattle++;
  9854. checkNodes();
  9855. } else {
  9856. endRaidNodes('missionEndError', e['error']);
  9857. }
  9858. return;
  9859. }
  9860.  
  9861. if (!(--raidData.countExecuteBattles)) {
  9862. raidData.attempts--;
  9863. checkNodes();
  9864. }
  9865. }
  9866. /**
  9867. * Completing a task
  9868. *
  9869. * Завершение задачи
  9870. */
  9871. function endRaidNodes(reason, info) {
  9872. setIsCancalBattle(true);
  9873. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  9874. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  9875. console.log(reason, info);
  9876. resolve();
  9877. }
  9878. }
  9879.  
  9880. this.HWHClasses.executeRaidNodes = executeRaidNodes;
  9881.  
  9882. /**
  9883. * Asgard Boss Attack Replay
  9884. *
  9885. * Повтор атаки босса Асгарда
  9886. */
  9887. function testBossBattle() {
  9888. const { executeBossBattle } = HWHClasses;
  9889. return new Promise((resolve, reject) => {
  9890. const bossBattle = new executeBossBattle(resolve, reject);
  9891. bossBattle.start(lastBossBattle);
  9892. });
  9893. }
  9894.  
  9895. /**
  9896. * Asgard Boss Attack Replay
  9897. *
  9898. * Повтор атаки босса Асгарда
  9899. */
  9900. function executeBossBattle(resolve, reject) {
  9901.  
  9902. this.start = function (battleInfo) {
  9903. preCalcBattle(battleInfo);
  9904. }
  9905.  
  9906. function getBattleInfo(battle) {
  9907. return new Promise(function (resolve) {
  9908. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9909. BattleCalc(battle, getBattleType(battle.type), e => {
  9910. let extra = e.progress[0].defenders.heroes[1].extra;
  9911. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  9912. });
  9913. });
  9914. }
  9915.  
  9916. function preCalcBattle(battle) {
  9917. let actions = [];
  9918. const countTestBattle = getInput('countTestBattle');
  9919. for (let i = 0; i < countTestBattle; i++) {
  9920. actions.push(getBattleInfo(battle, true));
  9921. }
  9922. Promise.all(actions)
  9923. .then(resultPreCalcBattle);
  9924. }
  9925.  
  9926. async function resultPreCalcBattle(damages) {
  9927. let maxDamage = 0;
  9928. let minDamage = 1e10;
  9929. let avgDamage = 0;
  9930. for (let damage of damages) {
  9931. avgDamage += damage
  9932. if (damage > maxDamage) {
  9933. maxDamage = damage;
  9934. }
  9935. if (damage < minDamage) {
  9936. minDamage = damage;
  9937. }
  9938. }
  9939. avgDamage /= damages.length;
  9940. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  9941.  
  9942. await popup.confirm(
  9943. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  9944. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  9945. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  9946. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  9947. , [
  9948. { msg: I18N('BTN_OK'), result: 0},
  9949. ])
  9950. endBossBattle(I18N('BTN_CANCEL'));
  9951. }
  9952.  
  9953. /**
  9954. * Completing a task
  9955. *
  9956. * Завершение задачи
  9957. */
  9958. function endBossBattle(reason, info) {
  9959. console.log(reason, info);
  9960. resolve();
  9961. }
  9962. }
  9963.  
  9964. this.HWHClasses.executeBossBattle = executeBossBattle;
  9965.  
  9966. class FixBattle {
  9967. minTimer = 1.3;
  9968. maxTimer = 15.3;
  9969.  
  9970. constructor(battle, isTimeout = true) {
  9971. this.battle = structuredClone(battle);
  9972. this.isTimeout = isTimeout;
  9973. }
  9974.  
  9975. timeout(callback, timeout) {
  9976. if (this.isTimeout) {
  9977. this.worker.postMessage(timeout);
  9978. this.worker.onmessage = callback;
  9979. } else {
  9980. callback();
  9981. }
  9982. }
  9983.  
  9984. randTimer() {
  9985. return Math.random() * (this.maxTimer - this.minTimer + 1) + this.minTimer;
  9986. }
  9987.  
  9988. setAvgTime(startTime) {
  9989. this.fixTime += Date.now() - startTime;
  9990. this.avgTime = this.fixTime / this.count;
  9991. }
  9992.  
  9993. init() {
  9994. this.fixTime = 0;
  9995. this.lastTimer = 0;
  9996. this.index = 0;
  9997. this.lastBossDamage = 0;
  9998. this.bestResult = {
  9999. count: 0,
  10000. timer: 0,
  10001. value: 0,
  10002. result: null,
  10003. progress: null,
  10004. };
  10005. this.lastBattleResult = {
  10006. win: false,
  10007. };
  10008. this.worker = new Worker(
  10009. URL.createObjectURL(
  10010. new Blob([
  10011. `self.onmessage = function(e) {
  10012. const timeout = e.data;
  10013. setTimeout(() => {
  10014. self.postMessage(1);
  10015. }, timeout);
  10016. };`,
  10017. ])
  10018. )
  10019. );
  10020. }
  10021.  
  10022. async start(endTime = Date.now() + 6e4, maxCount = 100) {
  10023. this.endTime = endTime;
  10024. this.maxCount = maxCount;
  10025. this.init();
  10026. return await new Promise((resolve) => {
  10027. this.resolve = resolve;
  10028. this.count = 0;
  10029. this.loop();
  10030. });
  10031. }
  10032.  
  10033. endFix() {
  10034. this.bestResult.maxCount = this.count;
  10035. this.worker.terminate();
  10036. this.resolve(this.bestResult);
  10037. }
  10038.  
  10039. async loop() {
  10040. const start = Date.now();
  10041. if (this.isEndLoop()) {
  10042. this.endFix();
  10043. return;
  10044. }
  10045. this.count++;
  10046. try {
  10047. this.lastResult = await Calc(this.battle);
  10048. } catch (e) {
  10049. this.updateProgressTimer(this.index++);
  10050. this.timeout(this.loop.bind(this), 0);
  10051. return;
  10052. }
  10053. const { progress, result } = this.lastResult;
  10054. this.lastBattleResult = result;
  10055. this.lastBattleProgress = progress;
  10056. this.setAvgTime(start);
  10057. this.checkResult();
  10058. this.showResult();
  10059. this.updateProgressTimer();
  10060. this.timeout(this.loop.bind(this), 0);
  10061. }
  10062.  
  10063. isEndLoop() {
  10064. return this.count >= this.maxCount || this.endTime < Date.now();
  10065. }
  10066.  
  10067. updateProgressTimer(index = 0) {
  10068. this.lastTimer = this.randTimer();
  10069. this.battle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', index, this.lastTimer] } }];
  10070. }
  10071.  
  10072. showResult() {
  10073. console.log(
  10074. this.count,
  10075. this.avgTime.toFixed(2),
  10076. (this.endTime - Date.now()) / 1000,
  10077. this.lastTimer.toFixed(2),
  10078. this.lastBossDamage.toLocaleString(),
  10079. this.bestResult.value.toLocaleString()
  10080. );
  10081. }
  10082.  
  10083. checkResult() {
  10084. const { damageTaken, damageTakenNextLevel } = this.lastBattleProgress[0].defenders.heroes[1].extra;
  10085. this.lastBossDamage = damageTaken + damageTakenNextLevel;
  10086. if (this.lastBossDamage > this.bestResult.value) {
  10087. this.bestResult = {
  10088. count: this.count,
  10089. timer: this.lastTimer,
  10090. value: this.lastBossDamage,
  10091. result: structuredClone(this.lastBattleResult),
  10092. progress: structuredClone(this.lastBattleProgress),
  10093. };
  10094. }
  10095. }
  10096.  
  10097. stopFix() {
  10098. this.endTime = 0;
  10099. }
  10100. }
  10101.  
  10102. this.HWHClasses.FixBattle = FixBattle;
  10103.  
  10104. class WinFixBattle extends FixBattle {
  10105. checkResult() {
  10106. if (this.lastBattleResult.win) {
  10107. this.bestResult = {
  10108. count: this.count,
  10109. timer: this.lastTimer,
  10110. value: this.lastBattleResult.stars,
  10111. result: structuredClone(this.lastBattleResult),
  10112. progress: structuredClone(this.lastBattleProgress),
  10113. battleTimer: this.lastResult.battleTimer,
  10114. };
  10115. }
  10116. }
  10117.  
  10118. setWinTimer(value) {
  10119. this.winTimer = value;
  10120. }
  10121.  
  10122. setMaxTimer(value) {
  10123. this.maxTimer = value;
  10124. }
  10125.  
  10126. randTimer() {
  10127. if (this.winTimer) {
  10128. return this.winTimer;
  10129. }
  10130. return super.randTimer();
  10131. }
  10132.  
  10133. isEndLoop() {
  10134. return super.isEndLoop() || this.bestResult.result?.win;
  10135. }
  10136.  
  10137. showResult() {
  10138. console.log(
  10139. this.count,
  10140. this.avgTime.toFixed(2),
  10141. (this.endTime - Date.now()) / 1000,
  10142. this.lastResult.battleTime,
  10143. this.lastTimer,
  10144. this.bestResult.value
  10145. );
  10146. const endTime = ((this.endTime - Date.now()) / 1000).toFixed(2);
  10147. const avgTime = this.avgTime.toFixed(2);
  10148. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${endTime}s<br/>${avgTime}ms`;
  10149. setProgress(msg, false, this.stopFix.bind(this));
  10150. }
  10151. }
  10152.  
  10153. this.HWHClasses.WinFixBattle = WinFixBattle;
  10154.  
  10155. class BestOrWinFixBattle extends WinFixBattle {
  10156. isNoMakeWin = false;
  10157.  
  10158. getState(result) {
  10159. let beforeSumFactor = 0;
  10160. const beforeHeroes = result.battleData.defenders[0];
  10161. for (let heroId in beforeHeroes) {
  10162. const hero = beforeHeroes[heroId];
  10163. const state = hero.state;
  10164. let factor = 1;
  10165. if (state) {
  10166. const hp = state.hp / (hero?.hp || 1);
  10167. const energy = state.energy / 1e3;
  10168. factor = hp + energy / 20;
  10169. }
  10170. beforeSumFactor += factor;
  10171. }
  10172.  
  10173. let afterSumFactor = 0;
  10174. const afterHeroes = result.progress[0].defenders.heroes;
  10175. for (let heroId in afterHeroes) {
  10176. const hero = afterHeroes[heroId];
  10177. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10178. const energy = hero.energy / 1e3;
  10179. const factor = hp + energy / 20;
  10180. afterSumFactor += factor;
  10181. }
  10182. return 100 - Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10183. }
  10184.  
  10185. setNoMakeWin(value) {
  10186. this.isNoMakeWin = value;
  10187. }
  10188.  
  10189. checkResult() {
  10190. const state = this.getState(this.lastResult);
  10191. console.log(state);
  10192.  
  10193. if (state > this.bestResult.value) {
  10194. if (!(this.isNoMakeWin && this.lastBattleResult.win)) {
  10195. this.bestResult = {
  10196. count: this.count,
  10197. timer: this.lastTimer,
  10198. value: state,
  10199. result: structuredClone(this.lastBattleResult),
  10200. progress: structuredClone(this.lastBattleProgress),
  10201. battleTimer: this.lastResult.battleTimer,
  10202. };
  10203. }
  10204. }
  10205. }
  10206. }
  10207.  
  10208. this.HWHClasses.BestOrWinFixBattle = BestOrWinFixBattle;
  10209.  
  10210. class BossFixBattle extends FixBattle {
  10211. showResult() {
  10212. super.showResult();
  10213. //setTimeout(() => {
  10214. const best = this.bestResult;
  10215. const maxDmg = best.value.toLocaleString();
  10216. const avgTime = this.avgTime.toLocaleString();
  10217. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${maxDmg}<br/>${avgTime}ms`;
  10218. setProgress(msg, false, this.stopFix.bind(this));
  10219. //}, 0);
  10220. }
  10221. }
  10222.  
  10223. this.HWHClasses.BossFixBattle = BossFixBattle;
  10224.  
  10225. class DungeonFixBattle extends FixBattle {
  10226. init() {
  10227. super.init();
  10228. this.isTimeout = false;
  10229. }
  10230.  
  10231. setState() {
  10232. const result = this.lastResult;
  10233. let beforeSumFactor = 0;
  10234. const beforeHeroes = result.battleData.attackers;
  10235. for (let heroId in beforeHeroes) {
  10236. const hero = beforeHeroes[heroId];
  10237. const state = hero.state;
  10238. let factor = 1;
  10239. if (state) {
  10240. const hp = state.hp / (hero?.hp || 1);
  10241. const energy = state.energy / 1e3;
  10242. factor = hp + energy / 20;
  10243. }
  10244. beforeSumFactor += factor;
  10245. }
  10246.  
  10247. let afterSumFactor = 0;
  10248. const afterHeroes = result.progress[0].attackers.heroes;
  10249. for (let heroId in afterHeroes) {
  10250. const hero = afterHeroes[heroId];
  10251. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10252. const energy = hero.energy / 1e3;
  10253. const factor = hp + energy / 20;
  10254. afterSumFactor += factor;
  10255. }
  10256. this.lastState = Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10257. }
  10258.  
  10259. checkResult() {
  10260. this.setState();
  10261. if (this.lastResult.result.win && this.lastState > this.bestResult.value) {
  10262. this.bestResult = {
  10263. count: this.count,
  10264. timer: this.lastTimer,
  10265. value: this.lastState,
  10266. result: this.lastResult.result,
  10267. progress: this.lastResult.progress,
  10268. };
  10269. }
  10270. }
  10271.  
  10272. showResult() {
  10273. console.log(
  10274. this.count,
  10275. this.avgTime.toFixed(2),
  10276. (this.endTime - Date.now()) / 1000,
  10277. this.lastTimer.toFixed(2),
  10278. this.lastState.toLocaleString(),
  10279. this.bestResult.value.toLocaleString()
  10280. );
  10281. }
  10282. }
  10283.  
  10284. this.HWHClasses.DungeonFixBattle = DungeonFixBattle;
  10285.  
  10286. const masterWsMixin = {
  10287. wsStart() {
  10288. const socket = new WebSocket(this.url);
  10289.  
  10290. socket.onopen = () => {
  10291. console.log('Connected to server');
  10292.  
  10293. // Пример создания новой задачи
  10294. const newTask = {
  10295. type: 'newTask',
  10296. battle: this.battle,
  10297. endTime: this.endTime - 1e4,
  10298. maxCount: this.maxCount,
  10299. };
  10300. socket.send(JSON.stringify(newTask));
  10301. };
  10302.  
  10303. socket.onmessage = this.onmessage.bind(this);
  10304.  
  10305. socket.onclose = () => {
  10306. console.log('Disconnected from server');
  10307. };
  10308.  
  10309. this.ws = socket;
  10310. },
  10311.  
  10312. onmessage(event) {
  10313. const data = JSON.parse(event.data);
  10314. switch (data.type) {
  10315. case 'newTask': {
  10316. console.log('newTask:', data);
  10317. this.id = data.id;
  10318. this.countExecutor = data.count;
  10319. break;
  10320. }
  10321. case 'getSolTask': {
  10322. console.log('getSolTask:', data);
  10323. this.endFix(data.solutions);
  10324. break;
  10325. }
  10326. case 'resolveTask': {
  10327. console.log('resolveTask:', data);
  10328. if (data.id === this.id && data.solutions.length === this.countExecutor) {
  10329. this.worker.terminate();
  10330. this.endFix(data.solutions);
  10331. }
  10332. break;
  10333. }
  10334. default:
  10335. console.log('Unknown message type:', data.type);
  10336. }
  10337. },
  10338.  
  10339. getTask() {
  10340. this.ws.send(
  10341. JSON.stringify({
  10342. type: 'getSolTask',
  10343. id: this.id,
  10344. })
  10345. );
  10346. },
  10347. };
  10348.  
  10349. /*
  10350. mFix = new action.masterFixBattle(battle)
  10351. await mFix.start(Date.now() + 6e4, 1);
  10352. */
  10353. class masterFixBattle extends FixBattle {
  10354. constructor(battle, url = 'wss://localho.st:3000') {
  10355. super(battle, true);
  10356. this.url = url;
  10357. }
  10358.  
  10359. async start(endTime, maxCount) {
  10360. this.endTime = endTime;
  10361. this.maxCount = maxCount;
  10362. this.init();
  10363. this.wsStart();
  10364. return await new Promise((resolve) => {
  10365. this.resolve = resolve;
  10366. const timeout = this.endTime - Date.now();
  10367. this.timeout(this.getTask.bind(this), timeout);
  10368. });
  10369. }
  10370.  
  10371. async endFix(solutions) {
  10372. this.ws.close();
  10373. let maxCount = 0;
  10374. for (const solution of solutions) {
  10375. maxCount += solution.maxCount;
  10376. if (solution.value > this.bestResult.value) {
  10377. this.bestResult = solution;
  10378. }
  10379. }
  10380. this.count = maxCount;
  10381. super.endFix();
  10382. }
  10383. }
  10384.  
  10385. Object.assign(masterFixBattle.prototype, masterWsMixin);
  10386.  
  10387. this.HWHClasses.masterFixBattle = masterFixBattle;
  10388.  
  10389. class masterWinFixBattle extends WinFixBattle {
  10390. constructor(battle, url = 'wss://localho.st:3000') {
  10391. super(battle, true);
  10392. this.url = url;
  10393. }
  10394.  
  10395. async start(endTime, maxCount) {
  10396. this.endTime = endTime;
  10397. this.maxCount = maxCount;
  10398. this.init();
  10399. this.wsStart();
  10400. return await new Promise((resolve) => {
  10401. this.resolve = resolve;
  10402. const timeout = this.endTime - Date.now();
  10403. this.timeout(this.getTask.bind(this), timeout);
  10404. });
  10405. }
  10406.  
  10407. async endFix(solutions) {
  10408. this.ws.close();
  10409. let maxCount = 0;
  10410. for (const solution of solutions) {
  10411. maxCount += solution.maxCount;
  10412. if (solution.value > this.bestResult.value) {
  10413. this.bestResult = solution;
  10414. }
  10415. }
  10416. this.count = maxCount;
  10417. super.endFix();
  10418. }
  10419. }
  10420.  
  10421. Object.assign(masterWinFixBattle.prototype, masterWsMixin);
  10422.  
  10423. this.HWHClasses.masterWinFixBattle = masterWinFixBattle;
  10424.  
  10425. const slaveWsMixin = {
  10426. wsStop() {
  10427. this.ws.close();
  10428. },
  10429.  
  10430. wsStart() {
  10431. const socket = new WebSocket(this.url);
  10432.  
  10433. socket.onopen = () => {
  10434. console.log('Connected to server');
  10435. };
  10436. socket.onmessage = this.onmessage.bind(this);
  10437. socket.onclose = () => {
  10438. console.log('Disconnected from server');
  10439. };
  10440.  
  10441. this.ws = socket;
  10442. },
  10443.  
  10444. async onmessage(event) {
  10445. const data = JSON.parse(event.data);
  10446. switch (data.type) {
  10447. case 'newTask': {
  10448. console.log('newTask:', data.task);
  10449. const { battle, endTime, maxCount } = data.task;
  10450. this.battle = battle;
  10451. const id = data.task.id;
  10452. const solution = await this.start(endTime, maxCount);
  10453. this.ws.send(
  10454. JSON.stringify({
  10455. type: 'resolveTask',
  10456. id,
  10457. solution,
  10458. })
  10459. );
  10460. break;
  10461. }
  10462. default:
  10463. console.log('Unknown message type:', data.type);
  10464. }
  10465. },
  10466. };
  10467. /*
  10468. sFix = new action.slaveFixBattle();
  10469. sFix.wsStart()
  10470. */
  10471. class slaveFixBattle extends FixBattle {
  10472. constructor(url = 'wss://localho.st:3000') {
  10473. super(null, false);
  10474. this.isTimeout = false;
  10475. this.url = url;
  10476. }
  10477. }
  10478.  
  10479. Object.assign(slaveFixBattle.prototype, slaveWsMixin);
  10480.  
  10481. this.HWHClasses.slaveFixBattle = slaveFixBattle;
  10482.  
  10483. class slaveWinFixBattle extends WinFixBattle {
  10484. constructor(url = 'wss://localho.st:3000') {
  10485. super(null, false);
  10486. this.isTimeout = false;
  10487. this.url = url;
  10488. }
  10489. }
  10490.  
  10491. Object.assign(slaveWinFixBattle.prototype, slaveWsMixin);
  10492.  
  10493. this.HWHClasses.slaveWinFixBattle = slaveWinFixBattle;
  10494. /**
  10495. * Auto-repeat attack
  10496. *
  10497. * Автоповтор атаки
  10498. */
  10499. function testAutoBattle() {
  10500. const { executeAutoBattle } = HWHClasses;
  10501. return new Promise((resolve, reject) => {
  10502. const bossBattle = new executeAutoBattle(resolve, reject);
  10503. bossBattle.start(lastBattleArg, lastBattleInfo);
  10504. });
  10505. }
  10506.  
  10507. /**
  10508. * Auto-repeat attack
  10509. *
  10510. * Автоповтор атаки
  10511. */
  10512. function executeAutoBattle(resolve, reject) {
  10513. let battleArg = {};
  10514. let countBattle = 0;
  10515. let countError = 0;
  10516. let findCoeff = 0;
  10517. let dataNotEeceived = 0;
  10518. let stopAutoBattle = false;
  10519.  
  10520. let isSetWinTimer = false;
  10521. 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>';
  10522. 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>';
  10523. 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>';
  10524.  
  10525. this.start = function (battleArgs, battleInfo) {
  10526. battleArg = battleArgs;
  10527. if (nameFuncStartBattle == 'invasion_bossStart') {
  10528. startBattle();
  10529. return;
  10530. }
  10531. preCalcBattle(battleInfo);
  10532. }
  10533. /**
  10534. * Returns a promise for combat recalculation
  10535. *
  10536. * Возвращает промис для прерасчета боя
  10537. */
  10538. function getBattleInfo(battle) {
  10539. return new Promise(function (resolve) {
  10540. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10541. Calc(battle).then(e => {
  10542. e.coeff = calcCoeff(e, 'defenders');
  10543. resolve(e);
  10544. });
  10545. });
  10546. }
  10547. /**
  10548. * Battle recalculation
  10549. *
  10550. * Прерасчет боя
  10551. */
  10552. function preCalcBattle(battle) {
  10553. let actions = [];
  10554. const countTestBattle = getInput('countTestBattle');
  10555. for (let i = 0; i < countTestBattle; i++) {
  10556. actions.push(getBattleInfo(battle));
  10557. }
  10558. Promise.all(actions)
  10559. .then(resultPreCalcBattle);
  10560. }
  10561. /**
  10562. * Processing the results of the battle recalculation
  10563. *
  10564. * Обработка результатов прерасчета боя
  10565. */
  10566. async function resultPreCalcBattle(results) {
  10567. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  10568. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  10569. if (countWin > 0) {
  10570. setIsCancalBattle(false);
  10571. startBattle();
  10572. return;
  10573. }
  10574.  
  10575. let minCoeff = 100;
  10576. let maxCoeff = -100;
  10577. let avgCoeff = 0;
  10578. results.forEach(e => {
  10579. if (e.coeff < minCoeff) minCoeff = e.coeff;
  10580. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  10581. avgCoeff += e.coeff;
  10582. });
  10583. avgCoeff /= results.length;
  10584.  
  10585. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10586. nameFuncStartBattle == 'bossAttack') {
  10587. const result = await popup.confirm(
  10588. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  10589. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  10590. { msg: I18N('BTN_DO_IT'), result: true },
  10591. ])
  10592. if (result) {
  10593. setIsCancalBattle(false);
  10594. startBattle();
  10595. return;
  10596. }
  10597. setProgress(I18N('NOT_THIS_TIME'), true);
  10598. endAutoBattle('invasion_bossStart');
  10599. return;
  10600. }
  10601.  
  10602. const result = await popup.confirm(
  10603. I18N('VICTORY_IMPOSSIBLE') +
  10604. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  10605. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  10606. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  10607. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  10608. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  10609. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  10610. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  10611. ])
  10612. if (result) {
  10613. findCoeff = result;
  10614. setIsCancalBattle(false);
  10615. startBattle();
  10616. return;
  10617. }
  10618. setProgress(I18N('NOT_THIS_TIME'), true);
  10619. endAutoBattle(I18N('NOT_THIS_TIME'));
  10620. }
  10621.  
  10622. /**
  10623. * Calculation of the combat result coefficient
  10624. *
  10625. * Расчет коэфициента результата боя
  10626. */
  10627. function calcCoeff(result, packType) {
  10628. let beforeSumFactor = 0;
  10629. const beforePack = result.battleData[packType][0];
  10630. for (let heroId in beforePack) {
  10631. const hero = beforePack[heroId];
  10632. const state = hero.state;
  10633. let factor = 1;
  10634. if (state) {
  10635. const hp = state.hp / state.maxHp;
  10636. const energy = state.energy / 1e3;
  10637. factor = hp + energy / 20;
  10638. }
  10639. beforeSumFactor += factor;
  10640. }
  10641.  
  10642. let afterSumFactor = 0;
  10643. const afterPack = result.progress[0][packType].heroes;
  10644. for (let heroId in afterPack) {
  10645. const hero = afterPack[heroId];
  10646. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  10647. const hp = hero.hp / stateHp;
  10648. const energy = hero.energy / 1e3;
  10649. const factor = hp + energy / 20;
  10650. afterSumFactor += factor;
  10651. }
  10652. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  10653. return Math.round(resultCoeff * 1000) / 1000;
  10654. }
  10655. /**
  10656. * Start battle
  10657. *
  10658. * Начало боя
  10659. */
  10660. function startBattle() {
  10661. countBattle++;
  10662. const countMaxBattle = getInput('countAutoBattle');
  10663. // setProgress(countBattle + '/' + countMaxBattle);
  10664. if (countBattle > countMaxBattle) {
  10665. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  10666. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  10667. return;
  10668. }
  10669. if (stopAutoBattle) {
  10670. setProgress(I18N('STOPPED'), true);
  10671. endAutoBattle('STOPPED');
  10672. return;
  10673. }
  10674. send({calls: [{
  10675. name: nameFuncStartBattle,
  10676. args: battleArg,
  10677. ident: "body"
  10678. }]}, calcResultBattle);
  10679. }
  10680. /**
  10681. * Battle calculation
  10682. *
  10683. * Расчет боя
  10684. */
  10685. async function calcResultBattle(e) {
  10686. if (!e) {
  10687. console.log('данные не были получены');
  10688. if (dataNotEeceived < 10) {
  10689. dataNotEeceived++;
  10690. startBattle();
  10691. return;
  10692. }
  10693. endAutoBattle('Error', 'данные не были получены ' + dataNotEeceived + ' раз');
  10694. return;
  10695. }
  10696. if ('error' in e) {
  10697. if (e.error.description === 'too many tries') {
  10698. invasionTimer += 100;
  10699. countBattle--;
  10700. countError++;
  10701. console.log(`Errors: ${countError}`, e.error);
  10702. startBattle();
  10703. return;
  10704. }
  10705. const result = await popup.confirm(I18N('ERROR_DURING_THE_BATTLE') + '<br>' + e.error.description, [
  10706. { msg: I18N('BTN_OK'), result: false },
  10707. { msg: I18N('RELOAD_GAME'), result: true },
  10708. ]);
  10709. endAutoBattle('Error', e.error);
  10710. if (result) {
  10711. location.reload();
  10712. }
  10713. return;
  10714. }
  10715. let battle = e.results[0].result.response.battle
  10716. if (nameFuncStartBattle == 'towerStartBattle' ||
  10717. nameFuncStartBattle == 'bossAttack' ||
  10718. nameFuncStartBattle == 'invasion_bossStart') {
  10719. battle = e.results[0].result.response;
  10720. }
  10721. lastBattleInfo = battle;
  10722. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  10723. }
  10724. /**
  10725. * Processing the results of the battle
  10726. *
  10727. * Обработка результатов боя
  10728. */
  10729. async function resultBattle(e) {
  10730. const isWin = e.result.win;
  10731. if (isWin) {
  10732. endBattle(e, false);
  10733. return;
  10734. } else if (isChecked('tryFixIt_v2')) {
  10735. const { WinFixBattle } = HWHClasses;
  10736. const cloneBattle = structuredClone(e.battleData);
  10737. const bFix = new WinFixBattle(cloneBattle);
  10738. let attempts = Infinity;
  10739. if (nameFuncStartBattle == 'invasion_bossStart' && !isSetWinTimer) {
  10740. let winTimer = await popup.confirm(`Secret number:`, [
  10741. { result: false, isClose: true },
  10742. { msg: 'Go', isInput: true, default: '0' },
  10743. ]);
  10744. winTimer = Number.parseFloat(winTimer);
  10745. if (winTimer) {
  10746. attempts = 5;
  10747. bFix.setWinTimer(winTimer);
  10748. }
  10749. isSetWinTimer = true;
  10750. }
  10751. let endTime = Date.now() + 6e4;
  10752. if (nameFuncStartBattle == 'invasion_bossStart') {
  10753. endTime = Date.now() + 6e4 * 4;
  10754. bFix.setMaxTimer(120.3);
  10755. }
  10756. const result = await bFix.start(endTime, attempts);
  10757. console.log(result);
  10758. if (result.value) {
  10759. endBattle(result, false);
  10760. return;
  10761. }
  10762. }
  10763. const countMaxBattle = getInput('countAutoBattle');
  10764. if (findCoeff) {
  10765. const coeff = calcCoeff(e, 'defenders');
  10766. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  10767. if (coeff > findCoeff) {
  10768. endBattle(e, false);
  10769. return;
  10770. }
  10771. } else {
  10772. if (nameFuncStartBattle == 'invasion_bossStart') {
  10773. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10774. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10775. setProgress(`${svgBoss} ${bossLvl} ${svgJustice} ${justice} <br>${svgAttempt} ${countBattle}/${countMaxBattle}`, false, () => {
  10776. stopAutoBattle = true;
  10777. });
  10778. await new Promise((resolve) => setTimeout(resolve, 5000));
  10779. } else {
  10780. setProgress(`${countBattle}/${countMaxBattle}`);
  10781. }
  10782. }
  10783. if (nameFuncStartBattle == 'towerStartBattle' ||
  10784. nameFuncStartBattle == 'bossAttack' ||
  10785. nameFuncStartBattle == 'invasion_bossStart') {
  10786. startBattle();
  10787. return;
  10788. }
  10789. cancelEndBattle(e);
  10790. }
  10791. /**
  10792. * Cancel fight
  10793. *
  10794. * Отмена боя
  10795. */
  10796. function cancelEndBattle(r) {
  10797. const fixBattle = function (heroes) {
  10798. for (const ids in heroes) {
  10799. hero = heroes[ids];
  10800. hero.energy = random(1, 999);
  10801. if (hero.hp > 0) {
  10802. hero.hp = random(1, hero.hp);
  10803. }
  10804. }
  10805. }
  10806. fixBattle(r.progress[0].attackers.heroes);
  10807. fixBattle(r.progress[0].defenders.heroes);
  10808. endBattle(r, true);
  10809. }
  10810. /**
  10811. * End of the fight
  10812. *
  10813. * Завершение боя */
  10814. function endBattle(battleResult, isCancal) {
  10815. let calls = [{
  10816. name: nameFuncEndBattle,
  10817. args: {
  10818. result: battleResult.result,
  10819. progress: battleResult.progress
  10820. },
  10821. ident: "body"
  10822. }];
  10823.  
  10824. if (nameFuncStartBattle == 'invasion_bossStart') {
  10825. calls[0].args.id = lastBattleArg.id;
  10826. }
  10827.  
  10828. send(JSON.stringify({
  10829. calls
  10830. }), async e => {
  10831. console.log(e);
  10832. if (isCancal) {
  10833. startBattle();
  10834. return;
  10835. }
  10836.  
  10837. setProgress(`${I18N('SUCCESS')}!`, 5000)
  10838. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10839. nameFuncStartBattle == 'bossAttack') {
  10840. const countMaxBattle = getInput('countAutoBattle');
  10841. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10842. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10843. let winTimer = '';
  10844. if (nameFuncStartBattle == 'invasion_bossStart') {
  10845. winTimer = '<br>Secret number: ' + battleResult.progress[0].attackers.input[5];
  10846. }
  10847. const result = await popup.confirm(
  10848. I18N('BOSS_HAS_BEEN_DEF_TEXT', {
  10849. bossLvl: `${svgBoss} ${bossLvl} ${svgJustice} ${justice}`,
  10850. countBattle: svgAttempt + ' ' + countBattle,
  10851. countMaxBattle,
  10852. winTimer,
  10853. }),
  10854. [
  10855. { msg: I18N('BTN_OK'), result: 0 },
  10856. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  10857. { msg: I18N('RELOAD_GAME'), result: 2 },
  10858. ]
  10859. );
  10860. if (result) {
  10861. if (result == 1) {
  10862. cheats.refreshGame();
  10863. }
  10864. if (result == 2) {
  10865. location.reload();
  10866. }
  10867. }
  10868.  
  10869. }
  10870. endAutoBattle(`${I18N('SUCCESS')}!`)
  10871. });
  10872. }
  10873. /**
  10874. * Completing a task
  10875. *
  10876. * Завершение задачи
  10877. */
  10878. function endAutoBattle(reason, info) {
  10879. setIsCancalBattle(true);
  10880. console.log(reason, info);
  10881. resolve();
  10882. }
  10883. }
  10884.  
  10885. this.HWHClasses.executeAutoBattle = executeAutoBattle;
  10886.  
  10887. function testDailyQuests() {
  10888. const { dailyQuests } = HWHClasses;
  10889. return new Promise((resolve, reject) => {
  10890. const quests = new dailyQuests(resolve, reject);
  10891. quests.init(questsInfo);
  10892. quests.start();
  10893. });
  10894. }
  10895.  
  10896. /**
  10897. * Automatic completion of daily quests
  10898. *
  10899. * Автоматическое выполнение ежедневных квестов
  10900. */
  10901. class dailyQuests {
  10902. /**
  10903. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  10904. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10905. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10906. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  10907. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10908. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10909. */
  10910. callsList = ['userGetInfo', 'heroGetAll', 'titanGetAll', 'inventoryGet', 'questGetAll', 'bossGetAll', 'missionGetAll'];
  10911.  
  10912. dataQuests = {
  10913. 10001: {
  10914. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  10915. doItCall: () => {
  10916. const upgradeSkills = this.getUpgradeSkills();
  10917. return upgradeSkills.map(({ heroId, skill }, index) => ({
  10918. name: 'heroUpgradeSkill',
  10919. args: { heroId, skill },
  10920. ident: `heroUpgradeSkill_${index}`,
  10921. }));
  10922. },
  10923. isWeCanDo: () => {
  10924. const upgradeSkills = this.getUpgradeSkills();
  10925. let sumGold = 0;
  10926. for (const skill of upgradeSkills) {
  10927. sumGold += this.skillCost(skill.value);
  10928. if (!skill.heroId) {
  10929. return false;
  10930. }
  10931. }
  10932. return this.questInfo['userGetInfo'].gold > sumGold;
  10933. },
  10934. },
  10935. 10002: {
  10936. description: 'Пройди 10 миссий', // --------------
  10937. isWeCanDo: () => false,
  10938. },
  10939. 10003: {
  10940. description: 'Пройди 3 героические миссии', // ++++++++++++++++
  10941. isWeCanDo: () => {
  10942. const vipPoints = +this.questInfo.userGetInfo.vipPoints;
  10943. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10944. return (vipPoints > 100 || goldTicket) && this.getHeroicMissionId();
  10945. },
  10946. doItCall: () => {
  10947. const selectedMissionId = this.getHeroicMissionId();
  10948. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10949. const vipLevel = Math.max(...lib.data.level.vip.filter(l => l.vipPoints <= +this.questInfo.userGetInfo.vipPoints).map(l => l.level));
  10950. // Возвращаем массив команд для рейда
  10951. if (vipLevel >= 5 || goldTicket) {
  10952. return [{ name: 'missionRaid', args: { id: selectedMissionId, times: 3 }, ident: 'missionRaid_1' }];
  10953. } else {
  10954. return [
  10955. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_1' },
  10956. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_2' },
  10957. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_3' },
  10958. ];
  10959. }
  10960. },
  10961. },
  10962. 10004: {
  10963. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  10964. isWeCanDo: () => false,
  10965. },
  10966. 10006: {
  10967. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  10968. doItCall: () => [
  10969. {
  10970. name: 'refillableAlchemyUse',
  10971. args: { multi: false },
  10972. ident: 'refillableAlchemyUse',
  10973. },
  10974. ],
  10975. isWeCanDo: () => {
  10976. const starMoney = this.questInfo['userGetInfo'].starMoney;
  10977. return starMoney >= 20;
  10978. },
  10979. },
  10980. 10007: {
  10981. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  10982. doItCall: () => [{ name: 'gacha_open', args: { ident: 'heroGacha', free: true, pack: false }, ident: 'gacha_open' }],
  10983. isWeCanDo: () => {
  10984. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  10985. return soulCrystal > 0;
  10986. },
  10987. },
  10988. 10016: {
  10989. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  10990. doItCall: () => [{ name: 'clanSendDailyGifts', args: {}, ident: 'clanSendDailyGifts' }],
  10991. isWeCanDo: () => true,
  10992. },
  10993. 10018: {
  10994. description: 'Используй зелье опыта', // ++++++++++++++++
  10995. doItCall: () => {
  10996. const expHero = this.getExpHero();
  10997. return [
  10998. {
  10999. name: 'consumableUseHeroXp',
  11000. args: {
  11001. heroId: expHero.heroId,
  11002. libId: expHero.libId,
  11003. amount: 1,
  11004. },
  11005. ident: 'consumableUseHeroXp',
  11006. },
  11007. ];
  11008. },
  11009. isWeCanDo: () => {
  11010. const expHero = this.getExpHero();
  11011. return expHero.heroId && expHero.libId;
  11012. },
  11013. },
  11014. 10019: {
  11015. description: 'Открой 1 сундук в Башне',
  11016. doItFunc: testTower,
  11017. isWeCanDo: () => false,
  11018. },
  11019. 10020: {
  11020. description: 'Открой 3 сундука в Запределье', // Готово
  11021. doItCall: () => {
  11022. return this.getOutlandChest();
  11023. },
  11024. isWeCanDo: () => {
  11025. const outlandChest = this.getOutlandChest();
  11026. return outlandChest.length > 0;
  11027. },
  11028. },
  11029. 10021: {
  11030. description: 'Собери 75 Титанита в Подземелье Гильдии',
  11031. isWeCanDo: () => false,
  11032. },
  11033. 10022: {
  11034. description: 'Собери 150 Титанита в Подземелье Гильдии',
  11035. doItFunc: testDungeon,
  11036. isWeCanDo: () => false,
  11037. },
  11038. 10023: {
  11039. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  11040. doItCall: () => {
  11041. const heroId = this.getHeroIdTitanGift();
  11042. return [
  11043. { name: 'heroTitanGiftLevelUp', args: { heroId }, ident: 'heroTitanGiftLevelUp' },
  11044. { name: 'heroTitanGiftDrop', args: { heroId }, ident: 'heroTitanGiftDrop' },
  11045. ];
  11046. },
  11047. isWeCanDo: () => {
  11048. const heroId = this.getHeroIdTitanGift();
  11049. return heroId;
  11050. },
  11051. },
  11052. 10024: {
  11053. description: 'Повысь уровень любого артефакта один раз', // Готово
  11054. doItCall: () => {
  11055. const upArtifact = this.getUpgradeArtifact();
  11056. return [
  11057. {
  11058. name: 'heroArtifactLevelUp',
  11059. args: {
  11060. heroId: upArtifact.heroId,
  11061. slotId: upArtifact.slotId,
  11062. },
  11063. ident: `heroArtifactLevelUp`,
  11064. },
  11065. ];
  11066. },
  11067. isWeCanDo: () => {
  11068. const upgradeArtifact = this.getUpgradeArtifact();
  11069. return upgradeArtifact.heroId;
  11070. },
  11071. },
  11072. 10025: {
  11073. description: 'Начни 1 Экспедицию',
  11074. doItFunc: checkExpedition,
  11075. isWeCanDo: () => false,
  11076. },
  11077. 10026: {
  11078. description: 'Начни 4 Экспедиции', // --------------
  11079. doItFunc: checkExpedition,
  11080. isWeCanDo: () => false,
  11081. },
  11082. 10027: {
  11083. description: 'Победи в 1 бою Турнира Стихий',
  11084. doItFunc: testTitanArena,
  11085. isWeCanDo: () => false,
  11086. },
  11087. 10028: {
  11088. description: 'Повысь уровень любого артефакта титанов', // Готово
  11089. doItCall: () => {
  11090. const upTitanArtifact = this.getUpgradeTitanArtifact();
  11091. return [
  11092. {
  11093. name: 'titanArtifactLevelUp',
  11094. args: {
  11095. titanId: upTitanArtifact.titanId,
  11096. slotId: upTitanArtifact.slotId,
  11097. },
  11098. ident: `titanArtifactLevelUp`,
  11099. },
  11100. ];
  11101. },
  11102. isWeCanDo: () => {
  11103. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  11104. return upgradeTitanArtifact.titanId;
  11105. },
  11106. },
  11107. 10029: {
  11108. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  11109. doItCall: () => [{ name: 'titanArtifactChestOpen', args: { amount: 1, free: true }, ident: 'titanArtifactChestOpen' }],
  11110. isWeCanDo: () => {
  11111. return this.questInfo['inventoryGet']?.consumable[55] > 0;
  11112. },
  11113. },
  11114. 10030: {
  11115. description: 'Улучши облик любого героя 1 раз', // Готово
  11116. doItCall: () => {
  11117. const upSkin = this.getUpgradeSkin();
  11118. return [
  11119. {
  11120. name: 'heroSkinUpgrade',
  11121. args: {
  11122. heroId: upSkin.heroId,
  11123. skinId: upSkin.skinId,
  11124. },
  11125. ident: `heroSkinUpgrade`,
  11126. },
  11127. ];
  11128. },
  11129. isWeCanDo: () => {
  11130. const upgradeSkin = this.getUpgradeSkin();
  11131. return upgradeSkin.heroId;
  11132. },
  11133. },
  11134. 10031: {
  11135. description: 'Победи в 6 боях Турнира Стихий', // --------------
  11136. doItFunc: testTitanArena,
  11137. isWeCanDo: () => false,
  11138. },
  11139. 10043: {
  11140. description: 'Начни или присоеденись к Приключению', // --------------
  11141. isWeCanDo: () => false,
  11142. },
  11143. 10044: {
  11144. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  11145. doItCall: () => [{ name: 'pet_chestOpen', args: { amount: 1, paid: false }, ident: 'pet_chestOpen' }],
  11146. isWeCanDo: () => {
  11147. return this.questInfo['inventoryGet']?.consumable[90] > 0;
  11148. },
  11149. },
  11150. 10046: {
  11151. /**
  11152. * TODO: Watch Adventure
  11153. * TODO: Смотреть приключение
  11154. */
  11155. description: 'Открой 3 сундука в Приключениях',
  11156. isWeCanDo: () => false,
  11157. },
  11158. 10047: {
  11159. description: 'Набери 150 очков активности в Гильдии', // Готово
  11160. doItCall: () => {
  11161. const enchantRune = this.getEnchantRune();
  11162. return [
  11163. {
  11164. name: 'heroEnchantRune',
  11165. args: {
  11166. heroId: enchantRune.heroId,
  11167. tier: enchantRune.tier,
  11168. items: {
  11169. consumable: { [enchantRune.itemId]: 1 },
  11170. },
  11171. },
  11172. ident: `heroEnchantRune`,
  11173. },
  11174. ];
  11175. },
  11176. isWeCanDo: () => {
  11177. const userInfo = this.questInfo['userGetInfo'];
  11178. const enchantRune = this.getEnchantRune();
  11179. return enchantRune.heroId && userInfo.gold > 1e3;
  11180. },
  11181. },
  11182. };
  11183.  
  11184. constructor(resolve, reject, questInfo) {
  11185. this.resolve = resolve;
  11186. this.reject = reject;
  11187. }
  11188.  
  11189. init(questInfo) {
  11190. this.questInfo = questInfo;
  11191. this.isAuto = false;
  11192. }
  11193.  
  11194. async autoInit(isAuto) {
  11195. this.isAuto = isAuto || false;
  11196. const quests = {};
  11197. const calls = this.callsList.map((name) => ({
  11198. name,
  11199. args: {},
  11200. ident: name,
  11201. }));
  11202. const result = await Send(JSON.stringify({ calls })).then((e) => e.results);
  11203. for (const call of result) {
  11204. quests[call.ident] = call.result.response;
  11205. }
  11206. this.questInfo = quests;
  11207. }
  11208.  
  11209. async start() {
  11210. const weCanDo = [];
  11211. const selectedActions = getSaveVal('selectedActions', {});
  11212. for (let quest of this.questInfo['questGetAll']) {
  11213. if (quest.id in this.dataQuests && quest.state == 1) {
  11214. if (!selectedActions[quest.id]) {
  11215. selectedActions[quest.id] = {
  11216. checked: false,
  11217. };
  11218. }
  11219.  
  11220. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  11221. if (!isWeCanDo.call(this)) {
  11222. continue;
  11223. }
  11224.  
  11225. weCanDo.push({
  11226. name: quest.id,
  11227. label: I18N(`QUEST_${quest.id}`),
  11228. checked: selectedActions[quest.id].checked,
  11229. });
  11230. }
  11231. }
  11232.  
  11233. if (!weCanDo.length) {
  11234. this.end(I18N('NOTHING_TO_DO'));
  11235. return;
  11236. }
  11237.  
  11238. console.log(weCanDo);
  11239. let taskList = [];
  11240. if (this.isAuto) {
  11241. taskList = weCanDo;
  11242. } else {
  11243. const answer = await popup.confirm(
  11244. `${I18N('YOU_CAN_COMPLETE')}:`,
  11245. [
  11246. { msg: I18N('BTN_DO_IT'), result: true },
  11247. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11248. ],
  11249. weCanDo
  11250. );
  11251. if (!answer) {
  11252. this.end('');
  11253. return;
  11254. }
  11255. taskList = popup.getCheckBoxes();
  11256. taskList.forEach((e) => {
  11257. selectedActions[e.name].checked = e.checked;
  11258. });
  11259. setSaveVal('selectedActions', selectedActions);
  11260. }
  11261.  
  11262. const calls = [];
  11263. let countChecked = 0;
  11264. for (const task of taskList) {
  11265. if (task.checked) {
  11266. countChecked++;
  11267. const quest = this.dataQuests[task.name];
  11268. console.log(quest.description);
  11269.  
  11270. if (quest.doItCall) {
  11271. const doItCall = quest.doItCall.call(this);
  11272. calls.push(...doItCall);
  11273. }
  11274. }
  11275. }
  11276.  
  11277. if (!countChecked) {
  11278. this.end(I18N('NOT_QUEST_COMPLETED'));
  11279. return;
  11280. }
  11281.  
  11282. const result = await Send(JSON.stringify({ calls }));
  11283. if (result.error) {
  11284. console.error(result.error, result.error.call);
  11285. }
  11286. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  11287. }
  11288.  
  11289. errorHandling(error) {
  11290. //console.error(error);
  11291. let errorInfo = error.toString() + '\n';
  11292. try {
  11293. const errorStack = error.stack.split('\n');
  11294. const endStack = errorStack.map((e) => e.split('@')[0]).indexOf('testDoYourBest');
  11295. errorInfo += errorStack.slice(0, endStack).join('\n');
  11296. } catch (e) {
  11297. errorInfo += error.stack;
  11298. }
  11299. copyText(errorInfo);
  11300. }
  11301.  
  11302. skillCost(lvl) {
  11303. return 573 * lvl ** 0.9 + lvl ** 2.379;
  11304. }
  11305.  
  11306. getUpgradeSkills() {
  11307. const heroes = Object.values(this.questInfo['heroGetAll']);
  11308. const upgradeSkills = [
  11309. { heroId: 0, slotId: 0, value: 130 },
  11310. { heroId: 0, slotId: 0, value: 130 },
  11311. { heroId: 0, slotId: 0, value: 130 },
  11312. ];
  11313. const skillLib = lib.getData('skill');
  11314. /**
  11315. * color - 1 (белый) открывает 1 навык
  11316. * color - 2 (зеленый) открывает 2 навык
  11317. * color - 4 (синий) открывает 3 навык
  11318. * color - 7 (фиолетовый) открывает 4 навык
  11319. */
  11320. const colors = [1, 2, 4, 7];
  11321. for (const hero of heroes) {
  11322. const level = hero.level;
  11323. const color = hero.color;
  11324. for (let skillId in hero.skills) {
  11325. const tier = skillLib[skillId].tier;
  11326. const sVal = hero.skills[skillId];
  11327. if (color < colors[tier] || tier < 1 || tier > 4) {
  11328. continue;
  11329. }
  11330. for (let upSkill of upgradeSkills) {
  11331. if (sVal < upSkill.value && sVal < level) {
  11332. upSkill.value = sVal;
  11333. upSkill.heroId = hero.id;
  11334. upSkill.skill = tier;
  11335. break;
  11336. }
  11337. }
  11338. }
  11339. }
  11340. return upgradeSkills;
  11341. }
  11342.  
  11343. getUpgradeArtifact() {
  11344. const heroes = Object.values(this.questInfo['heroGetAll']);
  11345. const inventory = this.questInfo['inventoryGet'];
  11346. const upArt = { heroId: 0, slotId: 0, level: 100 };
  11347.  
  11348. const heroLib = lib.getData('hero');
  11349. const artifactLib = lib.getData('artifact');
  11350.  
  11351. for (const hero of heroes) {
  11352. const heroInfo = heroLib[hero.id];
  11353. const level = hero.level;
  11354. if (level < 20) {
  11355. continue;
  11356. }
  11357.  
  11358. for (let slotId in hero.artifacts) {
  11359. const art = hero.artifacts[slotId];
  11360. /* Текущая звезданость арта */
  11361. const star = art.star;
  11362. if (!star) {
  11363. continue;
  11364. }
  11365. /* Текущий уровень арта */
  11366. const level = art.level;
  11367. if (level >= 100) {
  11368. continue;
  11369. }
  11370. /* Идентификатор арта в библиотеке */
  11371. const artifactId = heroInfo.artifacts[slotId];
  11372. const artInfo = artifactLib.id[artifactId];
  11373. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  11374.  
  11375. const costCurrency = Object.keys(costNextLevel).pop();
  11376. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11377. const costId = costValues[0];
  11378. const costValue = +costValues[1];
  11379.  
  11380. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11381. if (level < upArt.level && inventory[costCurrency][costId] >= costValue) {
  11382. upArt.level = level;
  11383. upArt.heroId = hero.id;
  11384. upArt.slotId = slotId;
  11385. upArt.costCurrency = costCurrency;
  11386. upArt.costId = costId;
  11387. upArt.costValue = costValue;
  11388. }
  11389. }
  11390. }
  11391. return upArt;
  11392. }
  11393.  
  11394. getUpgradeSkin() {
  11395. const heroes = Object.values(this.questInfo['heroGetAll']);
  11396. const inventory = this.questInfo['inventoryGet'];
  11397. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  11398.  
  11399. const skinLib = lib.getData('skin');
  11400.  
  11401. for (const hero of heroes) {
  11402. const level = hero.level;
  11403. if (level < 20) {
  11404. continue;
  11405. }
  11406.  
  11407. for (let skinId in hero.skins) {
  11408. /* Текущий уровень скина */
  11409. const level = hero.skins[skinId];
  11410. if (level >= 60) {
  11411. continue;
  11412. }
  11413. /* Идентификатор скина в библиотеке */
  11414. const skinInfo = skinLib[skinId];
  11415. if (!skinInfo.statData.levels?.[level + 1]) {
  11416. continue;
  11417. }
  11418. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  11419.  
  11420. const costCurrency = Object.keys(costNextLevel).pop();
  11421. const costCurrencyId = Object.keys(costNextLevel[costCurrency]).pop();
  11422. const costValue = +costNextLevel[costCurrency][costCurrencyId];
  11423.  
  11424. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11425. if (level < upSkin.level && costValue < upSkin.cost && inventory[costCurrency][costCurrencyId] >= costValue) {
  11426. upSkin.cost = costValue;
  11427. upSkin.level = level;
  11428. upSkin.heroId = hero.id;
  11429. upSkin.skinId = skinId;
  11430. upSkin.costCurrency = costCurrency;
  11431. upSkin.costCurrencyId = costCurrencyId;
  11432. }
  11433. }
  11434. }
  11435. return upSkin;
  11436. }
  11437.  
  11438. getUpgradeTitanArtifact() {
  11439. const titans = Object.values(this.questInfo['titanGetAll']);
  11440. const inventory = this.questInfo['inventoryGet'];
  11441. const userInfo = this.questInfo['userGetInfo'];
  11442. const upArt = { titanId: 0, slotId: 0, level: 120 };
  11443.  
  11444. const titanLib = lib.getData('titan');
  11445. const artTitanLib = lib.getData('titanArtifact');
  11446.  
  11447. for (const titan of titans) {
  11448. const titanInfo = titanLib[titan.id];
  11449. // const level = titan.level
  11450. // if (level < 20) {
  11451. // continue;
  11452. // }
  11453.  
  11454. for (let slotId in titan.artifacts) {
  11455. const art = titan.artifacts[slotId];
  11456. /* Текущая звезданость арта */
  11457. const star = art.star;
  11458. if (!star) {
  11459. continue;
  11460. }
  11461. /* Текущий уровень арта */
  11462. const level = art.level;
  11463. if (level >= 120) {
  11464. continue;
  11465. }
  11466. /* Идентификатор арта в библиотеке */
  11467. const artifactId = titanInfo.artifacts[slotId];
  11468. const artInfo = artTitanLib.id[artifactId];
  11469. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  11470.  
  11471. const costCurrency = Object.keys(costNextLevel).pop();
  11472. let costValue = 0;
  11473. let currentValue = 0;
  11474. if (costCurrency == 'gold') {
  11475. costValue = costNextLevel[costCurrency];
  11476. currentValue = userInfo.gold;
  11477. } else {
  11478. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11479. const costId = costValues[0];
  11480. costValue = +costValues[1];
  11481. currentValue = inventory[costCurrency][costId];
  11482. }
  11483.  
  11484. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11485. if (level < upArt.level && currentValue >= costValue) {
  11486. upArt.level = level;
  11487. upArt.titanId = titan.id;
  11488. upArt.slotId = slotId;
  11489. break;
  11490. }
  11491. }
  11492. }
  11493. return upArt;
  11494. }
  11495.  
  11496. getEnchantRune() {
  11497. const heroes = Object.values(this.questInfo['heroGetAll']);
  11498. const inventory = this.questInfo['inventoryGet'];
  11499. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  11500. for (let i = 1; i <= 4; i++) {
  11501. if (inventory.consumable[i] > 0) {
  11502. enchRune.itemId = i;
  11503. break;
  11504. }
  11505. return enchRune;
  11506. }
  11507.  
  11508. const runeLib = lib.getData('rune');
  11509. const runeLvls = Object.values(runeLib.level);
  11510. /**
  11511. * color - 4 (синий) открывает 1 и 2 символ
  11512. * color - 7 (фиолетовый) открывает 3 символ
  11513. * color - 8 (фиолетовый +1) открывает 4 символ
  11514. * color - 9 (фиолетовый +2) открывает 5 символ
  11515. */
  11516. // TODO: кажется надо учесть уровень команды
  11517. const colors = [4, 4, 7, 8, 9];
  11518. for (const hero of heroes) {
  11519. const color = hero.color;
  11520.  
  11521. for (let runeTier in hero.runes) {
  11522. /* Проверка на доступность руны */
  11523. if (color < colors[runeTier]) {
  11524. continue;
  11525. }
  11526. /* Текущий опыт руны */
  11527. const exp = hero.runes[runeTier];
  11528. if (exp >= 43750) {
  11529. continue;
  11530. }
  11531.  
  11532. let level = 0;
  11533. if (exp) {
  11534. for (let lvl of runeLvls) {
  11535. if (exp >= lvl.enchantValue) {
  11536. level = lvl.level;
  11537. } else {
  11538. break;
  11539. }
  11540. }
  11541. }
  11542. /** Уровень героя необходимый для уровня руны */
  11543. const heroLevel = runeLib.level[level].heroLevel;
  11544. if (hero.level < heroLevel) {
  11545. continue;
  11546. }
  11547.  
  11548. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11549. if (exp < enchRune.exp) {
  11550. enchRune.exp = exp;
  11551. enchRune.heroId = hero.id;
  11552. enchRune.tier = runeTier;
  11553. break;
  11554. }
  11555. }
  11556. }
  11557. return enchRune;
  11558. }
  11559.  
  11560. getOutlandChest() {
  11561. const bosses = this.questInfo['bossGetAll'];
  11562.  
  11563. const calls = [];
  11564.  
  11565. for (let boss of bosses) {
  11566. if (boss.mayRaid) {
  11567. calls.push({
  11568. name: 'bossRaid',
  11569. args: {
  11570. bossId: boss.id,
  11571. },
  11572. ident: 'bossRaid_' + boss.id,
  11573. });
  11574. calls.push({
  11575. name: 'bossOpenChest',
  11576. args: {
  11577. bossId: boss.id,
  11578. amount: 1,
  11579. starmoney: 0,
  11580. },
  11581. ident: 'bossOpenChest_' + boss.id,
  11582. });
  11583. } else if (boss.chestId == 1) {
  11584. calls.push({
  11585. name: 'bossOpenChest',
  11586. args: {
  11587. bossId: boss.id,
  11588. amount: 1,
  11589. starmoney: 0,
  11590. },
  11591. ident: 'bossOpenChest_' + boss.id,
  11592. });
  11593. }
  11594. }
  11595.  
  11596. return calls;
  11597. }
  11598.  
  11599. getExpHero() {
  11600. const heroes = Object.values(this.questInfo['heroGetAll']);
  11601. const inventory = this.questInfo['inventoryGet'];
  11602. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  11603. /** зелья опыта (consumable 9, 10, 11, 12) */
  11604. for (let i = 9; i <= 12; i++) {
  11605. if (inventory.consumable[i]) {
  11606. expHero.libId = i;
  11607. break;
  11608. }
  11609. }
  11610.  
  11611. for (const hero of heroes) {
  11612. const exp = hero.xp;
  11613. if (exp < expHero.exp) {
  11614. expHero.heroId = hero.id;
  11615. }
  11616. }
  11617. return expHero;
  11618. }
  11619.  
  11620. getHeroIdTitanGift() {
  11621. const heroes = Object.values(this.questInfo['heroGetAll']);
  11622. const inventory = this.questInfo['inventoryGet'];
  11623. const user = this.questInfo['userGetInfo'];
  11624. const titanGiftLib = lib.getData('titanGift');
  11625. /** Искры */
  11626. const titanGift = inventory.consumable[24];
  11627. let heroId = 0;
  11628. let minLevel = 30;
  11629.  
  11630. if (titanGift < 250 || user.gold < 7000) {
  11631. return 0;
  11632. }
  11633.  
  11634. for (const hero of heroes) {
  11635. if (hero.titanGiftLevel >= 30) {
  11636. continue;
  11637. }
  11638.  
  11639. if (!hero.titanGiftLevel) {
  11640. return hero.id;
  11641. }
  11642.  
  11643. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  11644. if (minLevel > hero.titanGiftLevel && titanGift >= cost.consumable[24] && user.gold >= cost.gold) {
  11645. minLevel = hero.titanGiftLevel;
  11646. heroId = hero.id;
  11647. }
  11648. }
  11649.  
  11650. return heroId;
  11651. }
  11652.  
  11653. getHeroicMissionId() {
  11654. // Получаем доступные миссии с 3 звездами
  11655. const availableMissionsToRaid = Object.values(this.questInfo.missionGetAll)
  11656. .filter((mission) => mission.stars === 3)
  11657. .map((mission) => mission.id);
  11658.  
  11659. // Получаем героев для улучшения, у которых меньше 6 звезд
  11660. const heroesToUpgrade = Object.values(this.questInfo.heroGetAll)
  11661. .filter((hero) => hero.star < 6)
  11662. .sort((a, b) => b.power - a.power)
  11663. .map((hero) => hero.id);
  11664.  
  11665. // Получаем героические миссии, которые доступны для рейдов
  11666. const heroicMissions = Object.values(lib.data.mission).filter((mission) => mission.isHeroic && availableMissionsToRaid.includes(mission.id));
  11667.  
  11668. // Собираем дропы из героических миссий
  11669. const drops = heroicMissions.map((mission) => {
  11670. const lastWave = mission.normalMode.waves[mission.normalMode.waves.length - 1];
  11671. const allRewards = lastWave.enemies[lastWave.enemies.length - 1]
  11672. .drop.map((drop) => drop.reward);
  11673.  
  11674. const heroId = +Object.keys(allRewards.find((reward) => reward.fragmentHero).fragmentHero).pop();
  11675.  
  11676. return { id: mission.id, heroId };
  11677. });
  11678.  
  11679. // Определяем, какие дропы подходят для героев, которых нужно улучшить
  11680. const heroDrops = heroesToUpgrade.map((heroId) => drops.find((drop) => drop.heroId == heroId)).filter((drop) => drop);
  11681. const firstMission = heroDrops[0];
  11682. // Выбираем миссию для рейда
  11683. const selectedMissionId = firstMission ? firstMission.id : 1;
  11684.  
  11685. const stamina = this.questInfo.userGetInfo.refillable.find((x) => x.id == 1).amount;
  11686. const costMissions = 3 * lib.data.mission[selectedMissionId].normalMode.teamExp;
  11687. if (stamina < costMissions) {
  11688. console.log('Энергии не достаточно');
  11689. return 0;
  11690. }
  11691. return selectedMissionId;
  11692. }
  11693.  
  11694. end(status) {
  11695. setProgress(status, true);
  11696. this.resolve();
  11697. }
  11698. }
  11699.  
  11700. this.questRun = dailyQuests;
  11701. this.HWHClasses.dailyQuests = dailyQuests;
  11702.  
  11703. function testDoYourBest() {
  11704. const { doYourBest } = HWHClasses;
  11705. return new Promise((resolve, reject) => {
  11706. const doIt = new doYourBest(resolve, reject);
  11707. doIt.start();
  11708. });
  11709. }
  11710.  
  11711. /**
  11712. * Do everything button
  11713. *
  11714. * Кнопка сделать все
  11715. */
  11716. class doYourBest {
  11717.  
  11718. funcList = [
  11719. {
  11720. name: 'getOutland',
  11721. label: I18N('ASSEMBLE_OUTLAND'),
  11722. checked: false
  11723. },
  11724. {
  11725. name: 'testTower',
  11726. label: I18N('PASS_THE_TOWER'),
  11727. checked: false
  11728. },
  11729. {
  11730. name: 'checkExpedition',
  11731. label: I18N('CHECK_EXPEDITIONS'),
  11732. checked: false
  11733. },
  11734. {
  11735. name: 'testTitanArena',
  11736. label: I18N('COMPLETE_TOE'),
  11737. checked: false
  11738. },
  11739. {
  11740. name: 'mailGetAll',
  11741. label: I18N('COLLECT_MAIL'),
  11742. checked: false
  11743. },
  11744. {
  11745. name: 'collectAllStuff',
  11746. label: I18N('COLLECT_MISC'),
  11747. title: I18N('COLLECT_MISC_TITLE'),
  11748. checked: false
  11749. },
  11750. {
  11751. name: 'getDailyBonus',
  11752. label: I18N('DAILY_BONUS'),
  11753. checked: false
  11754. },
  11755. {
  11756. name: 'dailyQuests',
  11757. label: I18N('DO_DAILY_QUESTS'),
  11758. checked: false
  11759. },
  11760. {
  11761. name: 'rollAscension',
  11762. label: I18N('SEER_TITLE'),
  11763. checked: false
  11764. },
  11765. {
  11766. name: 'questAllFarm',
  11767. label: I18N('COLLECT_QUEST_REWARDS'),
  11768. checked: false
  11769. },
  11770. {
  11771. name: 'testDungeon',
  11772. label: I18N('COMPLETE_DUNGEON'),
  11773. checked: false
  11774. },
  11775. {
  11776. name: 'synchronization',
  11777. label: I18N('MAKE_A_SYNC'),
  11778. checked: false
  11779. },
  11780. {
  11781. name: 'reloadGame',
  11782. label: I18N('RELOAD_GAME'),
  11783. checked: false
  11784. },
  11785. ];
  11786.  
  11787. functions = {
  11788. getOutland,
  11789. testTower,
  11790. checkExpedition,
  11791. testTitanArena,
  11792. mailGetAll,
  11793. collectAllStuff: async () => {
  11794. await offerFarmAllReward();
  11795. 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"}]}');
  11796. },
  11797. dailyQuests: async function () {
  11798. const quests = new dailyQuests(() => { }, () => { });
  11799. await quests.autoInit(true);
  11800. await quests.start();
  11801. },
  11802. rollAscension,
  11803. getDailyBonus,
  11804. questAllFarm,
  11805. testDungeon,
  11806. synchronization: async () => {
  11807. cheats.refreshGame();
  11808. },
  11809. reloadGame: async () => {
  11810. location.reload();
  11811. },
  11812. }
  11813.  
  11814. constructor(resolve, reject, questInfo) {
  11815. this.resolve = resolve;
  11816. this.reject = reject;
  11817. this.questInfo = questInfo
  11818. }
  11819.  
  11820. async start() {
  11821. const selectedDoIt = getSaveVal('selectedDoIt', {});
  11822.  
  11823. this.funcList.forEach(task => {
  11824. if (!selectedDoIt[task.name]) {
  11825. selectedDoIt[task.name] = {
  11826. checked: task.checked
  11827. }
  11828. } else {
  11829. task.checked = selectedDoIt[task.name].checked
  11830. }
  11831. });
  11832.  
  11833. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  11834. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11835. { msg: I18N('BTN_GO'), result: true },
  11836. ], this.funcList);
  11837.  
  11838. if (!answer) {
  11839. this.end('');
  11840. return;
  11841. }
  11842.  
  11843. const taskList = popup.getCheckBoxes();
  11844. taskList.forEach(task => {
  11845. selectedDoIt[task.name].checked = task.checked;
  11846. });
  11847. setSaveVal('selectedDoIt', selectedDoIt);
  11848. for (const task of popup.getCheckBoxes()) {
  11849. if (task.checked) {
  11850. try {
  11851. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  11852. await this.functions[task.name]();
  11853. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  11854. } catch (error) {
  11855. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  11856. { msg: I18N('BTN_NO'), result: false },
  11857. { msg: I18N('BTN_YES'), result: true },
  11858. ])) {
  11859. this.errorHandling(error);
  11860. }
  11861. }
  11862. }
  11863. }
  11864. setTimeout((msg) => {
  11865. this.end(msg);
  11866. }, 2000, I18N('ALL_TASK_COMPLETED'));
  11867. return;
  11868. }
  11869.  
  11870. errorHandling(error) {
  11871. //console.error(error);
  11872. let errorInfo = error.toString() + '\n';
  11873. try {
  11874. const errorStack = error.stack.split('\n');
  11875. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  11876. errorInfo += errorStack.slice(0, endStack).join('\n');
  11877. } catch (e) {
  11878. errorInfo += error.stack;
  11879. }
  11880. copyText(errorInfo);
  11881. }
  11882.  
  11883. end(status) {
  11884. setProgress(status, true);
  11885. this.resolve();
  11886. }
  11887. }
  11888.  
  11889. this.HWHClasses.doYourBest = doYourBest;
  11890.  
  11891. /**
  11892. * Passing the adventure along the specified route
  11893. *
  11894. * Прохождение приключения по указанному маршруту
  11895. */
  11896. function testAdventure(type) {
  11897. const { executeAdventure } = HWHClasses;
  11898. return new Promise((resolve, reject) => {
  11899. const bossBattle = new executeAdventure(resolve, reject);
  11900. bossBattle.start(type);
  11901. });
  11902. }
  11903.  
  11904. /**
  11905. * Passing the adventure along the specified route
  11906. *
  11907. * Прохождение приключения по указанному маршруту
  11908. */
  11909. class executeAdventure {
  11910.  
  11911. type = 'default';
  11912.  
  11913. actions = {
  11914. default: {
  11915. getInfo: "adventure_getInfo",
  11916. startBattle: 'adventure_turnStartBattle',
  11917. endBattle: 'adventure_endBattle',
  11918. collectBuff: 'adventure_turnCollectBuff'
  11919. },
  11920. solo: {
  11921. getInfo: "adventureSolo_getInfo",
  11922. startBattle: 'adventureSolo_turnStartBattle',
  11923. endBattle: 'adventureSolo_endBattle',
  11924. collectBuff: 'adventureSolo_turnCollectBuff'
  11925. }
  11926. }
  11927.  
  11928. terminatеReason = I18N('UNKNOWN');
  11929. callAdventureInfo = {
  11930. name: "adventure_getInfo",
  11931. args: {},
  11932. ident: "adventure_getInfo"
  11933. }
  11934. callTeamGetAll = {
  11935. name: "teamGetAll",
  11936. args: {},
  11937. ident: "teamGetAll"
  11938. }
  11939. callTeamGetFavor = {
  11940. name: "teamGetFavor",
  11941. args: {},
  11942. ident: "teamGetFavor"
  11943. }
  11944. callStartBattle = {
  11945. name: "adventure_turnStartBattle",
  11946. args: {},
  11947. ident: "body"
  11948. }
  11949. callEndBattle = {
  11950. name: "adventure_endBattle",
  11951. args: {
  11952. result: {},
  11953. progress: {},
  11954. },
  11955. ident: "body"
  11956. }
  11957. callCollectBuff = {
  11958. name: "adventure_turnCollectBuff",
  11959. args: {},
  11960. ident: "body"
  11961. }
  11962.  
  11963. constructor(resolve, reject) {
  11964. this.resolve = resolve;
  11965. this.reject = reject;
  11966. }
  11967.  
  11968. async start(type) {
  11969. this.type = type || this.type;
  11970. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  11971. const data = await Send(JSON.stringify({
  11972. calls: [
  11973. this.callAdventureInfo,
  11974. this.callTeamGetAll,
  11975. this.callTeamGetFavor
  11976. ]
  11977. }));
  11978. return this.checkAdventureInfo(data.results);
  11979. }
  11980.  
  11981. async getPath() {
  11982. const oldVal = getSaveVal('adventurePath', '');
  11983. const keyPath = `adventurePath:${this.mapIdent}`;
  11984. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  11985. {
  11986. msg: I18N('START_ADVENTURE'),
  11987. placeholder: '1,2,3,4,5,6',
  11988. isInput: true,
  11989. default: getSaveVal(keyPath, oldVal)
  11990. },
  11991. {
  11992. msg: I18N('BTN_CANCEL'),
  11993. result: false,
  11994. isCancel: true
  11995. },
  11996. ]);
  11997. if (!answer) {
  11998. this.terminatеReason = I18N('BTN_CANCELED');
  11999. return false;
  12000. }
  12001.  
  12002. let path = answer.split(',');
  12003. if (path.length < 2) {
  12004. path = answer.split('-');
  12005. }
  12006. if (path.length < 2) {
  12007. this.terminatеReason = I18N('MUST_TWO_POINTS');
  12008. return false;
  12009. }
  12010.  
  12011. for (let p in path) {
  12012. path[p] = +path[p].trim()
  12013. if (Number.isNaN(path[p])) {
  12014. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  12015. return false;
  12016. }
  12017. }
  12018.  
  12019. if (!this.checkPath(path)) {
  12020. return false;
  12021. }
  12022. setSaveVal(keyPath, answer);
  12023. return path;
  12024. }
  12025.  
  12026. checkPath(path) {
  12027. for (let i = 0; i < path.length - 1; i++) {
  12028. const currentPoint = path[i];
  12029. const nextPoint = path[i + 1];
  12030.  
  12031. const isValidPath = this.paths.some(p =>
  12032. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  12033. (p.from_id === nextPoint && p.to_id === currentPoint)
  12034. );
  12035.  
  12036. if (!isValidPath) {
  12037. this.terminatеReason = I18N('INCORRECT_WAY', {
  12038. from: currentPoint,
  12039. to: nextPoint,
  12040. });
  12041. return false;
  12042. }
  12043. }
  12044.  
  12045. return true;
  12046. }
  12047.  
  12048. async checkAdventureInfo(data) {
  12049. this.advInfo = data[0].result.response;
  12050. if (!this.advInfo) {
  12051. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  12052. return this.end();
  12053. }
  12054. const heroesTeam = data[1].result.response.adventure_hero;
  12055. const favor = data[2]?.result.response.adventure_hero;
  12056. const heroes = heroesTeam.slice(0, 5);
  12057. const pet = heroesTeam[5];
  12058. this.args = {
  12059. pet,
  12060. heroes,
  12061. favor,
  12062. path: [],
  12063. broadcast: false
  12064. }
  12065. const advUserInfo = this.advInfo.users[userInfo.id];
  12066. this.turnsLeft = advUserInfo.turnsLeft;
  12067. this.currentNode = advUserInfo.currentNode;
  12068. this.nodes = this.advInfo.nodes;
  12069. this.paths = this.advInfo.paths;
  12070. this.mapIdent = this.advInfo.mapIdent;
  12071.  
  12072. this.path = await this.getPath();
  12073. if (!this.path) {
  12074. return this.end();
  12075. }
  12076.  
  12077. if (this.currentNode == 1 && this.path[0] != 1) {
  12078. this.path.unshift(1);
  12079. }
  12080.  
  12081. return this.loop();
  12082. }
  12083.  
  12084. async loop() {
  12085. const position = this.path.indexOf(+this.currentNode);
  12086. if (!(~position)) {
  12087. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  12088. return this.end();
  12089. }
  12090. this.path = this.path.slice(position);
  12091. if ((this.path.length - 1) > this.turnsLeft &&
  12092. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  12093. { msg: I18N('YES_CONTINUE'), result: false },
  12094. { msg: I18N('BTN_NO'), result: true },
  12095. ])) {
  12096. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  12097. return this.end();
  12098. }
  12099. const toPath = [];
  12100. for (const nodeId of this.path) {
  12101. if (!this.turnsLeft) {
  12102. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  12103. return this.end();
  12104. }
  12105. toPath.push(nodeId);
  12106. console.log(toPath);
  12107. if (toPath.length > 1) {
  12108. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  12109. }
  12110. if (nodeId == this.currentNode) {
  12111. continue;
  12112. }
  12113.  
  12114. const nodeInfo = this.getNodeInfo(nodeId);
  12115. if (nodeInfo.type == 'TYPE_COMBAT') {
  12116. if (nodeInfo.state == 'empty') {
  12117. this.turnsLeft--;
  12118. continue;
  12119. }
  12120.  
  12121. /**
  12122. * Disable regular battle cancellation
  12123. *
  12124. * Отключаем штатную отменую боя
  12125. */
  12126. setIsCancalBattle(false);
  12127. if (await this.battle(toPath)) {
  12128. this.turnsLeft--;
  12129. toPath.splice(0, toPath.indexOf(nodeId));
  12130. nodeInfo.state = 'empty';
  12131. setIsCancalBattle(true);
  12132. continue;
  12133. }
  12134. setIsCancalBattle(true);
  12135. return this.end()
  12136. }
  12137.  
  12138. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  12139. const buff = this.checkBuff(nodeInfo);
  12140. if (buff == null) {
  12141. continue;
  12142. }
  12143.  
  12144. if (await this.collectBuff(buff, toPath)) {
  12145. this.turnsLeft--;
  12146. toPath.splice(0, toPath.indexOf(nodeId));
  12147. continue;
  12148. }
  12149. this.terminatеReason = I18N('BUFF_GET_ERROR');
  12150. return this.end();
  12151. }
  12152. }
  12153. this.terminatеReason = I18N('SUCCESS');
  12154. return this.end();
  12155. }
  12156.  
  12157. /**
  12158. * Carrying out a fight
  12159. *
  12160. * Проведение боя
  12161. */
  12162. async battle(path, preCalc = true) {
  12163. const data = await this.startBattle(path);
  12164. try {
  12165. const battle = data.results[0].result.response.battle;
  12166. const result = await Calc(battle);
  12167. if (result.result.win) {
  12168. const info = await this.endBattle(result);
  12169. if (info.results[0].result.response?.error) {
  12170. this.terminatеReason = I18N('BATTLE_END_ERROR');
  12171. return false;
  12172. }
  12173. } else {
  12174. await this.cancelBattle(result);
  12175.  
  12176. if (preCalc && await this.preCalcBattle(battle)) {
  12177. path = path.slice(-2);
  12178. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  12179. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  12180. const result = await this.battle(path, false);
  12181. if (result) {
  12182. setProgress(I18N('VICTORY'));
  12183. return true;
  12184. }
  12185. }
  12186. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  12187. return false;
  12188. }
  12189. return false;
  12190. }
  12191. } catch (error) {
  12192. console.error(error);
  12193. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  12194. { msg: I18N('BTN_NO'), result: false },
  12195. { msg: I18N('BTN_YES'), result: true },
  12196. ])) {
  12197. this.errorHandling(error, data);
  12198. }
  12199. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  12200. return false;
  12201. }
  12202. return true;
  12203. }
  12204.  
  12205. /**
  12206. * Recalculate battles
  12207. *
  12208. * Прерасчтет битвы
  12209. */
  12210. async preCalcBattle(battle) {
  12211. const countTestBattle = getInput('countTestBattle');
  12212. for (let i = 0; i < countTestBattle; i++) {
  12213. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  12214. const result = await Calc(battle);
  12215. if (result.result.win) {
  12216. console.log(i, countTestBattle);
  12217. return true;
  12218. }
  12219. }
  12220. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  12221. return false;
  12222. }
  12223.  
  12224. /**
  12225. * Starts a fight
  12226. *
  12227. * Начинает бой
  12228. */
  12229. startBattle(path) {
  12230. this.args.path = path;
  12231. this.callStartBattle.name = this.actions[this.type].startBattle;
  12232. this.callStartBattle.args = this.args
  12233. const calls = [this.callStartBattle];
  12234. return Send(JSON.stringify({ calls }));
  12235. }
  12236.  
  12237. cancelBattle(battle) {
  12238. const fixBattle = function (heroes) {
  12239. for (const ids in heroes) {
  12240. const hero = heroes[ids];
  12241. hero.energy = random(1, 999);
  12242. if (hero.hp > 0) {
  12243. hero.hp = random(1, hero.hp);
  12244. }
  12245. }
  12246. }
  12247. fixBattle(battle.progress[0].attackers.heroes);
  12248. fixBattle(battle.progress[0].defenders.heroes);
  12249. return this.endBattle(battle);
  12250. }
  12251.  
  12252. /**
  12253. * Ends the fight
  12254. *
  12255. * Заканчивает бой
  12256. */
  12257. endBattle(battle) {
  12258. this.callEndBattle.name = this.actions[this.type].endBattle;
  12259. this.callEndBattle.args.result = battle.result
  12260. this.callEndBattle.args.progress = battle.progress
  12261. const calls = [this.callEndBattle];
  12262. return Send(JSON.stringify({ calls }));
  12263. }
  12264.  
  12265. /**
  12266. * Checks if you can get a buff
  12267. *
  12268. * Проверяет можно ли получить баф
  12269. */
  12270. checkBuff(nodeInfo) {
  12271. let id = null;
  12272. let value = 0;
  12273. for (const buffId in nodeInfo.buffs) {
  12274. const buff = nodeInfo.buffs[buffId];
  12275. if (buff.owner == null && buff.value > value) {
  12276. id = buffId;
  12277. value = buff.value;
  12278. }
  12279. }
  12280. nodeInfo.buffs[id].owner = 'Я';
  12281. return id;
  12282. }
  12283.  
  12284. /**
  12285. * Collects a buff
  12286. *
  12287. * Собирает баф
  12288. */
  12289. async collectBuff(buff, path) {
  12290. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  12291. this.callCollectBuff.args = { buff, path };
  12292. const calls = [this.callCollectBuff];
  12293. return Send(JSON.stringify({ calls }));
  12294. }
  12295.  
  12296. getNodeInfo(nodeId) {
  12297. return this.nodes.find(node => node.id == nodeId);
  12298. }
  12299.  
  12300. errorHandling(error, data) {
  12301. //console.error(error);
  12302. let errorInfo = error.toString() + '\n';
  12303. try {
  12304. const errorStack = error.stack.split('\n');
  12305. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  12306. errorInfo += errorStack.slice(0, endStack).join('\n');
  12307. } catch (e) {
  12308. errorInfo += error.stack;
  12309. }
  12310. if (data) {
  12311. errorInfo += '\nData: ' + JSON.stringify(data);
  12312. }
  12313. copyText(errorInfo);
  12314. }
  12315.  
  12316. end() {
  12317. setIsCancalBattle(true);
  12318. setProgress(this.terminatеReason, true);
  12319. console.log(this.terminatеReason);
  12320. this.resolve();
  12321. }
  12322. }
  12323.  
  12324. this.HWHClasses.executeAdventure = executeAdventure;
  12325.  
  12326. /**
  12327. * Passage of brawls
  12328. *
  12329. * Прохождение потасовок
  12330. */
  12331. function testBrawls(isAuto) {
  12332. const { executeBrawls } = HWHClasses;
  12333. return new Promise((resolve, reject) => {
  12334. const brawls = new executeBrawls(resolve, reject);
  12335. brawls.start(brawlsPack, isAuto);
  12336. });
  12337. }
  12338. /**
  12339. * Passage of brawls
  12340. *
  12341. * Прохождение потасовок
  12342. */
  12343. class executeBrawls {
  12344. callBrawlQuestGetInfo = {
  12345. name: "brawl_questGetInfo",
  12346. args: {},
  12347. ident: "brawl_questGetInfo"
  12348. }
  12349. callBrawlFindEnemies = {
  12350. name: "brawl_findEnemies",
  12351. args: {},
  12352. ident: "brawl_findEnemies"
  12353. }
  12354. callBrawlQuestFarm = {
  12355. name: "brawl_questFarm",
  12356. args: {},
  12357. ident: "brawl_questFarm"
  12358. }
  12359. callUserGetInfo = {
  12360. name: "userGetInfo",
  12361. args: {},
  12362. ident: "userGetInfo"
  12363. }
  12364. callTeamGetMaxUpgrade = {
  12365. name: "teamGetMaxUpgrade",
  12366. args: {},
  12367. ident: "teamGetMaxUpgrade"
  12368. }
  12369. callBrawlGetInfo = {
  12370. name: "brawl_getInfo",
  12371. args: {},
  12372. ident: "brawl_getInfo"
  12373. }
  12374.  
  12375. stats = {
  12376. win: 0,
  12377. loss: 0,
  12378. count: 0,
  12379. }
  12380.  
  12381. stage = {
  12382. '3': 1,
  12383. '7': 2,
  12384. '12': 3,
  12385. }
  12386.  
  12387. attempts = 0;
  12388.  
  12389. constructor(resolve, reject) {
  12390. this.resolve = resolve;
  12391. this.reject = reject;
  12392.  
  12393. const allHeroIds = Object.keys(lib.getData('hero'));
  12394. this.callTeamGetMaxUpgrade.args.units = {
  12395. hero: allHeroIds.filter((id) => +id < 1000),
  12396. titan: allHeroIds.filter((id) => +id >= 4000 && +id < 4100),
  12397. pet: allHeroIds.filter((id) => +id >= 6000 && +id < 6100),
  12398. };
  12399. }
  12400.  
  12401. async start(args, isAuto) {
  12402. this.isAuto = isAuto;
  12403. this.args = args;
  12404. setIsCancalBattle(false);
  12405. this.brawlInfo = await this.getBrawlInfo();
  12406. this.attempts = this.brawlInfo.attempts;
  12407.  
  12408. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12409. this.end(I18N('DONT_HAVE_LIVES'));
  12410. return;
  12411. }
  12412.  
  12413. while (1) {
  12414. if (!isBrawlsAutoStart) {
  12415. this.end(I18N('BTN_CANCELED'));
  12416. return;
  12417. }
  12418.  
  12419. const maxStage = this.brawlInfo.questInfo.stage;
  12420. const stage = this.stage[maxStage];
  12421. const progress = this.brawlInfo.questInfo.progress;
  12422.  
  12423. setProgress(
  12424. `${I18N('STAGE')} ${stage}: ${progress}/${maxStage}<br>${I18N('FIGHTS')}: ${this.stats.count}<br>${I18N('WINS')}: ${
  12425. this.stats.win
  12426. }<br>${I18N('LOSSES')}: ${this.stats.loss}<br>${I18N('LIVES')}: ${this.attempts}<br>${I18N('STOP')}`,
  12427. false,
  12428. function () {
  12429. isBrawlsAutoStart = false;
  12430. }
  12431. );
  12432.  
  12433. if (this.brawlInfo.questInfo.canFarm) {
  12434. const result = await this.questFarm();
  12435. console.log(result);
  12436. }
  12437.  
  12438. if (!this.continueAttack && this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  12439. if (
  12440. await popup.confirm(I18N('BRAWL_DAILY_TASK_COMPLETED'), [
  12441. { msg: I18N('BTN_NO'), result: true },
  12442. { msg: I18N('BTN_YES'), result: false },
  12443. ])
  12444. ) {
  12445. this.end(I18N('SUCCESS'));
  12446. return;
  12447. } else {
  12448. this.continueAttack = true;
  12449. }
  12450. }
  12451.  
  12452. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12453. this.end(I18N('DONT_HAVE_LIVES'));
  12454. return;
  12455. }
  12456.  
  12457. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  12458.  
  12459. // Автоматический подбор пачки
  12460. if (this.isAuto) {
  12461. if (this.mandatoryId <= 4000 && this.mandatoryId != 13) {
  12462. this.end(I18N('BRAWL_AUTO_PACK_NOT_CUR_HERO'));
  12463. return;
  12464. }
  12465. if (this.mandatoryId >= 4000 && this.mandatoryId < 4100) {
  12466. this.args = await this.updateTitanPack(enemie.heroes);
  12467. } else if (this.mandatoryId < 4000 && this.mandatoryId == 13) {
  12468. this.args = await this.updateHeroesPack(enemie.heroes);
  12469. }
  12470. }
  12471.  
  12472. const result = await this.battle(enemie.userId);
  12473. this.brawlInfo = {
  12474. questInfo: result[1].result.response,
  12475. findEnemies: result[2].result.response,
  12476. };
  12477. }
  12478. }
  12479.  
  12480. async updateTitanPack(enemieHeroes) {
  12481. const packs = [
  12482. [4033, 4040, 4041, 4042, 4043],
  12483. [4032, 4040, 4041, 4042, 4043],
  12484. [4031, 4040, 4041, 4042, 4043],
  12485. [4030, 4040, 4041, 4042, 4043],
  12486. [4032, 4033, 4040, 4042, 4043],
  12487. [4030, 4033, 4041, 4042, 4043],
  12488. [4031, 4033, 4040, 4042, 4043],
  12489. [4032, 4033, 4040, 4041, 4043],
  12490. [4023, 4040, 4041, 4042, 4043],
  12491. [4030, 4033, 4040, 4042, 4043],
  12492. [4031, 4033, 4040, 4041, 4043],
  12493. [4022, 4040, 4041, 4042, 4043],
  12494. [4030, 4033, 4040, 4041, 4043],
  12495. [4021, 4040, 4041, 4042, 4043],
  12496. [4020, 4040, 4041, 4042, 4043],
  12497. [4023, 4033, 4040, 4042, 4043],
  12498. [4030, 4032, 4033, 4042, 4043],
  12499. [4023, 4033, 4040, 4041, 4043],
  12500. [4031, 4032, 4033, 4040, 4043],
  12501. [4030, 4032, 4033, 4041, 4043],
  12502. [4030, 4031, 4033, 4042, 4043],
  12503. [4013, 4040, 4041, 4042, 4043],
  12504. [4030, 4032, 4033, 4040, 4043],
  12505. [4030, 4031, 4033, 4041, 4043],
  12506. [4012, 4040, 4041, 4042, 4043],
  12507. [4030, 4031, 4033, 4040, 4043],
  12508. [4011, 4040, 4041, 4042, 4043],
  12509. [4010, 4040, 4041, 4042, 4043],
  12510. [4023, 4032, 4033, 4042, 4043],
  12511. [4022, 4032, 4033, 4042, 4043],
  12512. [4023, 4032, 4033, 4041, 4043],
  12513. [4021, 4032, 4033, 4042, 4043],
  12514. [4022, 4032, 4033, 4041, 4043],
  12515. [4023, 4030, 4033, 4042, 4043],
  12516. [4023, 4032, 4033, 4040, 4043],
  12517. [4013, 4033, 4040, 4042, 4043],
  12518. [4020, 4032, 4033, 4042, 4043],
  12519. [4021, 4032, 4033, 4041, 4043],
  12520. [4022, 4030, 4033, 4042, 4043],
  12521. [4022, 4032, 4033, 4040, 4043],
  12522. [4023, 4030, 4033, 4041, 4043],
  12523. [4023, 4031, 4033, 4040, 4043],
  12524. [4013, 4033, 4040, 4041, 4043],
  12525. [4020, 4031, 4033, 4042, 4043],
  12526. [4020, 4032, 4033, 4041, 4043],
  12527. [4021, 4030, 4033, 4042, 4043],
  12528. [4021, 4032, 4033, 4040, 4043],
  12529. [4022, 4030, 4033, 4041, 4043],
  12530. [4022, 4031, 4033, 4040, 4043],
  12531. [4023, 4030, 4033, 4040, 4043],
  12532. [4030, 4031, 4032, 4033, 4043],
  12533. [4003, 4040, 4041, 4042, 4043],
  12534. [4020, 4030, 4033, 4042, 4043],
  12535. [4020, 4031, 4033, 4041, 4043],
  12536. [4020, 4032, 4033, 4040, 4043],
  12537. [4021, 4030, 4033, 4041, 4043],
  12538. [4021, 4031, 4033, 4040, 4043],
  12539. [4022, 4030, 4033, 4040, 4043],
  12540. [4030, 4031, 4032, 4033, 4042],
  12541. [4002, 4040, 4041, 4042, 4043],
  12542. [4020, 4030, 4033, 4041, 4043],
  12543. [4020, 4031, 4033, 4040, 4043],
  12544. [4021, 4030, 4033, 4040, 4043],
  12545. [4030, 4031, 4032, 4033, 4041],
  12546. [4001, 4040, 4041, 4042, 4043],
  12547. [4030, 4031, 4032, 4033, 4040],
  12548. [4000, 4040, 4041, 4042, 4043],
  12549. [4013, 4032, 4033, 4042, 4043],
  12550. [4012, 4032, 4033, 4042, 4043],
  12551. [4013, 4032, 4033, 4041, 4043],
  12552. [4023, 4031, 4032, 4033, 4043],
  12553. [4011, 4032, 4033, 4042, 4043],
  12554. [4012, 4032, 4033, 4041, 4043],
  12555. [4013, 4030, 4033, 4042, 4043],
  12556. [4013, 4032, 4033, 4040, 4043],
  12557. [4023, 4030, 4032, 4033, 4043],
  12558. [4003, 4033, 4040, 4042, 4043],
  12559. [4013, 4023, 4040, 4042, 4043],
  12560. [4010, 4032, 4033, 4042, 4043],
  12561. [4011, 4032, 4033, 4041, 4043],
  12562. [4012, 4030, 4033, 4042, 4043],
  12563. [4012, 4032, 4033, 4040, 4043],
  12564. [4013, 4030, 4033, 4041, 4043],
  12565. [4013, 4031, 4033, 4040, 4043],
  12566. [4023, 4030, 4031, 4033, 4043],
  12567. [4003, 4033, 4040, 4041, 4043],
  12568. [4013, 4023, 4040, 4041, 4043],
  12569. [4010, 4031, 4033, 4042, 4043],
  12570. [4010, 4032, 4033, 4041, 4043],
  12571. [4011, 4030, 4033, 4042, 4043],
  12572. [4011, 4032, 4033, 4040, 4043],
  12573. [4012, 4030, 4033, 4041, 4043],
  12574. [4012, 4031, 4033, 4040, 4043],
  12575. [4013, 4030, 4033, 4040, 4043],
  12576. [4010, 4030, 4033, 4042, 4043],
  12577. [4010, 4031, 4033, 4041, 4043],
  12578. [4010, 4032, 4033, 4040, 4043],
  12579. [4011, 4030, 4033, 4041, 4043],
  12580. [4011, 4031, 4033, 4040, 4043],
  12581. [4012, 4030, 4033, 4040, 4043],
  12582. [4010, 4030, 4033, 4041, 4043],
  12583. [4010, 4031, 4033, 4040, 4043],
  12584. [4011, 4030, 4033, 4040, 4043],
  12585. [4003, 4032, 4033, 4042, 4043],
  12586. [4002, 4032, 4033, 4042, 4043],
  12587. [4003, 4032, 4033, 4041, 4043],
  12588. [4013, 4031, 4032, 4033, 4043],
  12589. [4001, 4032, 4033, 4042, 4043],
  12590. [4002, 4032, 4033, 4041, 4043],
  12591. [4003, 4030, 4033, 4042, 4043],
  12592. [4003, 4032, 4033, 4040, 4043],
  12593. [4013, 4030, 4032, 4033, 4043],
  12594. [4003, 4023, 4040, 4042, 4043],
  12595. [4000, 4032, 4033, 4042, 4043],
  12596. [4001, 4032, 4033, 4041, 4043],
  12597. [4002, 4030, 4033, 4042, 4043],
  12598. [4002, 4032, 4033, 4040, 4043],
  12599. [4003, 4030, 4033, 4041, 4043],
  12600. [4003, 4031, 4033, 4040, 4043],
  12601. [4020, 4022, 4023, 4042, 4043],
  12602. [4013, 4030, 4031, 4033, 4043],
  12603. [4003, 4023, 4040, 4041, 4043],
  12604. [4000, 4031, 4033, 4042, 4043],
  12605. [4000, 4032, 4033, 4041, 4043],
  12606. [4001, 4030, 4033, 4042, 4043],
  12607. [4001, 4032, 4033, 4040, 4043],
  12608. [4002, 4030, 4033, 4041, 4043],
  12609. [4002, 4031, 4033, 4040, 4043],
  12610. [4003, 4030, 4033, 4040, 4043],
  12611. [4021, 4022, 4023, 4040, 4043],
  12612. [4020, 4022, 4023, 4041, 4043],
  12613. [4020, 4021, 4023, 4042, 4043],
  12614. [4023, 4030, 4031, 4032, 4033],
  12615. [4000, 4030, 4033, 4042, 4043],
  12616. [4000, 4031, 4033, 4041, 4043],
  12617. [4000, 4032, 4033, 4040, 4043],
  12618. [4001, 4030, 4033, 4041, 4043],
  12619. [4001, 4031, 4033, 4040, 4043],
  12620. [4002, 4030, 4033, 4040, 4043],
  12621. [4020, 4022, 4023, 4040, 4043],
  12622. [4020, 4021, 4023, 4041, 4043],
  12623. [4022, 4030, 4031, 4032, 4033],
  12624. [4000, 4030, 4033, 4041, 4043],
  12625. [4000, 4031, 4033, 4040, 4043],
  12626. [4001, 4030, 4033, 4040, 4043],
  12627. [4020, 4021, 4023, 4040, 4043],
  12628. [4021, 4030, 4031, 4032, 4033],
  12629. [4020, 4030, 4031, 4032, 4033],
  12630. [4003, 4031, 4032, 4033, 4043],
  12631. [4020, 4022, 4023, 4033, 4043],
  12632. [4003, 4030, 4032, 4033, 4043],
  12633. [4003, 4013, 4040, 4042, 4043],
  12634. [4020, 4021, 4023, 4033, 4043],
  12635. [4003, 4030, 4031, 4033, 4043],
  12636. [4003, 4013, 4040, 4041, 4043],
  12637. [4013, 4030, 4031, 4032, 4033],
  12638. [4012, 4030, 4031, 4032, 4033],
  12639. [4011, 4030, 4031, 4032, 4033],
  12640. [4010, 4030, 4031, 4032, 4033],
  12641. [4013, 4023, 4031, 4032, 4033],
  12642. [4013, 4023, 4030, 4032, 4033],
  12643. [4020, 4022, 4023, 4032, 4033],
  12644. [4013, 4023, 4030, 4031, 4033],
  12645. [4021, 4022, 4023, 4030, 4033],
  12646. [4020, 4022, 4023, 4031, 4033],
  12647. [4020, 4021, 4023, 4032, 4033],
  12648. [4020, 4021, 4022, 4023, 4043],
  12649. [4003, 4030, 4031, 4032, 4033],
  12650. [4020, 4022, 4023, 4030, 4033],
  12651. [4020, 4021, 4023, 4031, 4033],
  12652. [4020, 4021, 4022, 4023, 4042],
  12653. [4002, 4030, 4031, 4032, 4033],
  12654. [4020, 4021, 4023, 4030, 4033],
  12655. [4020, 4021, 4022, 4023, 4041],
  12656. [4001, 4030, 4031, 4032, 4033],
  12657. [4020, 4021, 4022, 4023, 4040],
  12658. [4000, 4030, 4031, 4032, 4033],
  12659. [4003, 4023, 4031, 4032, 4033],
  12660. [4013, 4020, 4022, 4023, 4043],
  12661. [4003, 4023, 4030, 4032, 4033],
  12662. [4010, 4012, 4013, 4042, 4043],
  12663. [4013, 4020, 4021, 4023, 4043],
  12664. [4003, 4023, 4030, 4031, 4033],
  12665. [4011, 4012, 4013, 4040, 4043],
  12666. [4010, 4012, 4013, 4041, 4043],
  12667. [4010, 4011, 4013, 4042, 4043],
  12668. [4020, 4021, 4022, 4023, 4033],
  12669. [4010, 4012, 4013, 4040, 4043],
  12670. [4010, 4011, 4013, 4041, 4043],
  12671. [4020, 4021, 4022, 4023, 4032],
  12672. [4010, 4011, 4013, 4040, 4043],
  12673. [4020, 4021, 4022, 4023, 4031],
  12674. [4020, 4021, 4022, 4023, 4030],
  12675. [4003, 4013, 4031, 4032, 4033],
  12676. [4010, 4012, 4013, 4033, 4043],
  12677. [4003, 4020, 4022, 4023, 4043],
  12678. [4013, 4020, 4022, 4023, 4033],
  12679. [4003, 4013, 4030, 4032, 4033],
  12680. [4010, 4011, 4013, 4033, 4043],
  12681. [4003, 4020, 4021, 4023, 4043],
  12682. [4013, 4020, 4021, 4023, 4033],
  12683. [4003, 4013, 4030, 4031, 4033],
  12684. [4010, 4012, 4013, 4023, 4043],
  12685. [4003, 4020, 4022, 4023, 4033],
  12686. [4010, 4012, 4013, 4032, 4033],
  12687. [4010, 4011, 4013, 4023, 4043],
  12688. [4003, 4020, 4021, 4023, 4033],
  12689. [4011, 4012, 4013, 4030, 4033],
  12690. [4010, 4012, 4013, 4031, 4033],
  12691. [4010, 4011, 4013, 4032, 4033],
  12692. [4013, 4020, 4021, 4022, 4023],
  12693. [4010, 4012, 4013, 4030, 4033],
  12694. [4010, 4011, 4013, 4031, 4033],
  12695. [4012, 4020, 4021, 4022, 4023],
  12696. [4010, 4011, 4013, 4030, 4033],
  12697. [4011, 4020, 4021, 4022, 4023],
  12698. [4010, 4020, 4021, 4022, 4023],
  12699. [4010, 4012, 4013, 4023, 4033],
  12700. [4000, 4002, 4003, 4042, 4043],
  12701. [4010, 4011, 4013, 4023, 4033],
  12702. [4001, 4002, 4003, 4040, 4043],
  12703. [4000, 4002, 4003, 4041, 4043],
  12704. [4000, 4001, 4003, 4042, 4043],
  12705. [4010, 4011, 4012, 4013, 4043],
  12706. [4003, 4020, 4021, 4022, 4023],
  12707. [4000, 4002, 4003, 4040, 4043],
  12708. [4000, 4001, 4003, 4041, 4043],
  12709. [4010, 4011, 4012, 4013, 4042],
  12710. [4002, 4020, 4021, 4022, 4023],
  12711. [4000, 4001, 4003, 4040, 4043],
  12712. [4010, 4011, 4012, 4013, 4041],
  12713. [4001, 4020, 4021, 4022, 4023],
  12714. [4010, 4011, 4012, 4013, 4040],
  12715. [4000, 4020, 4021, 4022, 4023],
  12716. [4001, 4002, 4003, 4033, 4043],
  12717. [4000, 4002, 4003, 4033, 4043],
  12718. [4003, 4010, 4012, 4013, 4043],
  12719. [4003, 4013, 4020, 4022, 4023],
  12720. [4000, 4001, 4003, 4033, 4043],
  12721. [4003, 4010, 4011, 4013, 4043],
  12722. [4003, 4013, 4020, 4021, 4023],
  12723. [4010, 4011, 4012, 4013, 4033],
  12724. [4010, 4011, 4012, 4013, 4032],
  12725. [4010, 4011, 4012, 4013, 4031],
  12726. [4010, 4011, 4012, 4013, 4030],
  12727. [4001, 4002, 4003, 4023, 4043],
  12728. [4000, 4002, 4003, 4023, 4043],
  12729. [4003, 4010, 4012, 4013, 4033],
  12730. [4000, 4002, 4003, 4032, 4033],
  12731. [4000, 4001, 4003, 4023, 4043],
  12732. [4003, 4010, 4011, 4013, 4033],
  12733. [4001, 4002, 4003, 4030, 4033],
  12734. [4000, 4002, 4003, 4031, 4033],
  12735. [4000, 4001, 4003, 4032, 4033],
  12736. [4010, 4011, 4012, 4013, 4023],
  12737. [4000, 4002, 4003, 4030, 4033],
  12738. [4000, 4001, 4003, 4031, 4033],
  12739. [4010, 4011, 4012, 4013, 4022],
  12740. [4000, 4001, 4003, 4030, 4033],
  12741. [4010, 4011, 4012, 4013, 4021],
  12742. [4010, 4011, 4012, 4013, 4020],
  12743. [4001, 4002, 4003, 4013, 4043],
  12744. [4001, 4002, 4003, 4023, 4033],
  12745. [4000, 4002, 4003, 4013, 4043],
  12746. [4000, 4002, 4003, 4023, 4033],
  12747. [4003, 4010, 4012, 4013, 4023],
  12748. [4000, 4001, 4003, 4013, 4043],
  12749. [4000, 4001, 4003, 4023, 4033],
  12750. [4003, 4010, 4011, 4013, 4023],
  12751. [4001, 4002, 4003, 4013, 4033],
  12752. [4000, 4002, 4003, 4013, 4033],
  12753. [4000, 4001, 4003, 4013, 4033],
  12754. [4000, 4001, 4002, 4003, 4043],
  12755. [4003, 4010, 4011, 4012, 4013],
  12756. [4000, 4001, 4002, 4003, 4042],
  12757. [4002, 4010, 4011, 4012, 4013],
  12758. [4000, 4001, 4002, 4003, 4041],
  12759. [4001, 4010, 4011, 4012, 4013],
  12760. [4000, 4001, 4002, 4003, 4040],
  12761. [4000, 4010, 4011, 4012, 4013],
  12762. [4001, 4002, 4003, 4013, 4023],
  12763. [4000, 4002, 4003, 4013, 4023],
  12764. [4000, 4001, 4003, 4013, 4023],
  12765. [4000, 4001, 4002, 4003, 4033],
  12766. [4000, 4001, 4002, 4003, 4032],
  12767. [4000, 4001, 4002, 4003, 4031],
  12768. [4000, 4001, 4002, 4003, 4030],
  12769. [4000, 4001, 4002, 4003, 4023],
  12770. [4000, 4001, 4002, 4003, 4022],
  12771. [4000, 4001, 4002, 4003, 4021],
  12772. [4000, 4001, 4002, 4003, 4020],
  12773. [4000, 4001, 4002, 4003, 4013],
  12774. [4000, 4001, 4002, 4003, 4012],
  12775. [4000, 4001, 4002, 4003, 4011],
  12776. [4000, 4001, 4002, 4003, 4010],
  12777. ].filter((p) => p.includes(this.mandatoryId));
  12778.  
  12779. const bestPack = {
  12780. pack: packs[0],
  12781. winRate: 0,
  12782. countBattle: 0,
  12783. id: 0,
  12784. };
  12785.  
  12786. for (const id in packs) {
  12787. const pack = packs[id];
  12788. const attackers = this.maxUpgrade.filter((e) => pack.includes(e.id)).reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  12789. const battle = {
  12790. attackers,
  12791. defenders: [enemieHeroes],
  12792. type: 'brawl_titan',
  12793. };
  12794. const isRandom = this.isRandomBattle(battle);
  12795. const stat = {
  12796. count: 0,
  12797. win: 0,
  12798. winRate: 0,
  12799. };
  12800. for (let i = 1; i <= 20; i++) {
  12801. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12802. const result = await Calc(battle);
  12803. stat.win += result.result.win;
  12804. stat.count += 1;
  12805. stat.winRate = stat.win / stat.count;
  12806. if (!isRandom || (i >= 2 && stat.winRate < 0.65) || (i >= 10 && stat.winRate == 1)) {
  12807. break;
  12808. }
  12809. }
  12810.  
  12811. if (!isRandom && stat.win) {
  12812. return {
  12813. favor: {},
  12814. heroes: pack,
  12815. };
  12816. }
  12817. if (stat.winRate > 0.85) {
  12818. return {
  12819. favor: {},
  12820. heroes: pack,
  12821. };
  12822. }
  12823. if (stat.winRate > bestPack.winRate) {
  12824. bestPack.countBattle = stat.count;
  12825. bestPack.winRate = stat.winRate;
  12826. bestPack.pack = pack;
  12827. bestPack.id = id;
  12828. }
  12829. }
  12830.  
  12831. //console.log(bestPack.id, bestPack.pack, bestPack.winRate, bestPack.countBattle);
  12832. return {
  12833. favor: {},
  12834. heroes: bestPack.pack,
  12835. };
  12836. }
  12837.  
  12838. isRandomPack(pack) {
  12839. const ids = Object.keys(pack);
  12840. return ids.includes('4023') || ids.includes('4021');
  12841. }
  12842.  
  12843. isRandomBattle(battle) {
  12844. return this.isRandomPack(battle.attackers) || this.isRandomPack(battle.defenders[0]);
  12845. }
  12846.  
  12847. async updateHeroesPack(enemieHeroes) {
  12848. 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}}}];
  12849.  
  12850. const bestPack = {
  12851. pack: packs[0],
  12852. countWin: 0,
  12853. }
  12854.  
  12855. for (const pack of packs) {
  12856. const attackers = pack.attackers;
  12857. const battle = {
  12858. attackers,
  12859. defenders: [enemieHeroes],
  12860. type: 'brawl',
  12861. };
  12862.  
  12863. let countWinBattles = 0;
  12864. let countTestBattle = 10;
  12865. for (let i = 0; i < countTestBattle; i++) {
  12866. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12867. const result = await Calc(battle);
  12868. if (result.result.win) {
  12869. countWinBattles++;
  12870. }
  12871. if (countWinBattles > 7) {
  12872. console.log(pack)
  12873. return pack.args;
  12874. }
  12875. }
  12876. if (countWinBattles > bestPack.countWin) {
  12877. bestPack.countWin = countWinBattles;
  12878. bestPack.pack = pack.args;
  12879. }
  12880. }
  12881.  
  12882. console.log(bestPack);
  12883. return bestPack.pack;
  12884. }
  12885.  
  12886. async questFarm() {
  12887. const calls = [this.callBrawlQuestFarm];
  12888. const result = await Send(JSON.stringify({ calls }));
  12889. return result.results[0].result.response;
  12890. }
  12891.  
  12892. async getBrawlInfo() {
  12893. const data = await Send(JSON.stringify({
  12894. calls: [
  12895. this.callUserGetInfo,
  12896. this.callBrawlQuestGetInfo,
  12897. this.callBrawlFindEnemies,
  12898. this.callTeamGetMaxUpgrade,
  12899. this.callBrawlGetInfo,
  12900. ]
  12901. }));
  12902.  
  12903. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  12904.  
  12905. const maxUpgrade = data.results[3].result.response;
  12906. const maxHero = Object.values(maxUpgrade.hero);
  12907. const maxTitan = Object.values(maxUpgrade.titan);
  12908. const maxPet = Object.values(maxUpgrade.pet);
  12909. this.maxUpgrade = [...maxHero, ...maxPet, ...maxTitan];
  12910.  
  12911. this.info = data.results[4].result.response;
  12912. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  12913. return {
  12914. attempts: attempts.amount,
  12915. questInfo: data.results[1].result.response,
  12916. findEnemies: data.results[2].result.response,
  12917. }
  12918. }
  12919.  
  12920. /**
  12921. * Carrying out a fight
  12922. *
  12923. * Проведение боя
  12924. */
  12925. async battle(userId) {
  12926. this.stats.count++;
  12927. const battle = await this.startBattle(userId, this.args);
  12928. const result = await Calc(battle);
  12929. console.log(result.result);
  12930. if (result.result.win) {
  12931. this.stats.win++;
  12932. } else {
  12933. this.stats.loss++;
  12934. if (!this.info.boughtEndlessLivesToday) {
  12935. this.attempts--;
  12936. }
  12937. }
  12938. return await this.endBattle(result);
  12939. // return await this.cancelBattle(result);
  12940. }
  12941.  
  12942. /**
  12943. * Starts a fight
  12944. *
  12945. * Начинает бой
  12946. */
  12947. async startBattle(userId, args) {
  12948. const call = {
  12949. name: "brawl_startBattle",
  12950. args,
  12951. ident: "brawl_startBattle"
  12952. }
  12953. call.args.userId = userId;
  12954. const calls = [call];
  12955. const result = await Send(JSON.stringify({ calls }));
  12956. return result.results[0].result.response;
  12957. }
  12958.  
  12959. cancelBattle(battle) {
  12960. const fixBattle = function (heroes) {
  12961. for (const ids in heroes) {
  12962. const hero = heroes[ids];
  12963. hero.energy = random(1, 999);
  12964. if (hero.hp > 0) {
  12965. hero.hp = random(1, hero.hp);
  12966. }
  12967. }
  12968. }
  12969. fixBattle(battle.progress[0].attackers.heroes);
  12970. fixBattle(battle.progress[0].defenders.heroes);
  12971. return this.endBattle(battle);
  12972. }
  12973.  
  12974. /**
  12975. * Ends the fight
  12976. *
  12977. * Заканчивает бой
  12978. */
  12979. async endBattle(battle) {
  12980. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  12981. const calls = [{
  12982. name: "brawl_endBattle",
  12983. args: {
  12984. result: battle.result,
  12985. progress: battle.progress
  12986. },
  12987. ident: "brawl_endBattle"
  12988. },
  12989. this.callBrawlQuestGetInfo,
  12990. this.callBrawlFindEnemies,
  12991. ];
  12992. const result = await Send(JSON.stringify({ calls }));
  12993. return result.results;
  12994. }
  12995.  
  12996. end(endReason) {
  12997. setIsCancalBattle(true);
  12998. isBrawlsAutoStart = false;
  12999. setProgress(endReason, true);
  13000. console.log(endReason);
  13001. this.resolve();
  13002. }
  13003. }
  13004.  
  13005. this.HWHClasses.executeBrawls = executeBrawls;
  13006.  
  13007. })();
  13008.  
  13009. /**
  13010. * TODO:
  13011. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  13012. * Добивание на арене титанов
  13013. * Закрытие окошек по Esc +-
  13014. * Починить работу скрипта на уровне команды ниже 10 +-
  13015. * Написать номальную синхронизацию
  13016. * Запрет сбора квестов и отправки экспеиций в промежуток между локальным обновлением и глобальным обновлением дня
  13017. * Улучшение боев
  13018. */